seccomp

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2022 License: BSD-2-Clause Imports: 9 Imported by: 95

README

libseccomp Golang Bindings

https://github.com/seccomp/libseccomp-golang

Go Reference validate test

The libseccomp library provides an easy to use, platform independent, interface to the Linux Kernel's syscall filtering mechanism. The libseccomp API is designed to abstract away the underlying BPF based syscall filter language and present a more conventional function-call based filtering interface that should be familiar to, and easily adopted by, application developers.

The libseccomp-golang library provides a Go based interface to the libseccomp library.

Online Resources

The library source repository currently lives on GitHub at the following URLs:

Documentation for this package is also available at:

Verifying Releases

Starting with libseccomp-golang v0.10.0, the git tag corresponding to each release should be signed by one of the libseccomp-golang maintainers. It is recommended that before use you verify the release tags using the following command:

% git tag -v <tag>

At present, only the following keys, specified via the fingerprints below, are authorized to sign official libseccomp-golang release tags:

Paul Moore <paul@paul-moore.com>
7100 AADF AE6E 6E94 0D2E  0AD6 55E4 5A5A E8CA 7C8A

Tom Hromatka <tom.hromatka@oracle.com>
47A6 8FCE 37C7 D702 4FD6  5E11 356C E62C 2B52 4099

Kir Kolyshkin <kolyshkin@gmail.com>
C242 8CD7 5720 FACD CF76  B6EA 17DE 5ECB 75A1 100E

More information on GnuPG and git tag verification can be found at their respective websites: https://git-scm.com/docs/git and https://gnupg.org.

Installing the package

% go get github.com/seccomp/libseccomp-golang

Contributing

See CONTRIBUTING.md.

Documentation

Overview

Package seccomp provides bindings for libseccomp, a library wrapping the Linux seccomp syscall. Seccomp enables an application to restrict system call use for itself and its children.

Index

Constants

View Source
const (

	// NotifRespFlagContinue tells the kernel to continue executing the system
	// call that triggered the notification. Must only be used when the notification
	// response's error is 0.
	NotifRespFlagContinue uint32 = 1
)

Variables

View Source
var ErrSyscallDoesNotExist = errors.New("could not resolve syscall name")

ErrSyscallDoesNotExist represents an error condition where libseccomp is unable to resolve the syscall.

Functions

func GetAPI added in v0.10.0

func GetAPI() (uint, error)

GetAPI returns the API level supported by the system. Returns a positive int containing the API level, or 0 with an error if the API level could not be detected due to the library being older than v2.4.0. See the seccomp_api_get(3) man page for details on available API levels: https://github.com/seccomp/libseccomp/blob/main/doc/man/man3/seccomp_api_get.3

func GetLibraryVersion

func GetLibraryVersion() (major, minor, micro uint)

GetLibraryVersion returns the version of the library the bindings are built against. The version is formatted as follows: Major.Minor.Micro

func NotifIDValid added in v0.10.0

func NotifIDValid(fd ScmpFd, id uint64) error

NotifIDValid checks if a notification is still valid. An return value of nil means the notification is still valid. Otherwise the notification is not valid. This can be used to mitigate time-of-check-time-of-use (TOCTOU) attacks as described in seccomp_notify_id_valid(2).

func NotifRespond added in v0.10.0

func NotifRespond(fd ScmpFd, scmpResp *ScmpNotifResp) error

NotifRespond responds to a notification retrieved via NotifReceive(). The response Id must match that of the corresponding notification retrieved via NotifReceive().

func SetAPI added in v0.10.0

func SetAPI(api uint) error

SetAPI forcibly sets the API level. General use of this function is strongly discouraged. Returns an error if the API level could not be set. An error is always returned if the library is older than v2.4.0 See the seccomp_api_get(3) man page for details on available API levels: https://github.com/seccomp/libseccomp/blob/main/doc/man/man3/seccomp_api_get.3

Types

type ScmpAction

type ScmpAction uint

ScmpAction represents an action to be taken on a filter rule match in libseccomp

