Debian Codegraph @

seccomp.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // Public API specification for libseccomp Go bindings
2 // Contains public API for the bindings
3
4 // Package seccomp provides bindings for libseccomp, a library wrapping the Linux
5 // seccomp syscall. Seccomp enables an application to restrict system call use
6 // for itself and its children.
7 package seccomp
8
9 import (
10 "errors"
11 "fmt"
12 "os"
13 "runtime"
14 "strings"
15 "sync"
16 "syscall"
17 "unsafe"
18 )
19
20 /*
21 #include <errno.h>
22 #include <stdlib.h>
23 #include <seccomp.h>
24
25 // The following functions were added in libseccomp v2.6.0.
26 #if SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 6
27 int seccomp_precompute(scmp_filter_ctx ctx) {
28 return -EOPNOTSUPP;
29 }
30 int seccomp_export_bpf_mem(const scmp_filter_ctx ctx, void *buf, size_t *len) {
31 return -EOPNOTSUPP;
32 }
33 int seccomp_transaction_start(const scmp_filter_ctx ctx) {
34 return -EOPNOTSUPP;
35 }
36 int seccomp_transaction_commit(const scmp_filter_ctx ctx) {
37 return -EOPNOTSUPP;
38 }
39 void seccomp_transaction_reject(const scmp_filter_ctx ctx) {}
40 #endif
41 */
42 import "C"
43
44 // Exported types
45
46 // VersionError represents an error when either the system libseccomp version
47 // or the kernel version is too old to perform the operation requested.
48 type VersionError struct {
49 op string // operation that failed or would fail
50 major, minor, micro uint // minimally required libseccomp version
51 curAPI, minAPI uint // current and minimally required API versions
52 }
53
54 func init() {
55 // This forces the cgo libseccomp to initialize its internal API support state,
56 // which is necessary on older versions of libseccomp (< 2.5.0) in order to work
57 // correctly.
58 // TODO: remove once libseccomp < v2.5.0 is not supported.
59 _, _ = getAPI()
60 }
61
62 func (e VersionError) Error() string {
63 if e.minAPI != 0 {
64 return fmt.Sprintf("%s requires libseccomp >= %d.%d.%d and API level >= %d "+
65 "(current version: %d.%d.%d, API level: %d)",
66 e.op, e.major, e.minor, e.micro, e.minAPI,
67 verMajor, verMinor, verMicro, e.curAPI)
68 }
69 return fmt.Sprintf("%s requires libseccomp >= %d.%d.%d (current version: %d.%d.%d)",
70 e.op, e.major, e.minor, e.micro, verMajor, verMinor, verMicro)
71 }
72
73 // ScmpArch represents a CPU architecture. Seccomp can restrict syscalls on a
74 // per-architecture basis.
75 type ScmpArch uint
76
77 // ScmpAction represents an action to be taken on a filter rule match in
78 // libseccomp
79 type ScmpAction uint
80
81 // ScmpCompareOp represents a comparison operator which can be used in a filter
82 // rule
83 type ScmpCompareOp uint
84
85 // ScmpCondition represents a rule in a libseccomp filter context
86 type ScmpCondition struct {
87 Argument uint `json:"argument,omitempty"`
88 Op ScmpCompareOp `json:"operator,omitempty"`
89 Operand1 uint64 `json:"operand_one,omitempty"`
90 Operand2 uint64 `json:"operand_two,omitempty"`
91 }
92
93 // Seccomp userspace notification structures associated with filters that use the ActNotify action.
94
95 // ScmpSyscall identifies a Linux System Call by its number.
96 type ScmpSyscall int32
97
98 // ScmpFd represents a file-descriptor used for seccomp userspace notifications.
99 type ScmpFd int32
100
101 // ScmpNotifData describes the system call context that triggered a notification.
102 type ScmpNotifData struct {
103 // Syscall is the syscall number.
104 Syscall ScmpSyscall `json:"syscall,omitempty"`
105 // Arch is the filter architecture.
106 Arch ScmpArch `json:"arch,omitempty"`
107 // InstrPointer is the address of the instruction that triggered a notification.
108 InstrPointer uint64 `json:"instr_pointer,omitempty"`
109 // Args are the arguments (up to 6) for the syscall.
110 Args []uint64 `json:"args,omitempty"`
111 }
112
113 // ScmpNotifReq represents a seccomp userspace notification. See NotifReceive() for
114 // info on how to pull such a notification.
115 type ScmpNotifReq struct {
116 // ID is the notification ID.
117 ID uint64 `json:"id,omitempty"`
118 // Pid is the process that triggered the notification event.
119 Pid uint32 `json:"pid,omitempty"`
120 // Flags is filter flags (see seccomp(2)).
121 Flags uint32 `json:"flags,omitempty"`
122 // Data is system call context that triggered the notification.
123 Data ScmpNotifData `json:"data,omitempty"`
124 }
125
126 // ScmpNotifResp represents a seccomp userspace notification response. See NotifRespond()
127 // for info on how to push such a response.
128 type ScmpNotifResp struct {
129 // ID is the notification ID (must match the corresponding ScmpNotifReq ID).
130 ID uint64 `json:"id,omitempty"`
131 // Error must be 0 if no error occurred, or an error constant from
132 // package syscall (e.g., syscall.EPERM, etc). In the latter case, it
133 // is used as an error return from the syscall that created the
134 // notification.
135 Error int32 `json:"error,omitempty"`
136 // Val is a return value for the syscall that created the notification.
137 // Only relevant if Error is 0.
138 Val uint64 `json:"val,omitempty"`
139 // Flags is userspace notification response flag (e.g., NotifRespFlagContinue).
140 Flags uint32 `json:"flags,omitempty"`
141 }
142
143 // Exported Constants
144
145 const (
146 // Valid architectures recognized by libseccomp
147 // PowerPC and S390(x) architectures are unavailable below library version
148 // v2.3.0 and will returns errors if used with incompatible libraries
149
150 // ArchInvalid is a placeholder to ensure uninitialized ScmpArch
151 // variables are invalid
152 ArchInvalid ScmpArch = iota
153 // ArchNative is the native architecture of the kernel
154 ArchNative
155 // ArchX86 represents 32-bit x86 syscalls
156 ArchX86
157 // ArchAMD64 represents 64-bit x86-64 syscalls
158 ArchAMD64
159 // ArchX32 represents 64-bit x86-64 syscalls (32-bit pointers)
160 ArchX32
161 // ArchARM represents 32-bit ARM syscalls
162 ArchARM
163 // ArchARM64 represents 64-bit ARM syscalls
164 ArchARM64
165 // ArchMIPS represents 32-bit MIPS syscalls
166 ArchMIPS
167 // ArchMIPS64 represents 64-bit MIPS syscalls
168 ArchMIPS64
169 // ArchMIPS64N32 represents 64-bit MIPS syscalls (32-bit pointers)
170 ArchMIPS64N32
171 // ArchMIPSEL represents 32-bit MIPS syscalls (little endian)
172 ArchMIPSEL
173 // ArchMIPSEL64 represents 64-bit MIPS syscalls (little endian)
174 ArchMIPSEL64
175 // ArchMIPSEL64N32 represents 64-bit MIPS syscalls (little endian,
176 // 32-bit pointers)
177 ArchMIPSEL64N32
178 // ArchPPC represents 32-bit POWERPC syscalls
179 ArchPPC
180 // ArchPPC64 represents 64-bit POWER syscalls (big endian)
181 ArchPPC64
182 // ArchPPC64LE represents 64-bit POWER syscalls (little endian)
183 ArchPPC64LE
184 // ArchS390 represents 31-bit System z/390 syscalls
185 ArchS390
186 // ArchS390X represents 64-bit System z/390 syscalls
187 ArchS390X
188 // ArchPARISC represents 32-bit PA-RISC
189 ArchPARISC
190 // ArchPARISC64 represents 64-bit PA-RISC
191 ArchPARISC64
192 // ArchRISCV64 represents RISCV64
193 ArchRISCV64
194 // ArchLOONGARCH64 represents 64-bit LoongArch.
195 ArchLOONGARCH64
196 // ArchM68K represents 32-bit Motorola 68000.
197 ArchM68K
198 // ArchSH represents SuperH.
199 ArchSH
200 // ArchSHEB represents Big-endian SuperH.
201 ArchSHEB
202 )
203
204 const (
205 // Supported actions on filter match
206
207 // ActInvalid is a placeholder to ensure uninitialized ScmpAction
208 // variables are invalid
209 ActInvalid ScmpAction = iota
210 // ActKillThread kills the thread that violated the rule.
211 // All other threads from the same thread group will continue to execute.
212 ActKillThread
213 // ActTrap throws SIGSYS
214 ActTrap
215 // ActNotify triggers a userspace notification. This action is only usable when
216 // libseccomp API level 6 or higher is supported.
217 ActNotify
218 // ActErrno causes the syscall to return a negative error code. This
219 // code can be set with the SetReturnCode method
220 ActErrno
221 // ActTrace causes the syscall to notify tracing processes with the
222 // given error code. This code can be set with the SetReturnCode method
223 ActTrace
224 // ActAllow permits the syscall to continue execution
225 ActAllow
226 // ActLog permits the syscall to continue execution after logging it.
227 // This action is only usable when libseccomp API level 3 or higher is
228 // supported.
229 ActLog
230 // ActKillProcess kills the process that violated the rule.
231 // All threads in the thread group are also terminated.
232 // This action is only usable when libseccomp API level 3 or higher is
233 // supported.
234 ActKillProcess
235 // ActKill kills the thread that violated the rule.
236 // All other threads from the same thread group will continue to execute.
237 //
238 // Deprecated: use ActKillThread
239 ActKill = ActKillThread
240 )
241
242 const (
243 // These are comparison operators used in conditional seccomp rules
244 // They are used to compare the value of a single argument of a syscall
245 // against a user-defined constant
246
247 // CompareInvalid is a placeholder to ensure uninitialized ScmpCompareOp
248 // variables are invalid
249 CompareInvalid ScmpCompareOp = iota
250 // CompareNotEqual returns true if the argument is not equal to the
251 // given value
252 CompareNotEqual
253 // CompareLess returns true if the argument is less than the given value
254 CompareLess
255 // CompareLessOrEqual returns true if the argument is less than or equal
256 // to the given value
257 CompareLessOrEqual
258 // CompareEqual returns true if the argument is equal to the given value
259 CompareEqual
260 // CompareGreaterEqual returns true if the argument is greater than or
261 // equal to the given value
262 CompareGreaterEqual
263 // CompareGreater returns true if the argument is greater than the given
264 // value
265 CompareGreater
266 // CompareMaskedEqual returns true if the masked argument value is
267 // equal to the masked datum value. Mask is the first argument, and
268 // datum is the second one.
269 CompareMaskedEqual
270 )
271
272 // ErrSyscallDoesNotExist represents an error condition where
273 // libseccomp is unable to resolve the syscall.
274 var ErrSyscallDoesNotExist = errors.New("could not resolve syscall name")
275
276 const (
277 // Userspace notification response flags
278
279 // NotifRespFlagContinue tells the kernel to continue executing the system
280 // call that triggered the notification. Must only be used when the notification
281 // response's error is 0.
282 NotifRespFlagContinue uint32 = 1
283 )
284
285 // Helpers for types
286
287 // GetArchFromString returns an ScmpArch constant from a string representing an
288 // architecture
289 func GetArchFromString(arch string) (ScmpArch, error) {
290 if err := ensureSupportedVersion(); err != nil {
291 return ArchInvalid, err
292 }
293
294 switch strings.ToLower(arch) {
295 case "x86":
296 return ArchX86, nil
297 case "amd64", "x86-64", "x86_64", "x64":
298 return ArchAMD64, nil
299 case "x32":
300 return ArchX32, nil
301 case "arm":
302 return ArchARM, nil
303 case "arm64", "aarch64":
304 return ArchARM64, nil
305 case "mips":
306 return ArchMIPS, nil
307 case "mips64":
308 return ArchMIPS64, nil
309 case "mips64n32":
310 return ArchMIPS64N32, nil
311 case "mipsel":
312 return ArchMIPSEL, nil
313 case "mipsel64":
314 return ArchMIPSEL64, nil
315 case "mipsel64n32":
316 return ArchMIPSEL64N32, nil
317 case "ppc":
318 return ArchPPC, nil
319 case "ppc64":
320 return ArchPPC64, nil
321 case "ppc64le":
322 return ArchPPC64LE, nil
323 case "s390":
324 return ArchS390, nil
325 case "s390x":
326 return ArchS390X, nil
327 case "parisc":
328 return ArchPARISC, nil
329 case "parisc64":
330 return ArchPARISC64, nil
331 case "riscv64":
332 return ArchRISCV64, nil
333 case "loong64", "loongarch64":
334 return ArchLOONGARCH64, nil
335 case "m68k":
336 return ArchM68K, nil
337 case "sh":
338 return ArchSH, nil
339 case "sheb":
340 return ArchSHEB, nil
341 default:
342 return ArchInvalid, fmt.Errorf("cannot convert unrecognized string %q", arch)
343 }
344 }
345
346 // String returns a string representation of an architecture constant
347 func (a ScmpArch) String() string {
348 switch a {
349 case ArchX86:
350 return "x86"
351 case ArchAMD64:
352 return "amd64"
353 case ArchX32:
354 return "x32"
355 case ArchARM:
356 return "arm"
357 case ArchARM64:
358 return "arm64"
359 case ArchMIPS:
360 return "mips"
361 case ArchMIPS64:
362 return "mips64"
363 case ArchMIPS64N32:
364 return "mips64n32"
365 case ArchMIPSEL:
366 return "mipsel"
367 case ArchMIPSEL64:
368 return "mipsel64"
369 case ArchMIPSEL64N32:
370 return "mipsel64n32"
371 case ArchPPC:
372 return "ppc"
373 case ArchPPC64:
374 return "ppc64"
375 case ArchPPC64LE:
376 return "ppc64le"
377 case ArchS390:
378 return "s390"
379 case ArchS390X:
380 return "s390x"
381 case ArchPARISC:
382 return "parisc"
383 case ArchPARISC64:
384 return "parisc64"
385 case ArchRISCV64:
386 return "riscv64"
387 case ArchLOONGARCH64:
388 return "loong64"
389 case ArchM68K:
390 return "m68k"
391 case ArchSH:
392 return "sh"
393 case ArchSHEB:
394 return "sheb"
395 case ArchNative:
396 return "native"
397 case ArchInvalid:
398 return "Invalid architecture"
399 default:
400 return fmt.Sprintf("Unknown architecture %#x", uint(a))
401 }
402 }
403
404 // String returns a string representation of a comparison operator constant
405 func (a ScmpCompareOp) String() string {
406 switch a {
407 case CompareNotEqual:
408 return "Not equal"
409 case CompareLess:
410 return "Less than"
411 case CompareLessOrEqual:
412 return "Less than or equal to"
413 case CompareEqual:
414 return "Equal"
415 case CompareGreaterEqual:
416 return "Greater than or equal to"
417 case CompareGreater:
418 return "Greater than"
419 case CompareMaskedEqual:
420 return "Masked equality"
421 case CompareInvalid:
422 return "Invalid comparison operator"
423 default:
424 return fmt.Sprintf("Unrecognized comparison operator %#x", uint(a))
425 }
426 }
427
428 // String returns a string representation of a seccomp match action
429 func (a ScmpAction) String() string {
430 switch a & 0xFFFF {
431 case ActKillThread:
432 return "Action: Kill thread"
433 case ActKillProcess:
434 return "Action: Kill process"
435 case ActTrap:
436 return "Action: Send SIGSYS"
437 case ActErrno:
438 return fmt.Sprintf("Action: Return error code %d", (a >> 16))
439 case ActTrace:
440 return fmt.Sprintf("Action: Notify tracing processes with code %d",
441 (a >> 16))
442 case ActNotify:
443 return "Action: Notify userspace"
444 case ActLog:
445 return "Action: Log system call"
446 case ActAllow:
447 return "Action: Allow system call"
448 default:
449 return fmt.Sprintf("Unrecognized Action %#x", uint(a))
450 }
451 }
452
453 // SetReturnCode adds a return code to a supporting ScmpAction, clearing any
454 // existing code Only valid on ActErrno and ActTrace. Takes no action otherwise.
455 // Accepts 16-bit return code as argument.
456 // Returns a valid ScmpAction of the original type with the new error code set.
457 func (a ScmpAction) SetReturnCode(code int16) ScmpAction {
458 aTmp := a & 0x0000FFFF
459 if aTmp == ActErrno || aTmp == ActTrace {
460 return (aTmp | (ScmpAction(code)&0xFFFF)<<16)
461 }
462 return a
463 }
464
465 // GetReturnCode returns the return code of an ScmpAction
466 func (a ScmpAction) GetReturnCode() int16 {
467 return int16(a >> 16)
468 }
469
470 // General utility functions
471
472 // GetLibraryVersion returns the version of the library the bindings are built
473 // against.
474 // The version is formatted as follows: Major.Minor.Micro
475 func GetLibraryVersion() (major, minor, micro uint) {
476 return verMajor, verMinor, verMicro
477 }
478
479 // GetAPI returns the API level supported by the system.
480 // Returns a positive int containing the API level, or 0 with an error if the
481 // API level could not be detected due to the library being older than v2.4.0.
482 // See the seccomp_api_get(3) man page for details on available API levels:
483 // https://github.com/seccomp/libseccomp/blob/main/doc/man/man3/seccomp_api_get.3
484 func GetAPI() (uint, error) {
485 return getAPI()
486 }
487
•488 func GetApi() (uint, error) {
489 return getAPI()
490 }
491
492 // SetAPI forcibly sets the API level. General use of this function is strongly
493 // discouraged.
494 // Returns an error if the API level could not be set. An error is always
495 // returned if the library is older than v2.4.0
496 // See the seccomp_api_get(3) man page for details on available API levels:
497 // https://github.com/seccomp/libseccomp/blob/main/doc/man/man3/seccomp_api_get.3
498 func SetAPI(api uint) error {
499 return setAPI(api)
500 }
501
502 // Syscall functions
503
504 // GetName retrieves the name of a syscall from its number.
505 // Acts on any syscall number.
506 // Returns either a string containing the name of the syscall, or an error.
507 func (s ScmpSyscall) GetName() (string, error) {
508 return s.GetNameByArch(ArchNative)
509 }
510
511 // GetNameByArch retrieves the name of a syscall from its number for a given
512 // architecture.
513 // Acts on any syscall number.
514 // Accepts a valid architecture constant.
515 // Returns either a string containing the name of the syscall, or an error.
516 // if the syscall is unrecognized or an issue occurred.
517 func (s ScmpSyscall) GetNameByArch(arch ScmpArch) (string, error) {
518 if err := sanitizeArch(arch); err != nil {
519 return "", err
520 }
521
522 cString := C.seccomp_syscall_resolve_num_arch(arch.toNative(), C.int(s))
523 if cString == nil {
524 return "", ErrSyscallDoesNotExist
525 }
526 defer C.free(unsafe.Pointer(cString))
527
528 finalStr := C.GoString(cString)
529 return finalStr, nil
530 }
531
532 // GetSyscallFromName returns the number of a syscall by name on the kernel's
533 // native architecture.
534 // Accepts a string containing the name of a syscall.
535 // Returns the number of the syscall, or an error if no syscall with that name
536 // was found.
537 func GetSyscallFromName(name string) (ScmpSyscall, error) {
538 if err := ensureSupportedVersion(); err != nil {
539 return 0, err
540 }
541
542 cString := C.CString(name)
543 defer C.free(unsafe.Pointer(cString))
544
545 result := C.seccomp_syscall_resolve_name(cString)
546 if result == scmpError {
547 return 0, ErrSyscallDoesNotExist
548 }
549
550 return ScmpSyscall(result), nil
551 }
552
553 // GetSyscallFromNameByArch returns the number of a syscall by name for a given
554 // architecture's ABI.
555 // Accepts the name of a syscall and an architecture constant.
556 // Returns the number of the syscall, or an error if an invalid architecture is
557 // passed or a syscall with that name was not found.
558 func GetSyscallFromNameByArch(name string, arch ScmpArch) (ScmpSyscall, error) {
559 if err := ensureSupportedVersion(); err != nil {
560 return 0, err
561 }
562 if err := sanitizeArch(arch); err != nil {
563 return 0, err
564 }
565
566 cString := C.CString(name)
567 defer C.free(unsafe.Pointer(cString))
568
569 result := C.seccomp_syscall_resolve_name_arch(arch.toNative(), cString)
570 if result == scmpError {
571 return 0, ErrSyscallDoesNotExist
572 }
573
574 return ScmpSyscall(result), nil
575 }
576
577 // MakeCondition creates and returns a new condition to attach to a filter rule.
578 // Associated rules will only match if this condition is true.
579 // Accepts the number the argument we are checking, and a comparison operator
580 // and value to compare to.
581 // The rule will match if argument $arg (zero-indexed) of the syscall is
582 // $COMPARE_OP the provided comparison value.
583 // Some comparison operators accept two values. Masked equals, for example,
584 // will mask $arg of the syscall with the second value provided (via bitwise
585 // AND) and then compare against the first value provided.
586 // For example, in the less than or equal case, if the syscall argument was
587 // 0 and the value provided was 1, the condition would match, as 0 is less
588 // than or equal to 1.
589 // Return either an error on bad argument or a valid ScmpCondition struct.
590 func MakeCondition(arg uint, comparison ScmpCompareOp, values ...uint64) (ScmpCondition, error) {
591 var condStruct ScmpCondition
592
593 if err := ensureSupportedVersion(); err != nil {
594 return condStruct, err
595 }
596
597 if err := sanitizeCompareOp(comparison); err != nil {
598 return condStruct, err
599 } else if arg > 5 {
600 return condStruct, fmt.Errorf("syscalls only have up to 6 arguments (%d given)", arg)
601 } else if len(values) > 2 {
602 return condStruct, fmt.Errorf("conditions can have at most 2 arguments (%d given)", len(values))
603 } else if len(values) == 0 {
604 return condStruct, errors.New("must provide at least one value to compare against")
605 }
606
607 condStruct.Argument = arg
608 condStruct.Op = comparison
609 condStruct.Operand1 = values[0]
610 if len(values) == 2 {
611 condStruct.Operand2 = values[1]
612 } else {
613 condStruct.Operand2 = 0 // Unused
614 }
615
616 return condStruct, nil
617 }
618
619 // Utility Functions
620
621 // GetNativeArch returns architecture token representing the native kernel
622 // architecture
623 func GetNativeArch() (ScmpArch, error) {
624 if err := ensureSupportedVersion(); err != nil {
625 return ArchInvalid, err
626 }
627
628 arch := C.seccomp_arch_native()
629
630 return archFromNative(arch)
631 }
632
633 // Public Filter API
634
635 // ScmpFilter represents a filter context in libseccomp.
636 // A filter context is initially empty. Rules can be added to it, and it can
637 // then be loaded into the kernel.
638 type ScmpFilter struct {
639 filterCtx C.scmp_filter_ctx
640 valid bool
641 lock sync.Mutex
642 }
643
644 // NewFilter creates and returns a new filter context. Accepts a default action to be
645 // taken for syscalls which match no rules in the filter.
646 // Returns a reference to a valid filter context, or nil and an error
647 // if the filter context could not be created or an invalid default action was given.
648 func NewFilter(defaultAction ScmpAction) (*ScmpFilter, error) {
649 if err := ensureSupportedVersion(); err != nil {
650 return nil, err
651 }
652
653 if err := sanitizeAction(defaultAction); err != nil {
654 return nil, err
655 }
656
657 fPtr := C.seccomp_init(defaultAction.toNative())
658 if fPtr == nil {
659 return nil, errors.New("could not create filter")
660 }
661
662 filter := new(ScmpFilter)
663 filter.filterCtx = fPtr
664 filter.valid = true
665 runtime.SetFinalizer(filter, filterFinalizer)
666
667 // Enable TSync so all goroutines will receive the same rules.
668 // If the kernel does not support TSYNC, allow us to continue without error.
669 if err := filter.setFilterAttr(filterAttrTsync, 0x1); err != nil && err != syscall.ENOTSUP {
670 filter.Release()
671 return nil, fmt.Errorf("could not create filter: error setting tsync bit: %w", err)
672 }
673
674 return filter, nil
675 }
676
677 // IsValid determines whether a filter context is valid to use.
678 // Some operations (Release and Merge) render filter contexts invalid and
679 // consequently prevent further use.
680 func (f *ScmpFilter) IsValid() bool {
681 f.lock.Lock()
682 defer f.lock.Unlock()
683
684 return f.valid
685 }
686
687 // Reset resets a filter context, removing all its existing state.
688 // Accepts a new default action to be taken for syscalls which do not match.
689 // Returns an error if the filter or action provided are invalid.
690 func (f *ScmpFilter) Reset(defaultAction ScmpAction) error {
691 f.lock.Lock()
692 defer f.lock.Unlock()
693
694 if err := sanitizeAction(defaultAction); err != nil {
695 return err
696 } else if !f.valid {
697 return errBadFilter
698 }
699
700 if retCode := C.seccomp_reset(f.filterCtx, defaultAction.toNative()); retCode != 0 {
701 return errRc(retCode)
702 }
703
704 return nil
705 }
706
707 // Release releases a filter context, freeing its memory. Should be called after
708 // loading into the kernel, when the filter is no longer needed.
709 // After calling this function, the given filter is no longer valid and cannot
710 // be used.
711 // Release() will be invoked automatically when a filter context is garbage
712 // collected, but can also be called manually to free memory.
713 func (f *ScmpFilter) Release() {
714 f.lock.Lock()
715 defer f.lock.Unlock()
716
717 if !f.valid {
718 return
719 }
720
721 f.valid = false
722 C.seccomp_release(f.filterCtx)
723 }
724
725 // Merge merges two filter contexts.
726 // The source filter src will be released as part of the process, and will no
727 // longer be usable or valid after this call.
728 // To be merged, filters must NOT share any architectures, and all their
729 // attributes (Default Action, Bad Arch Action, and No New Privs bools)
730 // must match.
731 // The filter src will be merged into the filter this is called on.
732 // The architectures of the src filter not present in the destination, and all
733 // associated rules, will be added to the destination.
734 // Returns an error if merging the filters failed.
735 func (f *ScmpFilter) Merge(src *ScmpFilter) error {
736 f.lock.Lock()
737 defer f.lock.Unlock()
738
739 src.lock.Lock()
740 defer src.lock.Unlock()
741
742 if !src.valid || !f.valid {
743 return errors.New("one or more of the filter contexts is invalid or uninitialized")
744 }
745
746 // Merge the filters
747 if retCode := C.seccomp_merge(f.filterCtx, src.filterCtx); retCode != 0 {
748 e := errRc(retCode)
749 if e == syscall.EINVAL {
750 return fmt.Errorf("filters could not be merged due to a mismatch in attributes or invalid filter: %w", e)
751 }
752 return e
753 }
754
755 src.valid = false
756
757 return nil
758 }
759
760 // IsArchPresent checks if an architecture is present in a filter.
761 // If a filter contains an architecture, it uses its default action for
762 // syscalls which do not match rules in it, and its rules can match syscalls
763 // for that ABI.
764 // If a filter does not contain an architecture, all syscalls made to that
765 // kernel ABI will fail with the filter's default Bad Architecture Action
766 // (by default, killing the process).
767 // Accepts an architecture constant.
768 // Returns true if the architecture is present in the filter, false otherwise,
769 // and an error on an invalid filter context, architecture constant, or an
770 // issue with the call to libseccomp.
771 func (f *ScmpFilter) IsArchPresent(arch ScmpArch) (bool, error) {
772 f.lock.Lock()
773 defer f.lock.Unlock()
774
775 if err := sanitizeArch(arch); err != nil {
776 return false, err
777 } else if !f.valid {
778 return false, errBadFilter
779 }
780
781 if retCode := C.seccomp_arch_exist(f.filterCtx, arch.toNative()); retCode != 0 {
782 e := errRc(retCode)
783 if e == syscall.EEXIST {
784 // -EEXIST is "arch not present"
785 return false, nil
786 }
787 return false, e
788 }
789
790 return true, nil
791 }
792
793 // AddArch adds an architecture to the filter.
794 // Accepts an architecture constant.
795 // Returns an error on invalid filter context or architecture token, or an
796 // issue with the call to libseccomp.
797 func (f *ScmpFilter) AddArch(arch ScmpArch) error {
798 f.lock.Lock()
799 defer f.lock.Unlock()
800
801 if err := sanitizeArch(arch); err != nil {
802 return err
803 } else if !f.valid {
804 return errBadFilter
805 }
806
807 // Libseccomp returns -EEXIST if the specified architecture is already
808 // present. Succeed silently in this case, as it's not fatal, and the
809 // architecture is present already.
810 if retCode := C.seccomp_arch_add(f.filterCtx, arch.toNative()); retCode != 0 {
811 if e := errRc(retCode); e != syscall.EEXIST {
812 return e
813 }
814 }
815
816 return nil
817 }
818
819 // RemoveArch removes an architecture from the filter.
820 // Accepts an architecture constant.
821 // Returns an error on invalid filter context or architecture token, or an
822 // issue with the call to libseccomp.
823 func (f *ScmpFilter) RemoveArch(arch ScmpArch) error {
824 f.lock.Lock()
825 defer f.lock.Unlock()
826
827 if err := sanitizeArch(arch); err != nil {
828 return err
829 } else if !f.valid {
830 return errBadFilter
831 }
832
833 // Similar to AddArch, -EEXIST is returned if the arch is not present
834 // Succeed silently in that case, this is not fatal and the architecture
835 // is not present in the filter after RemoveArch
836 if retCode := C.seccomp_arch_remove(f.filterCtx, arch.toNative()); retCode != 0 {
837 if e := errRc(retCode); e != syscall.EEXIST {
838 return e
839 }
840 }
841
842 return nil
843 }
844
845 // Precompute precomputes the seccomp filter for later use by [Load] and
846 // similar functions. Not only does this improve performance of [Load],
847 // it also ensures that the seccomp filter can be loaded in an
848 // async-signal-safe manner if no changes have been made to the filter
849 // since it was precomputed.
850 func (f *ScmpFilter) Precompute() error {
851 f.lock.Lock()
852 defer f.lock.Unlock()
853
854 if !f.valid {
855 return errBadFilter
856 }
857
858 if retCode := C.seccomp_precompute(f.filterCtx); retCode != 0 {
859 return errRc(retCode)
860 }
861
862 return nil
863 }
864
865 // Load loads a filter context into the kernel.
866 // Returns an error if the filter context is invalid or the syscall failed.
867 func (f *ScmpFilter) Load() error {
868 f.lock.Lock()
869 defer f.lock.Unlock()
870
871 if !f.valid {
872 return errBadFilter
873 }
874
875 if retCode := C.seccomp_load(f.filterCtx); retCode != 0 {
876 return errRc(retCode)
877 }
878
879 return nil
880 }
881
882 // GetDefaultAction returns the default action taken on a syscall which does not
883 // match a rule in the filter, or an error if an issue was encountered
884 // retrieving the value.
885 func (f *ScmpFilter) GetDefaultAction() (ScmpAction, error) {
886 action, err := f.getFilterAttr(filterAttrActDefault)
887 if err != nil {
888 return 0x0, err
889 }
890
891 return actionFromNative(action)
892 }
893
894 // GetBadArchAction returns the default action taken on a syscall for an
895 // architecture not in the filter, or an error if an issue was encountered
896 // retrieving the value.
897 func (f *ScmpFilter) GetBadArchAction() (ScmpAction, error) {
898 action, err := f.getFilterAttr(filterAttrActBadArch)
899 if err != nil {
900 return 0x0, err
901 }
902
903 return actionFromNative(action)
904 }
905
906 // GetNoNewPrivsBit returns the current state the No New Privileges bit will be set
907 // to on the filter being loaded, or an error if an issue was encountered
908 // retrieving the value.
909 // The No New Privileges bit tells the kernel that new processes run with exec()
910 // cannot gain more privileges than the process that ran exec().
911 // For example, a process with No New Privileges set would be unable to exec
912 // setuid/setgid executables.
913 func (f *ScmpFilter) GetNoNewPrivsBit() (bool, error) {
914 noNewPrivs, err := f.getFilterAttr(filterAttrNNP)
915 if err != nil {
916 return false, err
917 }
918
919 if noNewPrivs == 0 {
920 return false, nil
921 }
922
923 return true, nil
924 }
925
926 // GetLogBit returns the current state the Log bit will be set to on the filter
927 // being loaded, or an error if an issue was encountered retrieving the value.
928 // The Log bit tells the kernel that all actions taken by the filter, with the
929 // exception of ActAllow, should be logged.
930 // The Log bit is only usable when libseccomp API level 3 or higher is
931 // supported.
932 func (f *ScmpFilter) GetLogBit() (bool, error) {
933 log, err := f.getFilterAttr(filterAttrLog)
934 if err != nil {
935 if e := checkAPI("GetLogBit", 3, 2, 4, 0); e != nil {
936 err = e
937 }
938
939 return false, err
940 }
941
942 if log == 0 {
943 return false, nil
944 }
945
946 return true, nil
947 }
948
949 // GetSSB returns the current state the SSB bit will be set to on the filter
950 // being loaded, or an error if an issue was encountered retrieving the value.
951 // The SSB bit tells the kernel that a seccomp user is not interested in enabling
952 // Speculative Store Bypass mitigation.
953 // The SSB bit is only usable when libseccomp API level 4 or higher is
954 // supported.
955 func (f *ScmpFilter) GetSSB() (bool, error) {
956 ssb, err := f.getFilterAttr(filterAttrSSB)
957 if err != nil {
958 if e := checkAPI("GetSSB", 4, 2, 5, 0); e != nil {
959 err = e
960 }
961
962 return false, err
963 }
964
965 if ssb == 0 {
966 return false, nil
967 }
968
969 return true, nil
970 }
971
972 // GetOptimize returns the current optimization level of the filter,
973 // or an error if an issue was encountered retrieving the value.
974 // See SetOptimize for more details.
975 func (f *ScmpFilter) GetOptimize() (int, error) {
976 level, err := f.getFilterAttr(filterAttrOptimize)
977 if err != nil {
978 if e := checkAPI("GetOptimize", 4, 2, 5, 0); e != nil {
979 err = e
980 }
981
982 return 0, err
983 }
984
985 return int(level), nil
986 }
987
988 // GetRawRC returns the current state of RawRC flag, or an error
989 // if an issue was encountered retrieving the value.
990 // See SetRawRC for more details.
991 func (f *ScmpFilter) GetRawRC() (bool, error) {
992 rawrc, err := f.getFilterAttr(filterAttrRawRC)
993 if err != nil {
994 if e := checkAPI("GetRawRC", 4, 2, 5, 0); e != nil {
995 err = e
996 }
997
998 return false, err
999 }
1000
1001 if rawrc == 0 {
1002 return false, nil
1003 }
1004
1005 return true, nil
1006 }
1007
1008 // GetWaitKill returns the current state of WaitKill flag,
1009 // or an error if an issue was encountered retrieving the value.
1010 // See SetWaitKill for more details.
1011 func (f *ScmpFilter) GetWaitKill() (bool, error) {
1012 val, err := f.getFilterAttr(filterAttrWaitKill)
1013 if err != nil {
1014 if e := checkAPI("GetWaitKill", 7, 2, 6, 0); e != nil {
1015 err = e
1016 }
1017
1018 return false, err
1019 }
1020 if val == 0 {
1021 return false, nil
1022 }
1023
1024 return true, nil
1025 }
1026
1027 // SetBadArchAction sets the default action taken on a syscall for an
1028 // architecture not in the filter, or an error if an issue was encountered
1029 // setting the value.
1030 func (f *ScmpFilter) SetBadArchAction(action ScmpAction) error {
1031 if err := sanitizeAction(action); err != nil {
1032 return err
1033 }
1034
1035 return f.setFilterAttr(filterAttrActBadArch, action.toNative())
1036 }
1037
1038 // SetNoNewPrivsBit sets the state of the No New Privileges bit, which will be
1039 // applied on filter load, or an error if an issue was encountered setting the
1040 // value.
1041 // Filters with No New Privileges set to 0 can only be loaded if the process
1042 // has the CAP_SYS_ADMIN capability.
1043 func (f *ScmpFilter) SetNoNewPrivsBit(state bool) error {
1044 var toSet C.uint32_t = 0x0
1045
1046 if state {
1047 toSet = 0x1
1048 }
1049
1050 return f.setFilterAttr(filterAttrNNP, toSet)
1051 }
1052
1053 // SetLogBit sets the state of the Log bit, which will be applied on filter
1054 // load, or an error if an issue was encountered setting the value.
1055 // The Log bit is only usable when libseccomp API level 3 or higher is
1056 // supported.
1057 func (f *ScmpFilter) SetLogBit(state bool) error {
1058 var toSet C.uint32_t = 0x0
1059
1060 if state {
1061 toSet = 0x1
1062 }
1063
1064 err := f.setFilterAttr(filterAttrLog, toSet)
1065 if err != nil {
1066 if e := checkAPI("SetLogBit", 3, 2, 4, 0); e != nil {
1067 err = e
1068 }
1069 }
1070
1071 return err
1072 }
1073
1074 // SetSSB sets the state of the SSB bit, which will be applied on filter
1075 // load, or an error if an issue was encountered setting the value.
1076 // The SSB bit is only usable when libseccomp API level 4 or higher is
1077 // supported.
1078 func (f *ScmpFilter) SetSSB(state bool) error {
1079 var toSet C.uint32_t = 0x0
1080
1081 if state {
1082 toSet = 0x1
1083 }
1084
1085 err := f.setFilterAttr(filterAttrSSB, toSet)
1086 if err != nil {
1087 if e := checkAPI("SetSSB", 4, 2, 5, 0); e != nil {
1088 err = e
1089 }
1090 }
1091
1092 return err
1093 }
1094
1095 // SetOptimize sets optimization level of the seccomp filter. By default
1096 // libseccomp generates a set of sequential "if" statements for each rule in
1097 // the filter. SetSyscallPriority can be used to prioritize the order for the
1098 // default cause. The binary tree optimization sorts by syscall numbers and
1099 // generates consistent O(log n) filter traversal for every rule in the filter.
1100 // The binary tree may be advantageous for large filters. Note that
1101 // SetSyscallPriority is ignored when level == 2.
1102 //
1103 // The different optimization levels are:
1104 // 0: Reserved value, not currently used.
1105 // 1: Rules sorted by priority and complexity (DEFAULT).
1106 // 2: Binary tree sorted by syscall number.
1107 func (f *ScmpFilter) SetOptimize(level int) error {
1108 cLevel := C.uint32_t(level)
1109
1110 err := f.setFilterAttr(filterAttrOptimize, cLevel)
1111 if err != nil {
1112 if e := checkAPI("SetOptimize", 4, 2, 5, 0); e != nil {
1113 err = e
1114 }
1115 }
1116
1117 return err
1118 }
1119
1120 // SetRawRC sets whether libseccomp should pass system error codes back to the
1121 // caller, instead of the default ECANCELED. Defaults to false.
1122 func (f *ScmpFilter) SetRawRC(state bool) error {
1123 var toSet C.uint32_t = 0x0
1124
1125 if state {
1126 toSet = 0x1
1127 }
1128
1129 err := f.setFilterAttr(filterAttrRawRC, toSet)
1130 if err != nil {
1131 if e := checkAPI("SetRawRC", 4, 2, 5, 0); e != nil {
1132 err = e
1133 }
1134 }
1135
1136 return err
1137 }
1138
1139 // SetWaitKill sets whether libseccomp should request wait killable semantics
1140 // when possible. Defaults to false.
1141 func (f *ScmpFilter) SetWaitKill(state bool) error {
1142 var toSet C.uint32_t = 0x0
1143
1144 if state {
1145 toSet = 0x1
1146 }
1147
1148 err := f.setFilterAttr(filterAttrWaitKill, toSet)
1149 if err != nil {
1150 if e := checkAPI("SetWaitKill", 7, 2, 6, 0); e != nil {
1151 err = e
1152 }
1153 }
1154
1155 return err
1156 }
1157
1158 // SetSyscallPriority sets a syscall's priority.
1159 // This provides a hint to the filter generator in libseccomp about the
1160 // importance of this syscall. High-priority syscalls are placed
1161 // first in the filter code, and incur less overhead (at the expense of
1162 // lower-priority syscalls).
1163 func (f *ScmpFilter) SetSyscallPriority(call ScmpSyscall, priority uint8) error {
1164 f.lock.Lock()
1165 defer f.lock.Unlock()
1166
1167 if !f.valid {
1168 return errBadFilter
1169 }
1170
1171 if retCode := C.seccomp_syscall_priority(f.filterCtx, C.int(call),
1172 C.uint8_t(priority)); retCode != 0 {
1173 return errRc(retCode)
1174 }
1175
1176 return nil
1177 }
1178
1179 // AddRule adds a single rule for an unconditional action on a syscall.
1180 // Accepts the number of the syscall and the action to be taken on the call
1181 // being made.
1182 // Returns an error if an issue was encountered adding the rule.
1183 func (f *ScmpFilter) AddRule(call ScmpSyscall, action ScmpAction) error {
1184 return f.addRuleGeneric(call, action, false, nil)
1185 }
1186
1187 // AddRuleExact adds a single rule for an unconditional action on a syscall.
1188 // Accepts the number of the syscall and the action to be taken on the call
1189 // being made.
1190 // No modifications will be made to the rule, and it will fail to add if it
1191 // cannot be applied to the current architecture without modification.
1192 // The rule will function exactly as described, but it may not function identically
1193 // (or be able to be applied to) all architectures.
1194 // Returns an error if an issue was encountered adding the rule.
1195 func (f *ScmpFilter) AddRuleExact(call ScmpSyscall, action ScmpAction) error {
1196 return f.addRuleGeneric(call, action, true, nil)
1197 }
1198
1199 // AddRuleConditional adds a single rule for a conditional action on a syscall.
1200 // Returns an error if an issue was encountered adding the rule.
1201 // All conditions must match for the rule to match.
1202 func (f *ScmpFilter) AddRuleConditional(call ScmpSyscall, action ScmpAction, conds []ScmpCondition) error {
1203 return f.addRuleGeneric(call, action, false, conds)
1204 }
1205
1206 // AddRuleConditionalExact adds a single rule for a conditional action on a
1207 // syscall.
1208 // No modifications will be made to the rule, and it will fail to add if it
1209 // cannot be applied to the current architecture without modification.
1210 // The rule will function exactly as described, but it may not function identically
1211 // (or be able to be applied to) all architectures.
1212 // Returns an error if an issue was encountered adding the rule.
1213 func (f *ScmpFilter) AddRuleConditionalExact(call ScmpSyscall, action ScmpAction, conds []ScmpCondition) error {
1214 return f.addRuleGeneric(call, action, true, conds)
1215 }
1216
1217 // ExportPFC output PFC-formatted, human-readable dump of a filter context's
1218 // rules to a file.
1219 // Accepts file to write to (must be open for writing).
1220 // Returns an error if writing to the file fails.
1221 func (f *ScmpFilter) ExportPFC(file *os.File) error {
1222 f.lock.Lock()
1223 defer f.lock.Unlock()
1224
1225 fd := file.Fd()
1226
1227 if !f.valid {
1228 return errBadFilter
1229 }
1230
1231 if retCode := C.seccomp_export_pfc(f.filterCtx, C.int(fd)); retCode != 0 {
1232 return errRc(retCode)
1233 }
1234
1235 return nil
1236 }
1237
1238 // ExportBPF outputs Berkeley Packet Filter-formatted, kernel-readable dump of a
1239 // filter context's rules to a file.
1240 // Accepts file to write to (must be open for writing).
1241 // Returns an error if writing to the file fails.
1242 func (f *ScmpFilter) ExportBPF(file *os.File) error {
1243 f.lock.Lock()
1244 defer f.lock.Unlock()
1245
1246 fd := file.Fd()
1247
1248 if !f.valid {
1249 return errBadFilter
1250 }
1251
1252 if retCode := C.seccomp_export_bpf(f.filterCtx, C.int(fd)); retCode != 0 {
1253 return errRc(retCode)
1254 }
1255
1256 return nil
1257 }
1258
1259 // ExportBPFMem is similar to [ExportBPF], except the data is written into
1260 // a memory and returned as []byte.
1261 func (f *ScmpFilter) ExportBPFMem() ([]byte, error) {
1262 f.lock.Lock()
1263 defer f.lock.Unlock()
1264
1265 if !f.valid {
1266 return nil, errBadFilter
1267 }
1268
1269 var len C.size_t
1270 // Get the size required.
1271 if retCode := C.seccomp_export_bpf_mem(f.filterCtx, unsafe.Pointer(nil), &len); retCode < 0 {
1272 return nil, errRc(retCode)
1273 }
1274 // Get the data.
1275 buf := make([]byte, int(len))
1276 if retCode := C.seccomp_export_bpf_mem(f.filterCtx, unsafe.Pointer(&buf[0]), &len); retCode < 0 {
1277 return nil, errRc(retCode)
1278 }
1279
1280 return buf, nil
1281 }
1282
1283 // Userspace Notification API
1284
1285 // GetNotifFd returns the userspace notification file descriptor associated with the given
1286 // filter context. Such a file descriptor is only valid after the filter has been loaded
1287 // and only when the filter uses the ActNotify action. The file descriptor can be used to
1288 // retrieve and respond to notifications associated with the filter (see NotifReceive(),
1289 // NotifRespond(), and NotifIDValid()).
1290 func (f *ScmpFilter) GetNotifFd() (ScmpFd, error) {
1291 return f.getNotifFd()
1292 }
1293
1294 // NotifReceive retrieves a seccomp userspace notification from a filter whose ActNotify
1295 // action has triggered. The caller is expected to process the notification and return a
1296 // response via NotifRespond(). Each invocation of this function returns one
1297 // notification. As multiple notifications may be pending at any time, this function is
1298 // normally called within a polling loop.
1299 func NotifReceive(fd ScmpFd) (*ScmpNotifReq, error) {
1300 return notifReceive(fd)
1301 }
1302
1303 // NotifRespond responds to a notification retrieved via NotifReceive(). The response Id
1304 // must match that of the corresponding notification retrieved via NotifReceive().
1305 func NotifRespond(fd ScmpFd, scmpResp *ScmpNotifResp) error {
1306 return notifRespond(fd, scmpResp)
1307 }
1308
1309 // NotifIDValid checks if a notification is still valid. An return value of nil means the
1310 // notification is still valid. Otherwise the notification is not valid. This can be used
1311 // to mitigate time-of-check-time-of-use (TOCTOU) attacks as described in seccomp_notify_id_valid(2).
1312 func NotifIDValid(fd ScmpFd, id uint64) error {
1313 return notifIDValid(fd, id)
1314 }
1315
1316 // TransactionStart starts a new seccomp filter transaction that the caller can
1317 // use to perform any number of filter modifications which can then be
1318 // committed to the filter using [TransactionCommit] or rejected using
1319 // [TransactionReject]. It is important to note that transactions only affect
1320 // the seccomp filter state while it is being managed by libseccomp; seccomp
1321 // filters which have been loaded into the kernel can not be modified, only new
1322 // seccomp filters can be added on top of the existing loaded filter stack.
1323 func (f *ScmpFilter) TransactionStart() error {
1324 f.lock.Lock()
1325 defer f.lock.Unlock()
1326
1327 if !f.valid {
1328 return errBadFilter
1329 }
1330
1331 if retCode := C.seccomp_transaction_start(f.filterCtx); retCode < 0 {
1332 return errRc(retCode)
1333 }
1334
1335 return nil
1336 }
1337
1338 // TransactionReject rejects a transaction started by [TransactionStart].
1339 func (f *ScmpFilter) TransactionReject() {
1340 f.lock.Lock()
1341 defer f.lock.Unlock()
1342
1343 if !f.valid {
1344 return
1345 }
1346
1347 C.seccomp_transaction_reject(f.filterCtx)
1348 }
1349
1350 // TransactionCommit commits a transaction started by [TransactionStart].
1351 func (f *ScmpFilter) TransactionCommit() error {
1352 f.lock.Lock()
1353 defer f.lock.Unlock()
1354
1355 if !f.valid {
1356 return errBadFilter
1357 }
1358
1359 if retCode := C.seccomp_transaction_commit(f.filterCtx); retCode < 0 {
1360 return errRc(retCode)
1361 }
1362
1363 return nil
1364 }