cap

package module
v0.2.37 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2020 License: GPL-2.0 Imports: 14 Imported by: 107

Documentation

Overview

Package cap is the Linux capabilities user space API (libcap) bindings in native Go.

For cgo linked binaries, behind the scenes, the package "kernel.org/pub/linux/libs/security/libcap/psx" is used to broker the POSIX semantics system calls that manipulate thread state uniformly over the whole process runtime.

If the Go runtime syscall interface contains the linux variant syscall.AllThreadsSyscall() API (it is not in go1.15beta1 for example) then this package can use that to invoke capability setting system calls for pure Go binaries. To force this behavior use the CGO_ENABLED=0 environment variable and, for now, a build tag:

CGO_ENABLED=0 go build -tags allthreadssyscall ...

If syscall.AllThreadsSyscall() is not present, the ".../libcap/cap" package will failover to using ".../libcap/psx".

Copyright (c) 2019,20 Andrew G. Morgan <morgan@kernel.org>

Index

Constants

View Source
const ExtMagic = uint32(0x5101c290)

ExtMagic is the 32-bit (little endian) magic for an external capability set. It can be used to transmit capabilities in binary format in a Linux portable way. The format is: <ExtMagic><byte:length><length-bytes*3-of-cap-data>.

View Source
const LaunchSupported = true

LaunchSupported indicates that is safe to return from a locked OS Thread and have that OS Thread be terminated by the runtime. The Launch functionality really needs to rely on the fact that an excess of runtime.LockOSThread() vs. runtime.UnlockOSThread() calls in a returning go routine will cause the underlying locked OSThread to terminate. That feature was added to the Go runtime in version 1.10.

See these bugs for the discussion and feature assumed by the code in this Launch() functionality:

https://github.com/golang/go/issues/20395
https://github.com/golang/go/issues/20458

A value of false for this constant causes cap.(*Launcher).Launch() to park the go routine used to perform the launch indefinitely so the kernel privilege state of the OS Thread locked to it does not pollute the rest of the runtime - yes, it leaks an OSThread. If this is a problem for your application you have two workarounds:

1) don't use cap.(*Launcher).Launch() 2) upgrade your Go toolchain to 1.10+ (ie., do this one).

View Source
const NamedCount = 40

NamedCount holds the number of capabilities with official names.

Variables

View Source
var (
	ErrBadSize  = errors.New("filecap bad size")
	ErrBadMagic = errors.New("unsupported magic")
	ErrBadPath  = errors.New("file is not a regular executable")
)

ErrBadSize indicates the the loaded file capability has an invalid number of bytes in it.

View Source
var ErrAmbiguousAmbient = errors.New("use Launcher for ambient caps")

ErrAmbiguousAmbient indicates that the Launcher is being used in addition callback supplied ambient set and the former should be used exclusively in a Launch call.

View Source
var ErrAmbiguousChroot = errors.New("use Launcher for chroot")

ErrAmbiguousChroot indicates that the Launcher is being used in addition to callback supplied Chroot. The former should be used exclusively for this.

View Source
var ErrAmbiguousIDs = errors.New("use Launcher for uids and gids")

ErrAmbiguousIDs indicates that the Launcher is being used in addition to callback supplied Credentials. The former should be used exclusively for this.

View Source
var ErrBadMode = errors.New("unsupported mode")

ErrBadMode is the error returned when an attempt is made to set an unrecognized libcap security mode.

View Source
var ErrBadSet = errors.New("bad capability set")

ErrBadSet indicates a nil pointer was used for a *Set, or the request of the Set is invalid in some way.

View Source
var ErrBadText = errors.New("bad text")

ErrBadText is returned if the text for a capability set cannot be parsed.

View Source
var ErrBadValue = errors.New("bad capability value")

ErrBadValue indicates a bad capability value was specified.

View Source
var ErrLaunchFailed = errors.New("launch failed")

ErrLaunchFailed is returned if a launch was aborted with no more specific error.

View Source
var ErrNoLaunch = errors.New("launch not supported")

ErrNoLaunch indicates the go runtime available to this binary does not reliably support launching. See cap.LaunchSupported.

Functions

func Differs

func Differs(cf uint, vec Flag) bool

Differs processes the result of Compare and determines if the Flag's components were different.

func DropBound

func DropBound(val ...Value) error