const (

	// ActInvalid is a placeholder to ensure uninitialized ScmpAction
	// variables are invalid
	ActInvalid ScmpAction = iota
	// ActKillThread kills the thread that violated the rule.
	// All other threads from the same thread group will continue to execute.
	ActKillThread
	// ActTrap throws SIGSYS
	ActTrap
	// ActNotify triggers a userspace notification. This action is only usable when
	// libseccomp API level 6 or higher is supported.
	ActNotify
	// ActErrno causes the syscall to return a negative error code. This
	// code can be set with the SetReturnCode method
	ActErrno
	// ActTrace causes the syscall to notify tracing processes with the
	// given error code. This code can be set with the SetReturnCode method
	ActTrace
	// ActAllow permits the syscall to continue execution
	ActAllow
	// ActLog permits the syscall to continue execution after logging it.
	// This action is only usable when libseccomp API level 3 or higher is
	// supported.
	ActLog
	// ActKillProcess kills the process that violated the rule.
	// All threads in the thread group are also terminated.
	// This action is only usable when libseccomp API level 3 or higher is
	// supported.
	ActKillProcess
	// ActKill kills the thread that violated the rule.
	// All other threads from the same thread group will continue to execute.
	//
	// Deprecated: use ActKillThread
	ActKill = ActKillThread
)

func (ScmpAction) GetReturnCode

func (a ScmpAction) GetReturnCode() int16

GetReturnCode returns the return code of an ScmpAction

func (ScmpAction) SetReturnCode

func (a ScmpAction) SetReturnCode(code int16) ScmpAction

SetReturnCode adds a return code to a supporting ScmpAction, clearing any existing code Only valid on ActErrno and ActTrace. Takes no action otherwise. Accepts 16-bit return code as argument. Returns a valid ScmpAction of the original type with the new error code set.

func (ScmpAction) String

func (a ScmpAction) String() string

String returns a string representation of a seccomp match action

type ScmpArch

type ScmpArch uint

ScmpArch represents a CPU architecture. Seccomp can restrict syscalls on a per-architecture basis.

const (

	// ArchInvalid is a placeholder to ensure uninitialized ScmpArch
	// variables are invalid
	ArchInvalid ScmpArch = iota
	// ArchNative is the native architecture of the kernel
	ArchNative
	// ArchX86 represents 32-bit x86 syscalls
	ArchX86
	// ArchAMD64 represents 64-bit x86-64 syscalls
	ArchAMD64
	// ArchX32 represents 64-bit x86-64 syscalls (32-bit pointers)
	ArchX32
	// ArchARM represents 32-bit ARM syscalls
	ArchARM
	// ArchARM64 represents 64-bit ARM syscalls
	ArchARM64
	// ArchMIPS represents 32-bit MIPS syscalls
	ArchMIPS
	// ArchMIPS64 represents 64-bit MIPS syscalls
	ArchMIPS64
	// ArchMIPS64N32 represents 64-bit MIPS syscalls (32-bit pointers)
	ArchMIPS64N32
	// ArchMIPSEL represents 32-bit MIPS syscalls (little endian)
	ArchMIPSEL
	// ArchMIPSEL64 represents 64-bit MIPS syscalls (little endian)
	ArchMIPSEL64
	// ArchMIPSEL64N32 represents 64-bit MIPS syscalls (little endian,
	// 32-bit pointers)
	ArchMIPSEL64N32
	// ArchPPC represents 32-bit POWERPC syscalls
	ArchPPC
	// ArchPPC64 represents 64-bit POWER syscalls (big endian)
	ArchPPC64
	// ArchPPC64LE represents 64-bit POWER syscalls (little endian)
	ArchPPC64LE
	// ArchS390 represents 31-bit System z/390 syscalls
	ArchS390
	// ArchS390X represents 64-bit System z/390 syscalls
	ArchS390X
	// ArchPARISC represents 32-bit PA-RISC
	ArchPARISC
	// ArchPARISC64 represents 64-bit PA-RISC
	ArchPARISC64
	// ArchRISCV64 represents RISCV64
	ArchRISCV64
)

func GetArchFromString

func GetArchFromString(arch string) (ScmpArch, error)

GetArchFromString returns an ScmpArch constant from a string representing an architecture

func GetNativeArch

func GetNativeArch() (ScmpArch, error)

GetNativeArch returns architecture token representing the native kernel architecture

func (ScmpArch) String

func (a ScmpArch) String() string

