Debian Codegraph @

internal/sys/token.go

raw symbols SCIP
1 package sys
2
3 import (
4 "errors"
5 "fmt"
6 "sync"
7 "unsafe"
8
9 "github.com/cilium/ebpf/internal"
10 "github.com/cilium/ebpf/internal/mountinfo"
11 "github.com/cilium/ebpf/internal/platform"
12 "github.com/cilium/ebpf/internal/testutils/testmain"
13 "github.com/cilium/ebpf/internal/unix"
14 )
15
16 var (
17 // ErrTokenCapabilities indicates that the operation failed due to
18 // insufficient capabilities being delegated to the token.
19 ErrTokenCapabilities = errors.New("token insufficiently privileged")
20 )
21
22 // Token is a BPF token that can be used to create BPF objects that normally
23 // require CAP_SYS_ADMIN or CAP_NET_ADMIN.
24 //
25 // With a valid token, equivalent BPF objects can be created while only being
26 // granted CAP_BPF.
27 type Token struct {
28 fd *FD
29
30 // Token info is available as of Linux 6.17, may be nil.
31 info *TokenInfo
32 }
33
34 // FD returns the raw file descriptor of the token.
35 func (t *Token) FD() int {
36 return t.fd.Int()
37 }
38
39 // Capable returns an error if the token does not allow using cmd or some of its
40 // provided attributes.
41 //
42 // Always returns nil on kernels before 6.17, as they don't provide token info.
43 func (t *Token) Capable(cmd Cmd, attr unsafe.Pointer) error {
44 if t.info == nil {
45 return nil
46 }
47
48 if !t.cmd(cmd) {
49 return fmt.Errorf("command %s: %w", cmd, ErrTokenCapabilities)
50 }
51
52 switch cmd {
53 case BPF_MAP_CREATE:
54 attr := (*MapCreateAttr)(attr)
55 if !t.mapType(attr.MapType) {
56 return fmt.Errorf("map type %s: %w", attr.MapType, ErrTokenCapabilities)
57 }
58
59 case BPF_PROG_LOAD:
60 attr := (*ProgLoadAttr)(attr)
61 if !t.progType(attr.ProgType) {
62 return fmt.Errorf("program type %s: %w", attr.ProgType, ErrTokenCapabilities)
63 }
64
65 if !t.attachType(attr.ExpectedAttachType) {
66 return fmt.Errorf("attach type %s: %w", attr.ExpectedAttachType, ErrTokenCapabilities)
67 }
68 }
69
70 return nil
71 }
72
73 // cmd returns true if cmd is allowed by the Token.
74 func (t *Token) cmd(cmd Cmd) bool {
75 if t.info == nil {
76 return true
77 }
78 return t.info.AllowedCmds&(uint64(1)<<cmd) != 0
79 }
80
81 // mapType returns true if the token allows creation of the given MapType.
82 func (t *Token) mapType(mt MapType) bool {
83 if t.info == nil {
84 return true
85 }
86 return t.info.AllowedMaps&(uint64(1)<<mt) != 0
87 }
88
89 // progType returns true if the token allows creation of the given ProgType.
90 func (t *Token) progType(pt ProgType) bool {
91 if t.info == nil {
92 return true
93 }
94 return t.info.AllowedProgs&(uint64(1)<<pt) != 0
95 }
96
97 // attachType returns true if the token allows using the given AttachType.
98 func (t *Token) attachType(at AttachType) bool {
99 if t.info == nil {
100 return true
101 }
102 return t.info.AllowedAttachs&(uint64(1)<<at) != 0
103 }
104
105 var (
106 tokenOnce sync.Once
107 token *Token
108 tokenErr error
109 )
110
111 // getToken attempts to create a BPF token by enumerating all bpffs mounts and
112 // issuing a token from each of them until it yields a valid one. Its result is
113 // cached for the lifetime of the process.
114 //
115 // Returns a nil token if one could not be created. If the OS is not Linux,
116 // additionally returns an error wrapping [internal.ErrNotSupportedOnOS].
117 func getToken() (*Token, error) {
118 tokenOnce.Do(func() {
119 token, tokenErr = findToken()
120
121 // Forget the fd, we are intentionally leaking it for caching purposes.
122 if token != nil {
123 testmain.ForgetFD(token.FD())
124 }
125 })
126
127 return token, tokenErr
128 }
129
130 func findToken() (*Token, error) {
131 if !platform.IsLinux {
132 return nil, fmt.Errorf("bpf token: %w", internal.ErrNotSupportedOnOS)
133 }
134
135 mounts, err := mountinfo.FindByFSType("bpf")
136 if err != nil {
137 return nil, fmt.Errorf("get bpffs mounts: %w", err)
138 }
139
140 for _, mount := range mounts {
141 tok, err := newToken(mount)
142 if errors.Is(err, unix.EACCES) || // lacking privileges to open mount dir
143 errors.Is(err, unix.EINVAL) || // tokens not supported or mount not a bpffs
144 errors.Is(err, unix.EPERM) || // CAP_BPF missing or mount not owned by current user namespace
145 errors.Is(err, unix.EOPNOTSUPP) || // cannot use token in init user namespace
146 errors.Is(err, unix.ENOENT) { // no permissions delegated to this bpffs
147 continue
148 }
149 if err != nil {
150 // Fail on any unexpected errors, since the list of mounts is already
151 // filtered down to bpffs only, and we don't expect any transient errors
152 // from the kernel. If errors occur like EACCES due to ACLs or EMFILE due
153 // to fd limits, it's better to flag this to the user to avoid surprises.
154 return nil, fmt.Errorf("create token from %q: %w", mount, err)
155 }
156 if tok != nil {
157 return tok, nil
158 }
159 }
160
161 return nil, nil
162 }
163
164 func newToken(mount string) (*Token, error) {
165 fsfd, err := unix.Open(mount, unix.O_DIRECTORY|unix.O_RDONLY, 0)
166 if err != nil {
167 return nil, fmt.Errorf("open bpffs mount %q: %w", mount, err)
168 }
169 defer unix.Close(fsfd)
170
171 tfd, err := TokenCreate(&TokenCreateAttr{BpffsFd: uint32(fsfd)})
172 if err != nil {
173 return nil, err
174 }
175
176 t := &Token{
177 fd: tfd,
178 }
179
180 var ti TokenInfo
181 if err := ObjInfo(tfd, &ti); err == nil {
182 t.info = &ti
183 } else if !errors.Is(err, unix.EINVAL) {
184 _ = tfd.Close()
185 return nil, fmt.Errorf("get token info: %w", err)
186 }
187
188 return t, nil
189 }
190
191 // tokenAttr sets the appropriate token fields in the BPF syscall attribute
192 // struct for the given command, if a token is available.
193 func tokenAttr(cmd Cmd, attr unsafe.Pointer) (*Token, error) {
194 switch cmd {
195 case BPF_MAP_CREATE, BPF_PROG_LOAD, BPF_BTF_LOAD:
196 default:
197 return nil, nil
198 }
199
200 tok, err := getToken()
201 if err != nil {
202 return nil, fmt.Errorf("get token: %w", err)
203 }
204 if tok == nil {
205 return nil, nil
206 }
207
208 switch cmd {
209 case BPF_MAP_CREATE:
210 attr := (*MapCreateAttr)(attr)
211 attr.MapTokenFd = int32(tok.FD())
212 attr.MapFlags |= BPF_F_TOKEN_FD
213
214 case BPF_PROG_LOAD:
215 attr := (*ProgLoadAttr)(attr)
216 attr.ProgTokenFd = int32(tok.FD())
217 attr.ProgFlags |= BPF_F_TOKEN_FD
218
219 case BPF_BTF_LOAD:
220 attr := (*BtfLoadAttr)(attr)
221 attr.BtfTokenFd = int32(tok.FD())
222 attr.BtfFlags |= BPF_F_TOKEN_FD
223 }
224
225 return tok, nil
226 }