DropBound attempts to suppress bounding set Values. The kernel will never allow a bounding set Value bit to be raised once successfully dropped. However, dropping requires the current process is sufficiently capable (usually via cap.SETPCAP being raised in the Effective flag vector). Note, the drops are performed in order and if one bounding value cannot be dropped, the function returns immediately with an error which may leave the system in an ill-defined state. The caller can determine where things went wrong from on error using GetBound().

func GetAmbient

func GetAmbient(val Value) (bool, error)

GetAmbient determines if a specific capability is currently part of the local ambient set. On systems where the ambient set Value is not present, this function returns an error.

func GetBound

func GetBound(val Value) (bool, error)

GetBound determines if a specific capability is currently part of the local bounding set. On systems where the bounding set Value is not present, this function returns an error.

func ResetAmbient

func ResetAmbient() error

ResetAmbient attempts to ensure the Ambient set is fully cleared. It works by first reading the set and if it finds any bits raised it will attempt a reset. This is a workaround for situations where the Ambient API is locked.

func SetAmbient

func SetAmbient(enable bool, val ...Value) error

SetAmbient attempts to set a specific Value bit to the enable state. This function will return an error if insufficient permission is available to perform this task. The settings are performed in order and the function returns immediately an error is detected. Use GetAmbient() to unravel where things went wrong.

func SetGroups

func SetGroups(gid int, suppl ...int) error

SetGroups is a convenience function for robustly setting the GID and all other variants of GID (EGID etc) to the specified value, as well as setting all of the supplementary groups. This function will raise cap.SETGID in order to achieve this operation, and will completely lower the Effective vector of the process before returning.

func SetUID

func SetUID(uid int) error

SetUID is a convenience function for robustly setting the UID and all other variants of UID (EUID etc) to the specified value without dropping the privilege of the current process. This function will raise cap.SETUID in order to achieve this operation, and will completely lower the Effective vector of the process before returning.

Types

type Flag

type Flag uint

Flag is the type of one of the three Value vectors held in a Set.

const (
	Effective Flag = iota
	Permitted
	Inheritable
)

Effective, Permitted, Inheritable are the three vectors of Values held in a Set.

type IAB

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

IAB holds a summary of all of the inheritable capability vectors: Inheritable, Ambient and Bounding sets. The Bounding set entries are inverted insofar as a raised bit here implies that when applied to the current process, the capability is dropped - think of this as synonymous with Blocked. This convention is used to support the empty IAB as being mostly harmless.

func IABFromText

func IABFromText(text string) (*IAB, error)

IABFromText parses a string representing an IAB set, as generated by IAB.String(), to generate an IAB.

func IABGetProc

func IABGetProc() *IAB

IABGetProc summarizes the Inheritable, Ambient and Bounding capabilty vectors of the current process.

func IABInit

func IABInit() *IAB

IABInit returns an empty IAB.

func (*IAB) Fill

func (iab *IAB) Fill(vec Vector, c *Set, flag Flag) error

Fill fills one of the Inheritable, Ambient and Bounding capability vectors from one of the flag vectors of a Set. Note, filling the I vector will mask the A vector, and filling the A vector may raise entries in the I vector. Further, when filling the Bounding vector, the bits are inverted - that is lowered bits from the Set will be raised in the Bounding vector.

func (*IAB) GetVector

func (iab *IAB) GetVector(vec Vector, val Value) (bool, error)

GetVector returns the raised state of the specific capability bit of the indicated vector.

func (*IAB) SetProc

func (iab *IAB) SetProc() error

SetProc attempts to change the Inheritable, Ambient and Bounding capabilty vectors of the current process.

func (*IAB) SetVector

func (iab *IAB) SetVector(vec Vector, raised bool, vals ...Value) error

SetVector sets all of the values in the specified vector to the raised value. Note, the A vector cannot contain values not raised in the I vector, so setting values directly in one vector may have the side effect of mirroring the value in the other vector to maintain this constraint.

func (*IAB) String

func (iab *IAB) String() string

String serializes an IAB to a string format.

type Launcher

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

Launcher holds a configuration for launching a child process with capability state different from (generally more restricted than) the parent.

func NewLauncher

func NewLauncher(path string, args []string, env []string) *Launcher

NewLauncher returns a new launcher for the specified program path and args with the specified environment.

func (*Launcher) Callback

func (attr *Launcher) Callback(fn func(*syscall.ProcAttr, interface{}) error)

Callback specifies a callback for Launch() to call before changing privilege. The only thing that is assumed is that the OS thread in use to call this callback function at launch time will be the one that ultimately calls fork. Any returned error value of said function will terminate the launch process. A nil callback (the default) is ignored. The specified callback fn should not call any "cap" package functions since this may deadlock or generate undefined behavior for the parent process.