String returns a string representation of an architecture constant

type ScmpCompareOp

type ScmpCompareOp uint

ScmpCompareOp represents a comparison operator which can be used in a filter rule

const (

	// CompareInvalid is a placeholder to ensure uninitialized ScmpCompareOp
	// variables are invalid
	CompareInvalid ScmpCompareOp = iota
	// CompareNotEqual returns true if the argument is not equal to the
	// given value
	CompareNotEqual
	// CompareLess returns true if the argument is less than the given value
	CompareLess
	// CompareLessOrEqual returns true if the argument is less than or equal
	// to the given value
	CompareLessOrEqual
	// CompareEqual returns true if the argument is equal to the given value
	CompareEqual
	// CompareGreaterEqual returns true if the argument is greater than or
	// equal to the given value
	CompareGreaterEqual
	// CompareGreater returns true if the argument is greater than the given
	// value
	CompareGreater
	// CompareMaskedEqual returns true if the masked argument value is
	// equal to the masked datum value. Mask is the first argument, and
	// datum is the second one.
	CompareMaskedEqual
)

func (ScmpCompareOp) String

func (a ScmpCompareOp) String() string

String returns a string representation of a comparison operator constant

type ScmpCondition

type ScmpCondition struct {
	Argument uint          `json:"argument,omitempty"`
	Op       ScmpCompareOp `json:"operator,omitempty"`
	Operand1 uint64        `json:"operand_one,omitempty"`
	Operand2 uint64        `json:"operand_two,omitempty"`
}

ScmpCondition represents a rule in a libseccomp filter context

func MakeCondition

func MakeCondition(arg uint, comparison ScmpCompareOp, values ...uint64) (ScmpCondition, error)

MakeCondition creates and returns a new condition to attach to a filter rule. Associated rules will only match if this condition is true. Accepts the number the argument we are checking, and a comparison operator and value to compare to. The rule will match if argument $arg (zero-indexed) of the syscall is $COMPARE_OP the provided comparison value. Some comparison operators accept two values. Masked equals, for example, will mask $arg of the syscall with the second value provided (via bitwise AND) and then compare against the first value provided. For example, in the less than or equal case, if the syscall argument was 0 and the value provided was 1, the condition would match, as 0 is less than or equal to 1. Return either an error on bad argument or a valid ScmpCondition struct.

type ScmpFd added in v0.10.0

type ScmpFd int32

ScmpFd represents a file-descriptor used for seccomp userspace notifications.

type ScmpFilter

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

ScmpFilter represents a filter context in libseccomp. A filter context is initially empty. Rules can be added to it, and it can then be loaded into the kernel.

func NewFilter

func NewFilter(defaultAction ScmpAction) (*ScmpFilter, error)

NewFilter creates and returns a new filter context. Accepts a default action to be taken for syscalls which match no rules in the filter. Returns a reference to a valid filter context, or nil and an error if the filter context could not be created or an invalid default action was given.

func (*ScmpFilter) AddArch

func (f *ScmpFilter) AddArch(arch ScmpArch) error

AddArch adds an architecture to the filter. Accepts an architecture constant. Returns an error on invalid filter context or architecture token, or an issue with the call to libseccomp.

func (*ScmpFilter) AddRule

func (f *ScmpFilter) AddRule(call ScmpSyscall, action ScmpAction) error

AddRule adds a single rule for an unconditional action on a syscall. Accepts the number of the syscall and the action to be taken on the call being made. Returns an error if an issue was encountered adding the rule.

func (*ScmpFilter) AddRuleConditional

func (f *ScmpFilter) AddRuleConditional(call ScmpSyscall, action ScmpAction, conds []ScmpCondition) error

AddRuleConditional adds a single rule for a conditional action on a syscall. Returns an error if an issue was encountered adding the rule. All conditions must match for the rule to match.

func (*ScmpFilter) AddRuleConditionalExact

func (f *ScmpFilter) AddRuleConditionalExact(call ScmpSyscall, action ScmpAction, conds []ScmpCondition) error

AddRuleConditionalExact adds a single rule for a conditional action on a syscall. No modifications will be made to the rule, and it will fail to add if it cannot be applied to the current architecture without modification. The rule will function exactly as described, but it may not function identically (or be able to be applied to) all architectures. Returns an error if an issue was encountered adding the rule.

