Debian Codegraph @

internal/testutils/token_linux.go

raw symbols SCIP
1 //go:build unix
2
3 package testutils
4
5 import (
6 "fmt"
7 "math"
8 "os"
9 "os/exec"
10 "regexp"
11 "slices"
12 "strconv"
13 "strings"
14 "syscall"
15 "testing"
16
17 "github.com/cilium/ebpf/internal/platform"
18 "github.com/cilium/ebpf/internal/unix"
19 )
20
21 // The logic in this file implements running tests with BPF tokens. The process
22 // works as follows:
23 //
24 // 1. A test or subtest calls [RunWithToken], which runs the test binary as a
25 // subprocess in its own user and mount namespace.
26 // 2. Child and parent work together to set up a bpffs with the desired
27 // delegated permissions.
28 // 3. The child mounts the token bpffs, drops capabilities and re-execs itself.
29 //
30 // The [setupUserNS] environment variable is set if child-side setup needs to
31 // take place. The [testUserNS] environment variable is set by the child before
32 // re-execing itself to signal that setup is done and the function under test
33 // can be run.
34
35 const (
36 // testUserNS being set indicates that setup is done and the test can be run.
37 // Set in the child process after user namespace setup is done and before
38 // re-execing itself.
39 testUserNS = "TEST_USERNS"
40
41 readyMarker = byte(0x60)
42
43 // File descriptors passed to [exec.Cmd.ExtraFiles] start at fd 3, being the
44 // to-parent socket in the child process.
45 toParentFd = 3
46 )
47
48 func init() {
49 // Before running any tests, check if we're a child process that needs to do
50 // user namespace setup and re-exec.
51 _, ok := os.LookupEnv(setupUserNS)
52 if !ok {
53 return
54 }
55 os.Unsetenv(setupUserNS)
56
57 // Note: this function never returns; it ends with a call to exec().
58 setupChildExec()
59 }
60
61 // RunWithToken runs fn as a subtest as an unprivileged, user-namespaced
62 // subprocess with only the given BPF permissions delegated to it. The subtest
63 // carries the given name.
64 //
65 // The subprocess retains CAP_BPF and CAP_DAC_READ_SEARCH to make BPF() syscalls
66 // with a token and read files owned by the test user.
67 //
68 // testutils.RunWithToken(t, "foo", testutils.Delegated{
69 // Cmds: []sys.Cmd{sys.BPF_MAP_CREATE},
70 // Maps: []sys.MapType{sys.BPF_MAP_TYPE_HASH},
71 // }, func(t *testing.T) {
72 // _, err := newMap(t, hashMapSpec, nil)
73 // qt.Assert(t, qt.IsNil(err))
74 // })
75 //
76 // Only works on Linux 6.9 and later.
77 func RunWithToken(t *testing.T, name string, delegated Delegated, fn func(t *testing.T)) {
78 t.Helper()
79
80 if !platform.IsLinux {
81 t.Skip("BPF tokens only work on Linux")
82 }
83
84 SkipOnOldKernel(t, "6.9", "BPF_TOKEN_CREATE")
85
86 t.Run(name, func(t *testing.T) {
87 // User namespace setup done. Run the function under test and end the test.
88 if _, ok := os.LookupEnv(testUserNS); ok {
89 fn(t)
90 return
91 }
92
93 // Execute the parent side of the test, which will spawn the child process
94 // and wait for it to finish.
95 runSubprocess(t, delegated)
96 })
97 }
98
99 func runSubprocess(t *testing.T, delegated Delegated) {
100 t.Helper()
101
102 args := []string{
103 // Re-run only the exact test and subtest.
104 splitTestRun(t),
105 // Run the subprocess in test2json mode so all stdout lines belonging to
106 // the test framework are prefixed with a marker byte (0x16 or ^V in caret
107 // notation).
108 "-test.v=test2json",
109 }
110
111 exe, err := os.Executable()
112 if err != nil {
113 t.Fatalf("get executable path: %v", err)
114 }
115
116 cmd := exec.CommandContext(t.Context(), exe, args...)
117
118 // Signal to the child process that it needs to do user namespace setup.
119 cmd.Env = append(cmd.Environ(), setupUserNS+"=true")
120
121 stdout := newt2jParser(t, os.Stdout)
122 cmd.Stdout = stdout
123 cmd.Stderr = os.Stderr
124
125 pair, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)
126 if err != nil {
127 t.Fatalf("create socket pair: %v", err)
128 }
129 toChild := pair[0]
130 defer unix.Close(toChild)
131
132 toParent := os.NewFile(uintptr(pair[1]), "child-to-parent-socket")
133 defer toParent.Close()
134
135 cmd.ExtraFiles = []*os.File{toParent}
136 cmd.SysProcAttr = &unix.SysProcAttr{
137 Cloneflags: unix.CLONE_NEWUSER | unix.CLONE_NEWNS,
138 AmbientCaps: []uintptr{uintptr(CAP_SYS_ADMIN), uintptr(CAP_DAC_READ_SEARCH), uintptr(CAP_BPF)},
139 UidMappings: mapUID(),
140 GidMappings: mapGID(),
141 }
142
143 if err := cmd.Start(); err != nil {
144 t.Fatalf("start child process: %v", err)
145 }
146
147 // Explicitly close the parent's copy of the to-parent socket, so that the
148 // child can detect when the parent process has exited and avoid hanging if
149 // the parent is killed.
150 if err := toParent.Close(); err != nil {
151 t.Fatalf("close child-to-parent socket in parent: %v", err)
152 }
153
154 if err := setupParent(toChild, delegated); err != nil {
155 // Clean up child before failing the test to avoid orphaned processes.
156 _ = cmd.Process.Kill()
157 _ = cmd.Wait()
158
159 t.Fatalf("parent setup: %v", err)
160 }
161
162 if err := cmd.Wait(); err != nil && !stdout.failed {
163 t.Fatalf("child process exited with error: %v", err)
164 }
165
166 stdout.Apply()
167 }
168
169 // splitTestRun returns the '-test.run' argument needed to re-run the current
170 // test as a child process. 'go test' assigns specific meaning to the '/'
171 // separator in test names, so each individual part needs to be wrapped as a
172 // regex matching the exact (sub)test.
173 //
174 // For example, if the current test is "TestFoo/bar/baz", the returned argument
175 // will be:
176 //
177 // -test.run=^TestFoo$/^bar$/^baz$
178 func splitTestRun(tb testing.TB) string {
179 tb.Helper()
180
181 parts := strings.Split(tb.Name(), "/")
182 for i, part := range parts {
183 parts[i] = "^" + regexp.QuoteMeta(part) + "$"
184 }
185 return "-test.run=" + strings.Join(parts, "/")
186 }
187
188 // mapUID returns a list of UID mappings for the user namespace. It includes the
189 // current UID and, if running with sudo, the SUDO_UID. This allows the child
190 // process to have the same permissions as the parent process in the user
191 // namespace.
192 func mapUID() []syscall.SysProcIDMap {
193 uids := []int{os.Getuid()}
194 if suid, _ := strconv.Atoi(os.Getenv("SUDO_UID")); suid != 0 && !slices.Contains(uids, suid) {
195 uids = append(uids, suid)
196 }
197
198 var umap []syscall.SysProcIDMap
199 for _, uid := range uids {
200 umap = append(umap, syscall.SysProcIDMap{
201 ContainerID: uid,
202 HostID: uid,
203 Size: 1,
204 })
205 }
206
207 return umap
208 }
209
210 // mapGID is like [mapUID] but for GIDs.
211 func mapGID() []syscall.SysProcIDMap {
212 gids := []int{os.Getgid()}
213 if sgid, _ := strconv.Atoi(os.Getenv("SUDO_GID")); sgid != 0 && !slices.Contains(gids, sgid) {
214 gids = append(gids, sgid)
215 }
216
217 var gmap []syscall.SysProcIDMap
218 for _, gid := range gids {
219 gmap = append(gmap, syscall.SysProcIDMap{
220 ContainerID: gid,
221 HostID: gid,
222 Size: 1,
223 })
224 }
225
226 return gmap
227 }
228
229 // setupParent performs the parent-side setup for a token-scoped test. It
230 // receives the bpffs file descriptor from the child, configures it with the
231 // delegated permissions and signals the child to continue.
232 func setupParent(toChild int, delegated Delegated) error {
233 bpffs, err := receiveFD(toChild)
234 if err != nil {
235 return fmt.Errorf("receive bpffs file descriptor from child: %w", err)
236 }
237 defer unix.Close(bpffs)
238
239 if err := configureDelegated(bpffs, delegated); err != nil {
240 return fmt.Errorf("configure delegated permissions on bpffs: %w", err)
241 }
242
243 if err := sendReady(toChild); err != nil {
244 return fmt.Errorf("send ready signal to child: %w", err)
245 }
246
247 return nil
248 }
249
250 // setupChildExec does the child-side setup for a token-scoped test and re-execs
251 // the test binary. The function never returns.
252 func setupChildExec() {
253 // Create a new bpffs file system context.
254 bpffsCtx, err := unix.Fsopen("bpf", unix.FSOPEN_CLOEXEC)
255 if err != nil {
256 panicf("create bpffs context: %v", err)
257 }
258
259 // Send the bpffs fd to the parent process so it can delegate permissions to
260 // it.
261 if err := sendFD(toParentFd, bpffsCtx); err != nil {
262 panicf("send bpffs fd to parent: %v", err)
263 }
264
265 // Wait for the parent's ready signal delegation is done.
266 if err := waitReady(toParentFd); err != nil {
267 panicf("wait for parent's reply: %v", err)
268 }
269
270 if err := unix.Close(toParentFd); err != nil {
271 panicf("close child socket: %v", err)
272 }
273
274 // Turn the filesystem context into an anonymous mount.
275 bpffsMnt, err := unix.Fsmount(bpffsCtx, unix.FSMOUNT_CLOEXEC, 0)
276 if err != nil {
277 panicf("mount bpffs: %v", err)
278 }
279
280 if err := unix.Close(bpffsCtx); err != nil {
281 panicf("close bpffs context: %v", err)
282 }
283
284 // Move the detached mount to /sys/fs/bpf, the default location.
285 if err := unix.MoveMount(bpffsMnt, "", unix.AT_FDCWD, "/sys/fs/bpf", unix.MOVE_MOUNT_F_EMPTY_PATH); err != nil {
286 panicf("move mount: %v", err)
287 }
288
289 if err := unix.Close(bpffsMnt); err != nil {
290 panicf("close bpffs mount fd: %v", err)
291 }
292
293 // Drop all but the following capabilities:
294 //
295 // - CAP_BPF for making BPF() syscalls with a token
296 // - CAP_DAC_READ_SEARCH for reading files owned by the user running the test,
297 // as we'll be `nobody` in the user namespace.
298 const caps = (uint64(1) << CAP_BPF) | (uint64(1) << CAP_DAC_READ_SEARCH)
299 if err := capset(capUserData{caps, caps, caps}); err != nil {
300 panicf("drop capabilities in child: %v", err)
301 }
302
303 // Setup done, re-exec and signal the child to run the function under test.
304 if err := os.Setenv(testUserNS, "true"); err != nil {
305 panicf("set test environment variable: %v", err)
306 }
307
308 if err := syscall.Exec(os.Args[0], os.Args, os.Environ()); err != nil {
309 panicf("re-exec child process: %v", err)
310 }
311 }
312
313 // sendFD sends fd over sock.
314 func sendFD(sock, fd int) error {
315 // According to the man pages, one byte of non-ancillary data must be sent
316 // (and received) along with the fd.
317 if err := unix.Sendmsg(sock, []byte{0}, unix.UnixRights(fd), nil, 0); err != nil {
318 return fmt.Errorf("send fd to parent: %w", err)
319 }
320
321 return nil
322 }
323
324 // receiveFD receives a file descriptor from sock.
325 func receiveFD(sock int) (int, error) {
326 // Allocate 4 bytes for receiving an fd.
327 buf := make([]byte, unix.CmsgSpace(unix.SizeofInt))
328
329 // Receive message, read out-of-band data containing fd, ignore payload.
330 _, oobn, _, _, err := unix.Recvmsg(sock, []byte{0}, buf, unix.MSG_CMSG_CLOEXEC)
331 if err != nil {
332 return -1, fmt.Errorf("recvmsg: %w", err)
333 }
334
335 // Parse the control messages.
336 msgs, err := unix.ParseSocketControlMessage(buf[:oobn])
337 if err != nil {
338 return -1, fmt.Errorf("parse socket control message: %w", err)
339 }
340
341 if len(msgs) != 1 {
342 return -1, fmt.Errorf("expected 1 control message, got: %d", len(msgs))
343 }
344
345 // Extract fds from the control message.
346 fds, err := unix.ParseUnixRights(&msgs[0])
347 if err != nil {
348 return -1, fmt.Errorf("parse unix rights: %w", err)
349 }
350
351 if len(fds) != 1 {
352 return -1, fmt.Errorf("expected 1 fd, got: %d", len(fds))
353 }
354
355 return fds[0], nil
356 }
357
358 // sendReady sends a message to the child over sock indicating that bpffs
359 // delegation is done.
360 func sendReady(sock int) error {
361 if err := unix.Sendmsg(sock, []byte{readyMarker}, nil, nil, 0); err != nil {
362 return fmt.Errorf("send ready marker: %w", err)
363 }
364
365 return nil
366 }
367
368 // waitReady waits for a message from the parent over sock indicating that the
369 // child can continue with the test.
370 func waitReady(sock int) error {
371 var buf [1]byte
372 n, _, _, _, err := unix.Recvmsg(sock, buf[:], nil, 0)
373 if err != nil {
374 return fmt.Errorf("receive message: %w", err)
375 }
376
377 if n != 1 {
378 return fmt.Errorf("short read waiting for ready marker: %d", n)
379 }
380
381 if buf[0] != readyMarker {
382 return fmt.Errorf("message did not contain %x", readyMarker)
383 }
384
385 return nil
386 }
387
388 // configureDelegated configures the bpffs file descriptor with the given
389 // delegated permissions.
390 func configureDelegated(bpffs int, delegated Delegated) error {
391 if err := delegateFSConfig(bpffs, "delegate_cmds", delegated.Cmds); err != nil {
392 return err
393 }
394 if err := delegateFSConfig(bpffs, "delegate_maps", delegated.Maps); err != nil {
395 return err
396 }
397 if err := delegateFSConfig(bpffs, "delegate_progs", delegated.Progs); err != nil {
398 return err
399 }
400 if err := delegateFSConfig(bpffs, "delegate_attachs", delegated.AttachTypes); err != nil {
401 return err
402 }
403 if err := unix.FsconfigCreate(bpffs); err != nil {
404 return fmt.Errorf("create fsconfig: %w", err)
405 }
406 return nil
407 }
408
409 func delegateFSConfig[T ~uint32](bpffs int, key string, delegates []T) error {
410 d, err := delegateToHex(delegates)
411 if err != nil {
412 return fmt.Errorf("convert delegated permissions to hex: %w", err)
413 }
414 if err := unix.FsconfigSetString(bpffs, key, d); err != nil {
415 return fmt.Errorf("set fsconfig %s: %w", key, err)
416 }
417 return nil
418 }
419
420 // delegateToHex takes a list of cmd/map/program/attach types and returns a hex
421 // string of the ORed bitmask of those types. Returns 'any' if the list contains
422 // math.MaxUint32, which is the value used by the kernel to indicate that all
423 // types of that kind are delegated.
424 func delegateToHex[T ~uint32](types []T) (string, error) {
425 const delegateAny = math.MaxUint32
426
427 var res uint64
428 for _, v := range types {
429 if uint32(v) == delegateAny {
430 return "any", nil
431 }
432 if v >= 64 {
433 return "", fmt.Errorf("delegate value out of range: %d", v)
434 }
435 res |= uint64(1) << v
436 }
437
438 return fmt.Sprintf("0x%x", res), nil
439 }
440
441 func panicf(format string, args ...any) {
442 panic(fmt.Sprintf(format, args...))
443 }