func (*Launcher) Launch

func (attr *Launcher) Launch(data interface{}) (int, error)

Launch performs a new program launch with security state specified in the supplied launcher.

func (*Launcher) SetChroot

func (attr *Launcher) SetChroot(root string)

SetChroot specifies the chroot value to be used by the launched command. An empty value means no-change from the prevailing value.

func (*Launcher) SetGroups

func (attr *Launcher) SetGroups(gid int, groups []int)

SetGroups specifies the GID and supplementary groups for the launched command.

func (*Launcher) SetIAB

func (attr *Launcher) SetIAB(iab *IAB)

SetIAB specifies the AIB capability vectors to be inherited by the launched command. A nil value means the prevailing vectors of the parent will be inherited.

func (*Launcher) SetMode

func (attr *Launcher) SetMode(mode Mode)

SetMode specifies the libcap Mode to be used by the launched command.

func (*Launcher) SetUID

func (attr *Launcher) SetUID(uid int)

SetUID specifies the UID to be used by the launched command.

type Mode

type Mode uint

Mode summarizes a complicated secure-bits and capability mode in a libcap preferred way.

const (
	ModeUncertain Mode = iota
	ModeNoPriv
	ModePure1EInit
	ModePure1E
)

ModeUncertain etc are how libcap summarizes security modes involving capabilitys and seure-bits.

func GetMode

func GetMode() Mode

GetMode assesses the current process state and summarizes it as a Mode. This function always succeeds. Unfamiliar modes are declared ModeUncertain.

func (Mode) Set

func (m Mode) Set() error

Set attempts to enter the specified mode. An attempt is made to enter the mode, so if you prefer this operation to be a no-op if entering the same mode, call only if CurrentMode() disagrees with the desired mode.

This function will raise cap.SETPCAP in order to achieve this operation, and will completely lower the Effective vector of the process before returning.

func (Mode) String

func (m Mode) String() string

String returns the libcap conventional string for this mode.

type Secbits

type Secbits uint

Secbits capture the prctl settable secure-bits of a process.

const (
	SecbitNoRoot Secbits = 1 << iota
	SecbitNoRootLocked
	SecbitNoSetUIDFixup
	SecbitNoSetUIDFixupLocked
	SecbitKeepCaps
	SecbitKeepCapsLocked
	SecbitNoCapAmbientRaise
	SecbitNoCapAmbientRaiseLocked
)

SecbitNoRoot etc are the bitmasks associated with the supported Secbit masks. Source: uapi/linux/securebits.h

func GetSecbits

func GetSecbits() Secbits

GetSecbits returns the current setting of the process' Secbits.

func (Secbits) Set

func (s Secbits) Set() error

Set attempts to force the process Secbits to a value. This function will raise cap.SETPCAP in order to achieve this operation, and will completely lower the Effective vector of the process returning.

type Set

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

Set is an opaque capabilities container for a set of system capbilities.

func FromText

func FromText(text string) (*Set, error)

FromText converts the canonical text representation for a Set into a freshly allocated Set.

func GetFd

func GetFd(file *os.File) (*Set, error)

GetFd returns the file capabilities of an open (*os.File).Fd().

func GetFile

func GetFile(path string) (*Set, error)

GetFile returns the file capabilities of a named file.

func GetPID

func GetPID(pid int) (*Set, error)

GetPID returns the capability set associated with the target process id; pid=0 is an alias for current.

func GetProc

func GetProc() *Set

GetProc returns the capability Set of the current process. If the kernel is unable to determine the Set associated with the current process, the function panic()s.

func Import

func Import(d []byte) (*Set, error)

Import imports a Set from a byte array where it has been stored in a portable (lossless) way.

func NewSet

func NewSet() *Set

NewSet returns an empty capability set.

func (*Set) Clear

func (c *Set) Clear() error

Clear fully clears a capability set.

func (*Set) ClearFlag

func (c *Set) ClearFlag(vec Flag) error

ClearFlag clears a specific vector of Values associated with the specified Flag.

func (*Set) Compare

func (c *Set) Compare(d *Set) (uint, error)

Compare returns 0 if c and d are identical in content. Otherwise, this function returns a non-zero value of 3 independent bits: (differE ? 1:0) | (differP ? 2:0) | (differI ? 4:0).

func (*Set) Dup