func (*ScmpFilter) AddRuleExact

func (f *ScmpFilter) AddRuleExact(call ScmpSyscall, action ScmpAction) error

AddRuleExact adds a single rule for an unconditional action on a syscall. Accepts the number of the syscall and the action to be taken on the call being made. No modifications will be made to the rule, and it will fail to add if it cannot be applied to the current architecture without modification. The rule will function exactly as described, but it may not function identically (or be able to be applied to) all architectures. Returns an error if an issue was encountered adding the rule.

func (*ScmpFilter) ExportBPF

func (f *ScmpFilter) ExportBPF(file *os.File) error

ExportBPF outputs Berkeley Packet Filter-formatted, kernel-readable dump of a filter context's rules to a file. Accepts file to write to (must be open for writing). Returns an error if writing to the file fails.

func (*ScmpFilter) ExportPFC

func (f *ScmpFilter) ExportPFC(file *os.File) error

ExportPFC output PFC-formatted, human-readable dump of a filter context's rules to a file. Accepts file to write to (must be open for writing). Returns an error if writing to the file fails.

func (*ScmpFilter) GetBadArchAction

func (f *ScmpFilter) GetBadArchAction() (ScmpAction, error)

GetBadArchAction returns the default action taken on a syscall for an architecture not in the filter, or an error if an issue was encountered retrieving the value.

func (*ScmpFilter) GetDefaultAction

func (f *ScmpFilter) GetDefaultAction() (ScmpAction, error)

GetDefaultAction returns the default action taken on a syscall which does not match a rule in the filter, or an error if an issue was encountered retrieving the value.

func (*ScmpFilter) GetLogBit added in v0.9.1

func (f *ScmpFilter) GetLogBit() (bool, error)

GetLogBit returns the current state the Log bit will be set to on the filter being loaded, or an error if an issue was encountered retrieving the value. The Log bit tells the kernel that all actions taken by the filter, with the exception of ActAllow, should be logged. The Log bit is only usable when libseccomp API level 3 or higher is supported.

func (*ScmpFilter) GetNoNewPrivsBit

func (f *ScmpFilter) GetNoNewPrivsBit() (bool, error)

GetNoNewPrivsBit returns the current state the No New Privileges bit will be set to on the filter being loaded, or an error if an issue was encountered retrieving the value. The No New Privileges bit tells the kernel that new processes run with exec() cannot gain more privileges than the process that ran exec(). For example, a process with No New Privileges set would be unable to exec setuid/setgid executables.

func (*ScmpFilter) GetNotifFd added in v0.10.0

func (f *ScmpFilter) GetNotifFd() (ScmpFd, error)

GetNotifFd returns the userspace notification file descriptor associated with the given filter context. Such a file descriptor is only valid after the filter has been loaded and only when the filter uses the ActNotify action. The file descriptor can be used to retrieve and respond to notifications associated with the filter (see NotifReceive(), NotifRespond(), and NotifIDValid()).

func (*ScmpFilter) GetOptimize added in v0.10.0

func (f *ScmpFilter) GetOptimize() (int, error)

GetOptimize returns the current optimization level of the filter, or an error if an issue was encountered retrieving the value. See SetOptimize for more details.

func (*ScmpFilter) GetRawRC added in v0.10.0

func (f *ScmpFilter) GetRawRC() (bool, error)

GetRawRC returns the current state of RawRC flag, or an error if an issue was encountered retrieving the value. See SetRawRC for more details.

func (*ScmpFilter) GetSSB added in v0.10.0

func (f *ScmpFilter) GetSSB() (bool, error)

GetSSB returns the current state the SSB bit will be set to on the filter being loaded, or an error if an issue was encountered retrieving the value. The SSB bit tells the kernel that a seccomp user is not interested in enabling Speculative Store Bypass mitigation. The SSB bit is only usable when libseccomp API level 4 or higher is supported.

func (*ScmpFilter) IsArchPresent

func (f *ScmpFilter) IsArchPresent(arch ScmpArch) (bool, error)

