package sys import ( "errors" "fmt" "sync" "unsafe" "github.com/cilium/ebpf/internal" "github.com/cilium/ebpf/internal/mountinfo" "github.com/cilium/ebpf/internal/platform" "github.com/cilium/ebpf/internal/testutils/testmain" "github.com/cilium/ebpf/internal/unix" ) var ( // ErrTokenCapabilities indicates that the operation failed due to // insufficient capabilities being delegated to the token. ErrTokenCapabilities = errors.New("token insufficiently privileged") ) // Token is a BPF token that can be used to create BPF objects that normally // require CAP_SYS_ADMIN or CAP_NET_ADMIN. // // With a valid token, equivalent BPF objects can be created while only being // granted CAP_BPF. type Token struct { fd *FD // Token info is available as of Linux 6.17, may be nil. info *TokenInfo } // FD returns the raw file descriptor of the token. func (t *Token) FD() int { return t.fd.Int() } // Capable returns an error if the token does not allow using cmd or some of its // provided attributes. // // Always returns nil on kernels before 6.17, as they don't provide token info. func (t *Token) Capable(cmd Cmd, attr unsafe.Pointer) error { if t.info == nil { return nil } if !t.cmd(cmd) { return fmt.Errorf("command %s: %w", cmd, ErrTokenCapabilities) } switch cmd { case BPF_MAP_CREATE: attr := (*MapCreateAttr)(attr) if !t.mapType(attr.MapType) { return fmt.Errorf("map type %s: %w", attr.MapType, ErrTokenCapabilities) } case BPF_PROG_LOAD: attr := (*ProgLoadAttr)(attr) if !t.progType(attr.ProgType) { return fmt.Errorf("program type %s: %w", attr.ProgType, ErrTokenCapabilities) } if !t.attachType(attr.ExpectedAttachType) { return fmt.Errorf("attach type %s: %w", attr.ExpectedAttachType, ErrTokenCapabilities) } } return nil } // cmd returns true if cmd is allowed by the Token. func (t *Token) cmd(cmd Cmd) bool { if t.info == nil { return true } return t.info.AllowedCmds&(uint64(1)<