func (c *Set) Dup() (*Set, error)

Dup returns a copy of the specified capability set.

func (*Set) Export

func (c *Set) Export() ([]byte, error)

Export exports a Set into a lossless byte array format where it is stored in a portable way. Note, any namespace owner in the Set content is not exported by this function.

func (*Set) GetFlag

func (c *Set) GetFlag(vec Flag, val Value) (bool, error)

GetFlag determines if the requested bit is enabled in the Flag vector of the capability Set.

func (*Set) GetNSOwner

func (c *Set) GetNSOwner() (int, error)

GetNSOwner returns the namespace owner UID of the capability Set.

func (*Set) SetFd

func (c *Set) SetFd(file *os.File) error

SetFd attempts to set the file capabilities of an open (*os.File).Fd(). Note, Linux does not store the full Effective Value vector in the metadata for the file. Only a single Effective bit is stored. This single bit is non-zero if the Permitted vector have any overlapping bits with the Effective or Inheritable vector of c. This may seem suboptimal, but the reasoning behind it is sound. Namely, the purpose of the Effective bit it to support capabability unaware binaries that can work if they magically launch with only the needed bits raised (this bit is sometimes referred to simply as the 'legacy' bit). However, the preferred way a binary will actually manipulate its file-acquired capabilities is carefully and deliberately using this package, or libcap for C family code. This function can also be used to delete a file's capabilities, by calling with c = nil.

func (*Set) SetFile

func (c *Set) SetFile(path string) error

SetFile attempts to set the file capabilities of the specfied filename. See the comment for SetFd() for some non-obvious behavior of Linux for the Effective Value vector on the modified file. This function can also be used to delete a file's capabilities, by calling with c = nil.

func (*Set) SetFlag

func (c *Set) SetFlag(vec Flag, enable bool, val ...Value) error

SetFlag sets the requested bits to the indicated enable state. This function does not perform any security checks, so values can be set out-of-order. Only when the Set is used to SetProc() etc., will the bits be checked for validity and permission by the kernel. If the function returns an error, the Set will not be modified.

func (*Set) SetProc

func (c *Set) SetProc() error

SetProc attempts to write the capability Set to the current process. The kernel will perform permission checks and an error will be returned if the attempt fails.

func (*Set) String

func (c *Set) String() string

String converts a full capability Set into it canonical readable string representation (which may contain spaces).

type Value

type Value uint

Value is the type of a single capability (or permission) bit.

const (
	CHOWN Value = iota
	DAC_OVERRIDE
	DAC_READ_SEARCH
	FOWNER
	FSETID
	KILL
	SETGID
	SETUID
	SETPCAP
	LINUX_IMMUTABLE
	NET_BIND_SERVICE
	NET_BROADCAST
	NET_ADMIN
	NET_RAW
	IPC_LOCK
	IPC_OWNER
	SYS_MODULE
	SYS_RAWIO
	SYS_CHROOT
	SYS_PTRACE
	SYS_PACCT
	SYS_ADMIN
	SYS_BOOT
	SYS_NICE
	SYS_RESOURCE
	SYS_TIME
	SYS_TTY_CONFIG
	MKNOD
	LEASE
	AUDIT_WRITE
	AUDIT_CONTROL
	SETFCAP
	MAC_OVERRIDE
	MAC_ADMIN
	SYSLOG
	WAKE_ALARM
	BLOCK_SUSPEND
	AUDIT_READ
	PERFMON
	BPF
)

CHOWN etc., are the named capability bits on this system. The canonical source for each name is the "uapi/linux/capabilities.h" file, which is hard-coded into this package.

func FromName

func FromName(name string) (Value, error)

FromName converts a named capability Value to its binary representation.

func MaxBits

func MaxBits() Value

MaxBits returns the number of kernel-named capabilities discovered at runtime in the current system.

func (Value) String

func (v Value) String() string

String converts a capability Value into its canonical text representation.

type Vector

type Vector int

Vector enumerates which of the inheritable IAB capability vectors is being manipulated.

const (
	Inh Vector = iota
	Amb
	Bound
)

Inh, Amb, Bound enumerate the IAB vector components. IMB.Inh is equivalent Set.Inheritable but they are named differently for syntax/type checking reasons.

Source Files

  • cap.go
  • convenience.go
  • file.go
  • flags.go
  • iab.go
  • launch.go
  • modern.go
  • names.go
  • oslocks.go
  • syscalls_cgo.go
  • text.go

Jump to

Keyboard shortcuts

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