IsArchPresent checks if an architecture is present in a filter. If a filter contains an architecture, it uses its default action for syscalls which do not match rules in it, and its rules can match syscalls for that ABI. If a filter does not contain an architecture, all syscalls made to that kernel ABI will fail with the filter's default Bad Architecture Action (by default, killing the process). Accepts an architecture constant. Returns true if the architecture is present in the filter, false otherwise, and an error on an invalid filter context, architecture constant, or an issue with the call to libseccomp.

func (*ScmpFilter) IsValid

func (f *ScmpFilter) IsValid() bool

IsValid determines whether a filter context is valid to use. Some operations (Release and Merge) render filter contexts invalid and consequently prevent further use.

func (*ScmpFilter) Load

func (f *ScmpFilter) Load() error

Load loads a filter context into the kernel. Returns an error if the filter context is invalid or the syscall failed.

func (*ScmpFilter) Merge

func (f *ScmpFilter) Merge(src *ScmpFilter) error

Merge merges two filter contexts. The source filter src will be released as part of the process, and will no longer be usable or valid after this call. To be merged, filters must NOT share any architectures, and all their attributes (Default Action, Bad Arch Action, and No New Privs bools) must match. The filter src will be merged into the filter this is called on. The architectures of the src filter not present in the destination, and all associated rules, will be added to the destination. Returns an error if merging the filters failed.

func (*ScmpFilter) Release

func (f *ScmpFilter) Release()

Release releases a filter context, freeing its memory. Should be called after loading into the kernel, when the filter is no longer needed. After calling this function, the given filter is no longer valid and cannot be used. Release() will be invoked automatically when a filter context is garbage collected, but can also be called manually to free memory.

func (*ScmpFilter) RemoveArch

func (f *ScmpFilter) RemoveArch(arch ScmpArch) error

RemoveArch removes an architecture from the filter. Accepts an architecture constant. Returns an error on invalid filter context or architecture token, or an issue with the call to libseccomp.

func (*ScmpFilter) Reset

func (f *ScmpFilter) Reset(defaultAction ScmpAction) error

Reset resets a filter context, removing all its existing state. Accepts a new default action to be taken for syscalls which do not match. Returns an error if the filter or action provided are invalid.

func (*ScmpFilter) SetBadArchAction

func (f *ScmpFilter) SetBadArchAction(action ScmpAction) error

SetBadArchAction sets the default action taken on a syscall for an architecture not in the filter, or an error if an issue was encountered setting the value.

func (*ScmpFilter) SetLogBit added in v0.9.1

func (f *ScmpFilter) SetLogBit(state bool) error

SetLogBit sets the state of the Log bit, which will be applied on filter load, or an error if an issue was encountered setting the value. The Log bit is only usable when libseccomp API level 3 or higher is supported.

func (*ScmpFilter) SetNoNewPrivsBit

func (f *ScmpFilter) SetNoNewPrivsBit(state bool) error

SetNoNewPrivsBit sets the state of the No New Privileges bit, which will be applied on filter load, or an error if an issue was encountered setting the value. Filters with No New Privileges set to 0 can only be loaded if the process has the CAP_SYS_ADMIN capability.

func (*ScmpFilter) SetOptimize added in v0.10.0

func (f *ScmpFilter) SetOptimize(level int) error

SetOptimize sets optimization level of the seccomp filter. By default libseccomp generates a set of sequential "if" statements for each rule in the filter. SetSyscallPriority can be used to prioritize the order for the default cause. The binary tree optimization sorts by syscall numbers and generates consistent O(log n) filter traversal for every rule in the filter. The binary tree may be advantageous for large filters. Note that SetSyscallPriority is ignored when level == 2.

The different optimization levels are: 0: Reserved value, not currently used. 1: Rules sorted by priority and complexity (DEFAULT). 2: Binary tree sorted by syscall number.

func (*ScmpFilter) SetRawRC added in v0.10.0

func (f *ScmpFilter) SetRawRC(state bool) error

SetRawRC sets whether libseccomp should pass system error codes back to the caller, instead of the default ECANCELED. Defaults to false.

func (*ScmpFilter) SetSSB added in v0.10.0

func (f *ScmpFilter) SetSSB(state bool) error

SetSSB sets the state of the SSB bit, which will be applied on filter load, or an error if an issue was encountered setting the value. The SSB bit is only usable when libseccomp API level 4 or higher is supported.

func (*ScmpFilter) SetSyscallPriority

func (f *ScmpFilter) SetSyscallPriority(call ScmpSyscall, priority uint8) error

SetSyscallPriority sets a syscall's priority. This provides a hint to the filter generator in libseccomp about the importance of this syscall. High-priority syscalls are placed first in the filter code, and incur less overhead (at the expense of lower-priority syscalls).

type ScmpNotifData added in v0.10.0

type ScmpNotifData struct {
	Syscall      ScmpSyscall `json:"syscall,omitempty"`
	Arch         ScmpArch    `json:"arch,omitempty"`
	InstrPointer uint64      `json:"instr_pointer,omitempty"`
	Args         []uint64    `json:"args,omitempty"`
}

ScmpNotifData describes the system call context that triggered a notification.

Syscall: the syscall number Arch: the filter architecture InstrPointer: address of the instruction that triggered a notification Args: arguments (up to 6) for the syscall

type ScmpNotifReq added in v0.10.0

type ScmpNotifReq struct {
	ID    uint64        `json:"id,omitempty"`
	Pid   uint32        `json:"pid,omitempty"`
	Flags uint32        `json:"flags,omitempty"`
	Data  ScmpNotifData `json:"data,omitempty"`
}

ScmpNotifReq represents a seccomp userspace notification. See NotifReceive() for info on how to pull such a notification.

ID: notification ID Pid: process that triggered the notification event Flags: filter flags (see seccomp(2)) Data: system call context that triggered the notification

func NotifReceive added in v0.10.0

func NotifReceive(fd ScmpFd) (*ScmpNotifReq, error)

NotifReceive retrieves a seccomp userspace notification from a filter whose ActNotify action has triggered. The caller is expected to process the notification and return a response via NotifRespond(). Each invocation of this function returns one notification. As multiple notifications may be pending at any time, this function is normally called within a polling loop.

type ScmpNotifResp added in v0.10.0

type ScmpNotifResp struct {
	ID    uint64 `json:"id,omitempty"`
	Error int32  `json:"error,omitempty"`
	Val   uint64 `json:"val,omitempty"`
	Flags uint32 `json:"flags,omitempty"`
}

ScmpNotifResp represents a seccomp userspace notification response. See NotifRespond() for info on how to push such a response.

ID: notification ID (must match the corresponding ScmpNotifReq ID) Error: must be 0 if no error occurred, or an error constant from package

syscall (e.g., syscall.EPERM, etc). In the latter case, it's used
as an error return from the syscall that created the notification.

Val: return value for the syscall that created the notification. Only

relevant if Error is 0.

Flags: userspace notification response flag (e.g., NotifRespFlagContinue)

type ScmpSyscall

type ScmpSyscall int32

ScmpSyscall identifies a Linux System Call by its number.

func GetSyscallFromName

func GetSyscallFromName(name string) (ScmpSyscall, error)

GetSyscallFromName returns the number of a syscall by name on the kernel's native architecture. Accepts a string containing the name of a syscall. Returns the number of the syscall, or an error if no syscall with that name was found.

func GetSyscallFromNameByArch

func GetSyscallFromNameByArch(name string, arch ScmpArch) (ScmpSyscall, error)

GetSyscallFromNameByArch returns the number of a syscall by name for a given architecture's ABI. Accepts the name of a syscall and an architecture constant. Returns the number of the syscall, or an error if an invalid architecture is passed or a syscall with that name was not found.

func (ScmpSyscall) GetName

func (s ScmpSyscall) GetName() (string, error)

GetName retrieves the name of a syscall from its number. Acts on any syscall number. Returns either a string containing the name of the syscall, or an error.

func (ScmpSyscall) GetNameByArch

func (s ScmpSyscall) GetNameByArch(arch ScmpArch) (string, error)

GetNameByArch retrieves the name of a syscall from its number for a given architecture. Acts on any syscall number. Accepts a valid architecture constant. Returns either a string containing the name of the syscall, or an error. if the syscall is unrecognized or an issue occurred.

type VersionError

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

VersionError represents an error when either the system libseccomp version or the kernel version is too old to perform the operation requested.

func (VersionError) Error

func (e VersionError) Error() string

Jump to

Keyboard shortcuts

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