summaryrefslogtreecommitdiff
path: root/tools/testing/selftests/bpf/prog_tests/token.c
blob: fc4a175d8d76f15a5b22dd9b0252418bed7b3c53 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
// SPDX-License-Identifier: GPL-2.0
/* Copyright (c) 2023 Meta Platforms, Inc. and affiliates. */
#define _GNU_SOURCE
#include <test_progs.h>
#include <bpf/btf.h>
#include "cap_helpers.h"
#include <fcntl.h>
#include <sched.h>
#include <signal.h>
#include <unistd.h>
#include <linux/filter.h>
#include <linux/unistd.h>
#include <linux/mount.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/un.h>
#include "priv_map.skel.h"
#include "priv_prog.skel.h"
#include "dummy_st_ops_success.skel.h"
#include "token_lsm.skel.h"

static inline int sys_mount(const char *dev_name, const char *dir_name,
			    const char *type, unsigned long flags,
			    const void *data)
{
	return syscall(__NR_mount, dev_name, dir_name, type, flags, data);
}

static inline int sys_fsopen(const char *fsname, unsigned flags)
{
	return syscall(__NR_fsopen, fsname, flags);
}

static inline int sys_fspick(int dfd, const char *path, unsigned flags)
{
	return syscall(__NR_fspick, dfd, path, flags);
}

static inline int sys_fsconfig(int fs_fd, unsigned cmd, const char *key, const void *val, int aux)
{
	return syscall(__NR_fsconfig, fs_fd, cmd, key, val, aux);
}

static inline int sys_fsmount(int fs_fd, unsigned flags, unsigned ms_flags)
{
	return syscall(__NR_fsmount, fs_fd, flags, ms_flags);
}

static inline int sys_move_mount(int from_dfd, const char *from_path,
				 int to_dfd, const char *to_path,
				 unsigned flags)
{
	return syscall(__NR_move_mount, from_dfd, from_path, to_dfd, to_path, flags);
}

static int drop_priv_caps(__u64 *old_caps)
{
	return cap_disable_effective((1ULL << CAP_BPF) |
				     (1ULL << CAP_PERFMON) |
				     (1ULL << CAP_NET_ADMIN) |
				     (1ULL << CAP_SYS_ADMIN), old_caps);
}

static int restore_priv_caps(__u64 old_caps)
{
	return cap_enable_effective(old_caps, NULL);
}

static int set_delegate_mask(int fs_fd, const char *key, __u64 mask, const char *mask_str)
{
	char buf[32];
	int err;

	if (!mask_str) {
		if (mask == ~0ULL) {
			mask_str = "any";
		} else {
			snprintf(buf, sizeof(buf), "0x%llx", (unsigned long long)mask);
			mask_str = buf;
		}
	}

	err = sys_fsconfig(fs_fd, FSCONFIG_SET_STRING, key,
			   mask_str, 0);
	if (err < 0)
		err = -errno;
	return err;
}

#define zclose(fd) do { if (fd >= 0) close(fd); fd = -1; } while (0)

struct bpffs_opts {
	__u64 cmds;
	__u64 maps;
	__u64 progs;
	__u64 attachs;
	const char *cmds_str;
	const char *maps_str;
	const char *progs_str;
	const char *attachs_str;
};

static int create_bpffs_fd(void)
{
	int fs_fd;

	/* create VFS context */
	fs_fd = sys_fsopen("bpf", 0);
	ASSERT_GE(fs_fd, 0, "fs_fd");

	return fs_fd;
}

static int materialize_bpffs_fd(int fs_fd, struct bpffs_opts *opts)
{
	int mnt_fd, err;

	/* set up token delegation mount options */
	err = set_delegate_mask(fs_fd, "delegate_cmds", opts->cmds, opts->cmds_str);
	if (!ASSERT_OK(err, "fs_cfg_cmds"))
		return err;
	err = set_delegate_mask(fs_fd, "delegate_maps", opts->maps, opts->maps_str);
	if (!ASSERT_OK(err, "fs_cfg_maps"))
		return err;
	err = set_delegate_mask(fs_fd, "delegate_progs", opts->progs, opts->progs_str);
	if (!ASSERT_OK(err, "fs_cfg_progs"))
		return err;
	err = set_delegate_mask(fs_fd, "delegate_attachs", opts->attachs, opts->attachs_str);
	if (!ASSERT_OK(err, "fs_cfg_attachs"))
		return err;

	/* instantiate FS object */
	err = sys_fsconfig(fs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0);
	if (err < 0)
		return -errno;

	/* create O_PATH fd for detached mount */
	mnt_fd = sys_fsmount(fs_fd, 0, 0);
	if (err < 0)
		return -errno;

	return mnt_fd;
}

/* send FD over Unix domain (AF_UNIX) socket */
static int sendfd(int sockfd, int fd)
{
	struct msghdr msg = {};
	struct cmsghdr *cmsg;
	int fds[1] = { fd }, err;
	char iobuf[1];
	struct iovec io = {
		.iov_base = iobuf,
		.iov_len = sizeof(iobuf),
	};
	union {
		char buf[CMSG_SPACE(sizeof(fds))];
		struct cmsghdr align;
	} u;

	msg.msg_iov = &io;
	msg.msg_iovlen = 1;
	msg.msg_control = u.buf;
	msg.msg_controllen = sizeof(u.buf);
	cmsg = CMSG_FIRSTHDR(&msg);
	cmsg->cmsg_level = SOL_SOCKET;
	cmsg->cmsg_type = SCM_RIGHTS;
	cmsg->cmsg_len = CMSG_LEN(sizeof(fds));
	memcpy(CMSG_DATA(cmsg), fds, sizeof(fds));

	err = sendmsg(sockfd, &msg, 0);
	if (err < 0)
		err = -errno;
	if (!ASSERT_EQ(err, 1, "sendmsg"))
		return -EINVAL;

	return 0;
}

/* receive FD over Unix domain (AF_UNIX) socket */
static int recvfd(int sockfd, int *fd)
{
	struct msghdr msg = {};
	struct cmsghdr *cmsg;
	int fds[1], err;
	char iobuf[1];
	struct iovec io = {
		.iov_base = iobuf,
		.iov_len = sizeof(iobuf),
	};
	union {
		char buf[CMSG_SPACE(sizeof(fds))];
		struct cmsghdr align;
	} u;

	msg.msg_iov = &io;
	msg.msg_iovlen = 1;
	msg.msg_control = u.buf;
	msg.msg_controllen = sizeof(u.buf);

	err = recvmsg(sockfd, &msg, 0);
	if (err < 0)
		err = -errno;
	if (!ASSERT_EQ(err, 1, "recvmsg"))
		return -EINVAL;

	cmsg = CMSG_FIRSTHDR(&msg);
	if (!ASSERT_OK_PTR(cmsg, "cmsg_null") ||
	    !ASSERT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(fds)), "cmsg_len") ||
	    !ASSERT_EQ(cmsg->cmsg_level, SOL_SOCKET, "cmsg_level") ||
	    !ASSERT_EQ(cmsg->cmsg_type, SCM_RIGHTS, "cmsg_type"))
		return -EINVAL;

	memcpy(fds, CMSG_DATA(cmsg), sizeof(fds));
	*fd = fds[0];

	return 0;
}

static ssize_t write_nointr(int fd, const void *buf, size_t count)
{
	ssize_t ret;

	do {
		ret = write(fd, buf, count);
	} while (ret < 0 && errno == EINTR);

	return ret;
}

static int write_file(const char *path, const void *buf, size_t count)
{
	int fd;
	ssize_t ret;

	fd = open(path, O_WRONLY | O_CLOEXEC | O_NOCTTY | O_NOFOLLOW);
	if (fd < 0)
		return -1;

	ret = write_nointr(fd, buf, count);
	close(fd);
	if (ret < 0 || (size_t)ret != count)
		return -1;

	return 0;
}

static int create_and_enter_userns(void)
{
	uid_t uid;
	gid_t gid;
	char map[100];

	uid = getuid();
	gid = getgid();

	if (unshare(CLONE_NEWUSER))
		return -1;

	if (write_file("/proc/self/setgroups", "deny", sizeof("deny") - 1) &&
	    errno != ENOENT)
		return -1;

	snprintf(map, sizeof(map), "0 %d 1", uid);
	if (write_file("/proc/self/uid_map", map, strlen(map)))
		return -1;


	snprintf(map, sizeof(map), "0 %d 1", gid);
	if (write_file("/proc/self/gid_map", map, strlen(map)))
		return -1;

	if (setgid(0))
		return -1;

	if (setuid(0))
		return -1;

	return 0;
}

typedef int (*child_callback_fn)(int bpffs_fd, struct token_lsm *lsm_skel);

static void child(int sock_fd, struct bpffs_opts *opts, child_callback_fn callback)
{
	int mnt_fd = -1, fs_fd = -1, err = 0, bpffs_fd = -1, token_fd = -1;
	struct token_lsm *lsm_skel = NULL;

	/* load and attach LSM "policy" before we go into unpriv userns */
	lsm_skel = token_lsm__open_and_load();
	if (!ASSERT_OK_PTR(lsm_skel, "lsm_skel_load")) {
		err = -EINVAL;
		goto cleanup;
	}
	lsm_skel->bss->my_pid = getpid();
	err = token_lsm__attach(lsm_skel);
	if (!ASSERT_OK(err, "lsm_skel_attach"))
		goto cleanup;

	/* setup userns with root mappings */
	err = create_and_enter_userns();
	if (!ASSERT_OK(err, "create_and_enter_userns"))
		goto cleanup;

	/* setup mountns to allow creating BPF FS (fsopen("bpf")) from unpriv process */
	err = unshare(CLONE_NEWNS);
	if (!ASSERT_OK(err, "create_mountns"))
		goto cleanup;

	err = sys_mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, 0);
	if (!ASSERT_OK(err, "remount_root"))
		goto cleanup;

	fs_fd = create_bpffs_fd();
	if (!ASSERT_GE(fs_fd, 0, "create_bpffs_fd")) {
		err = -EINVAL;
		goto cleanup;
	}

	/* ensure unprivileged child cannot set delegation options */
	err = set_delegate_mask(fs_fd, "delegate_cmds", 0x1, NULL);
	ASSERT_EQ(err, -EPERM, "delegate_cmd_eperm");
	err = set_delegate_mask(fs_fd, "delegate_maps", 0x1, NULL);
	ASSERT_EQ(err, -EPERM, "delegate_maps_eperm");
	err = set_delegate_mask(fs_fd, "delegate_progs", 0x1, NULL);
	ASSERT_EQ(err, -EPERM, "delegate_progs_eperm");
	err = set_delegate_mask(fs_fd, "delegate_attachs", 0x1, NULL);
	ASSERT_EQ(err, -EPERM, "delegate_attachs_eperm");

	/* pass BPF FS context object to parent */
	err = sendfd(sock_fd, fs_fd);
	if (!ASSERT_OK(err, "send_fs_fd"))
		goto cleanup;
	zclose(fs_fd);

	/* avoid mucking around with mount namespaces and mounting at
	 * well-known path, just get detach-mounted BPF FS fd back from parent
	 */
	err = recvfd(sock_fd, &mnt_fd);
	if (!ASSERT_OK(err, "recv_mnt_fd"))
		goto cleanup;

	/* try to fspick() BPF FS and try to add some delegation options */
	fs_fd = sys_fspick(mnt_fd, "", FSPICK_EMPTY_PATH);
	if (!ASSERT_GE(fs_fd, 0, "bpffs_fspick")) {
		err = -EINVAL;
		goto cleanup;
	}

	/* ensure unprivileged child cannot reconfigure to set delegation options */
	err = set_delegate_mask(fs_fd, "delegate_cmds", 0, "any");
	if (!ASSERT_EQ(err, -EPERM, "delegate_cmd_eperm_reconfig")) {
		err = -EINVAL;
		goto cleanup;
	}
	err = set_delegate_mask(fs_fd, "delegate_maps", 0, "any");
	if (!ASSERT_EQ(err, -EPERM, "delegate_maps_eperm_reconfig")) {
		err = -EINVAL;
		goto cleanup;
	}
	err = set_delegate_mask(fs_fd, "delegate_progs", 0, "any");
	if (!ASSERT_EQ(err, -EPERM, "delegate_progs_eperm_reconfig")) {
		err = -EINVAL;
		goto cleanup;
	}
	err = set_delegate_mask(fs_fd, "delegate_attachs", 0, "any");
	if (!ASSERT_EQ(err, -EPERM, "delegate_attachs_eperm_reconfig")) {
		err = -EINVAL;
		goto cleanup;
	}
	zclose(fs_fd);

	bpffs_fd = openat(mnt_fd, ".", 0, O_RDWR);
	if (!ASSERT_GE(bpffs_fd, 0, "bpffs_open")) {
		err = -EINVAL;
		goto cleanup;
	}

	/* create BPF token FD and pass it to parent for some extra checks */
	token_fd = bpf_token_create(bpffs_fd, NULL);
	if (!ASSERT_GT(token_fd, 0, "child_token_create")) {
		err = -EINVAL;
		goto cleanup;
	}
	err = sendfd(sock_fd, token_fd);
	if (!ASSERT_OK(err, "send_token_fd"))
		goto cleanup;
	zclose(token_fd);

	/* do custom test logic with customly set up BPF FS instance */
	err = callback(bpffs_fd, lsm_skel);
	if (!ASSERT_OK(err, "test_callback"))
		goto cleanup;

	err = 0;
cleanup:
	zclose(sock_fd);
	zclose(mnt_fd);
	zclose(fs_fd);
	zclose(bpffs_fd);
	zclose(token_fd);

	lsm_skel->bss->my_pid = 0;
	token_lsm__destroy(lsm_skel);

	exit(-err);
}

static int wait_for_pid(pid_t pid)
{
	int status, ret;

again:
	ret = waitpid(pid, &status, 0);
	if (ret == -1) {
		if (errno == EINTR)
			goto again;

		return -1;
	}

	if (!WIFEXITED(status))
		return -1;

	return WEXITSTATUS(status);
}

static void parent(int child_pid, struct bpffs_opts *bpffs_opts, int sock_fd)
{
	int fs_fd = -1, mnt_fd = -1, token_fd = -1, err;

	err = recvfd(sock_fd, &fs_fd);
	if (!ASSERT_OK(err, "recv_bpffs_fd"))
		goto cleanup;

	mnt_fd = materialize_bpffs_fd(fs_fd, bpffs_opts);
	if (!ASSERT_GE(mnt_fd, 0, "materialize_bpffs_fd")) {
		err = -EINVAL;
		goto cleanup;
	}
	zclose(fs_fd);

	/* pass BPF FS context object to parent */
	err = sendfd(sock_fd, mnt_fd);
	if (!ASSERT_OK(err, "send_mnt_fd"))
		goto cleanup;
	zclose(mnt_fd);

	/* receive BPF token FD back from child for some extra tests */
	err = recvfd(sock_fd, &token_fd);
	if (!ASSERT_OK(err, "recv_token_fd"))
		goto cleanup;

	err = wait_for_pid(child_pid);
	ASSERT_OK(err, "waitpid_child");

cleanup:
	zclose(sock_fd);
	zclose(fs_fd);
	zclose(mnt_fd);
	zclose(token_fd);

	if (child_pid > 0)
		(void)kill(child_pid, SIGKILL);
}

static void subtest_userns(struct bpffs_opts *bpffs_opts,
			   child_callback_fn child_cb)
{
	int sock_fds[2] = { -1, -1 };
	int child_pid = 0, err;

	err = socketpair(AF_UNIX, SOCK_STREAM, 0, sock_fds);
	if (!ASSERT_OK(err, "socketpair"))
		goto cleanup;

	child_pid = fork();
	if (!ASSERT_GE(child_pid, 0, "fork"))
		goto cleanup;

	if (child_pid == 0) {
		zclose(sock_fds[0]);
		return child(sock_fds[1], bpffs_opts, child_cb);

	} else {
		zclose(sock_fds[1]);
		return parent(child_pid, bpffs_opts, sock_fds[0]);
	}

cleanup:
	zclose(sock_fds[0]);
	zclose(sock_fds[1]);
	if (child_pid > 0)
		(void)kill(child_pid, SIGKILL);
}

static int userns_map_create(int mnt_fd, struct token_lsm *lsm_skel)
{
	LIBBPF_OPTS(bpf_map_create_opts, map_opts);
	int err, token_fd = -1, map_fd = -1;
	__u64 old_caps = 0;

	/* create BPF token from BPF FS mount */
	token_fd = bpf_token_create(mnt_fd, NULL);
	if (!ASSERT_GT(token_fd, 0, "token_create")) {
		err = -EINVAL;
		goto cleanup;
	}

	/* while inside non-init userns, we need both a BPF token *and*
	 * CAP_BPF inside current userns to create privileged map; let's test
	 * that neither BPF token alone nor namespaced CAP_BPF is sufficient
	 */
	err = drop_priv_caps(&old_caps);
	if (!ASSERT_OK(err, "drop_caps"))
		goto cleanup;

	/* no token, no CAP_BPF -> fail */
	map_opts.map_flags = 0;
	map_opts.token_fd = 0;
	map_fd = bpf_map_create(BPF_MAP_TYPE_STACK, "wo_token_wo_bpf", 0, 8, 1, &map_opts);
	if (!ASSERT_LT(map_fd, 0, "stack_map_wo_token_wo_cap_bpf_should_fail")) {
		err = -EINVAL;
		goto cleanup;
	}

	/* token without CAP_BPF -> fail */
	map_opts.map_flags = BPF_F_TOKEN_FD;
	map_opts.token_fd = token_fd;
	map_fd = bpf_map_create(BPF_MAP_TYPE_STACK, "w_token_wo_bpf", 0, 8, 1, &map_opts);
	if (!ASSERT_LT(map_fd, 0, "stack_map_w_token_wo_cap_bpf_should_fail")) {
		err = -EINVAL;
		goto cleanup;
	}

	/* get back effective local CAP_BPF (and CAP_SYS_ADMIN) */
	err = restore_priv_caps(old_caps);
	if (!ASSERT_OK(err, "restore_caps"))
		goto cleanup;

	/* CAP_BPF without token -> fail */
	map_opts.map_flags = 0;
	map_opts.token_fd = 0;
	map_fd = bpf_map_create(BPF_MAP_TYPE_STACK, "wo_token_w_bpf", 0, 8, 1, &map_opts);
	if (!ASSERT_LT(map_fd, 0, "stack_map_wo_token_w_cap_bpf_should_fail")) {
		err = -EINVAL;
		goto cleanup;
	}

	/* finally, namespaced CAP_BPF + token -> success */
	map_opts.map_flags = BPF_F_TOKEN_FD;
	map_opts.token_fd = token_fd;
	map_fd = bpf_map_create(BPF_MAP_TYPE_STACK, "w_token_w_bpf", 0, 8, 1, &map_opts);
	if (!ASSERT_GT(map_fd, 0, "stack_map_w_token_w_cap_bpf")) {
		err = -EINVAL;
		goto cleanup;
	}

cleanup:
	zclose(token_fd);
	zclose(map_fd);
	return err;
}

static int userns_btf_load(int mnt_fd, struct token_lsm *lsm_skel)
{
	LIBBPF_OPTS(bpf_btf_load_opts, btf_opts);
	int err, token_fd = -1, btf_fd = -1;
	const void *raw_btf_data;
	struct btf *btf = NULL;
	__u32 raw_btf_size;
	__u64 old_caps = 0;

	/* create BPF token from BPF FS mount */
	token_fd = bpf_token_create(mnt_fd, NULL);
	if (!ASSERT_GT(token_fd, 0, "token_create")) {
		err = -EINVAL;
		goto cleanup;
	}

	/* while inside non-init userns, we need both a BPF token *and*
	 * CAP_BPF inside current userns to create privileged map; let's test
	 * that neither BPF token alone nor namespaced CAP_BPF is sufficient
	 */
	err = drop_priv_caps(&old_caps);
	if (!ASSERT_OK(err, "drop_caps"))
		goto cleanup;

	/* setup a trivial BTF data to load to the kernel */
	btf = btf__new_empty();
	if (!ASSERT_OK_PTR(btf, "empty_btf"))
		goto cleanup;

	ASSERT_GT(btf__add_int(btf, "int", 4, 0), 0, "int_type");

	raw_btf_data = btf__raw_data(btf, &raw_btf_size);
	if (!ASSERT_OK_PTR(raw_btf_data, "raw_btf_data"))
		goto cleanup;

	/* no token + no CAP_BPF -> failure */
	btf_opts.btf_flags = 0;
	btf_opts.token_fd = 0;
	btf_fd = bpf_btf_load(raw_btf_data, raw_btf_size, &btf_opts);
	if (!ASSERT_LT(btf_fd, 0, "no_token_no_cap_should_fail"))
		goto cleanup;

	/* token + no CAP_BPF -> failure */
	btf_opts.btf_flags = BPF_F_TOKEN_FD;
	btf_opts.token_fd = token_fd;
	btf_fd = bpf_btf_load(raw_btf_data, raw_btf_size, &btf_opts);
	if (!ASSERT_LT(btf_fd, 0, "token_no_cap_should_fail"))
		goto cleanup;

	/* get back effective local CAP_BPF (and CAP_SYS_ADMIN) */
	err = restore_priv_caps(old_caps);
	if (!ASSERT_OK(err, "restore_caps"))
		goto cleanup;

	/* token + CAP_BPF -> success */
	btf_opts.btf_flags = BPF_F_TOKEN_FD;
	btf_opts.token_fd = token_fd;
	btf_fd = bpf_btf_load(raw_btf_data, raw_btf_size, &btf_opts);
	if (!ASSERT_GT(btf_fd, 0, "token_and_cap_success"))
		goto cleanup;

	err = 0;
cleanup:
	btf__free(btf);
	zclose(btf_fd);
	zclose(token_fd);
	return err;
}

static int userns_prog_load(int mnt_fd, struct token_lsm *lsm_skel)
{
	LIBBPF_OPTS(bpf_prog_load_opts, prog_opts);
	int err, token_fd = -1, prog_fd = -1;
	struct bpf_insn insns[] = {
		/* bpf_jiffies64() requires CAP_BPF */
		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_jiffies64),
		/* bpf_get_current_task() requires CAP_PERFMON */
		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_current_task),
		/* r0 = 0; exit; */
		BPF_MOV64_IMM(BPF_REG_0, 0),
		BPF_EXIT_INSN(),
	};
	size_t insn_cnt = ARRAY_SIZE(insns);
	__u64 old_caps = 0;

	/* create BPF token from BPF FS mount */
	token_fd = bpf_token_create(mnt_fd, NULL);
	if (!ASSERT_GT(token_fd, 0, "token_create")) {
		err = -EINVAL;
		goto cleanup;
	}

	/* validate we can successfully load BPF program with token; this
	 * being XDP program (CAP_NET_ADMIN) using bpf_jiffies64() (CAP_BPF)
	 * and bpf_get_current_task() (CAP_PERFMON) helpers validates we have
	 * BPF token wired properly in a bunch of places in the kernel
	 */
	prog_opts.prog_flags = BPF_F_TOKEN_FD;
	prog_opts.token_fd = token_fd;
	prog_opts.expected_attach_type = BPF_XDP;
	prog_fd = bpf_prog_load(BPF_PROG_TYPE_XDP, "token_prog", "GPL",
				insns, insn_cnt, &prog_opts);
	if (!ASSERT_GT(prog_fd, 0, "prog_fd")) {
		err = -EPERM;
		goto cleanup;
	}

	/* no token + caps -> failure */
	prog_opts.prog_flags = 0;
	prog_opts.token_fd = 0;
	prog_fd = bpf_prog_load(BPF_PROG_TYPE_XDP, "token_prog", "GPL",
				insns, insn_cnt, &prog_opts);
	if (!ASSERT_EQ(prog_fd, -EPERM, "prog_fd_eperm")) {
		err = -EPERM;
		goto cleanup;
	}

	err = drop_priv_caps(&old_caps);
	if (!ASSERT_OK(err, "drop_caps"))
		goto cleanup;

	/* no caps + token -> failure */
	prog_opts.prog_flags = BPF_F_TOKEN_FD;
	prog_opts.token_fd = token_fd;
	prog_fd = bpf_prog_load(BPF_PROG_TYPE_XDP, "token_prog", "GPL",
				insns, insn_cnt, &prog_opts);
	if (!ASSERT_EQ(prog_fd, -EPERM, "prog_fd_eperm")) {
		err = -EPERM;
		goto cleanup;
	}

	/* no caps + no token -> definitely a failure */
	prog_opts.prog_flags = 0;
	prog_opts.token_fd = 0;
	prog_fd = bpf_prog_load(BPF_PROG_TYPE_XDP, "token_prog", "GPL",
				insns, insn_cnt, &prog_opts);
	if (!ASSERT_EQ(prog_fd, -EPERM, "prog_fd_eperm")) {
		err = -EPERM;
		goto cleanup;
	}

	err = 0;
cleanup:
	zclose(prog_fd);
	zclose(token_fd);
	return err;
}

static int userns_obj_priv_map(int mnt_fd, struct token_lsm *lsm_skel)
{
	LIBBPF_OPTS(bpf_object_open_opts, opts);
	char buf[256];
	struct priv_map *skel;
	int err;

	skel = priv_map__open_and_load();
	if (!ASSERT_ERR_PTR(skel, "obj_tokenless_load")) {
		priv_map__destroy(skel);
		return -EINVAL;
	}

	/* use bpf_token_path to provide BPF FS path */
	snprintf(buf, sizeof(buf), "/proc/self/fd/%d", mnt_fd);
	opts.bpf_token_path = buf;
	skel = priv_map__open_opts(&opts);
	if (!ASSERT_OK_PTR(skel, "obj_token_path_open"))
		return -EINVAL;

	err = priv_map__load(skel);
	priv_map__destroy(skel);
	if (!ASSERT_OK(err, "obj_token_path_load"))
		return -EINVAL;

	return 0;
}

static int userns_obj_priv_prog(int mnt_fd, struct token_lsm *lsm_skel)
{
	LIBBPF_OPTS(bpf_object_open_opts, opts);
	char buf[256];
	struct priv_prog *skel;
	int err;

	skel = priv_prog__open_and_load();
	if (!ASSERT_ERR_PTR(skel, "obj_tokenless_load")) {
		priv_prog__destroy(skel);
		return -EINVAL;
	}

	/* use bpf_token_path to provide BPF FS path */
	snprintf(buf, sizeof(buf), "/proc/self/fd/%d", mnt_fd);
	opts.bpf_token_path = buf;
	skel = priv_prog__open_opts(&opts);
	if (!ASSERT_OK_PTR(skel, "obj_token_path_open"))
		return -EINVAL;
	err = priv_prog__load(skel);
	priv_prog__destroy(skel);
	if (!ASSERT_OK(err, "obj_token_path_load"))
		return -EINVAL;

	/* provide BPF token, but reject bpf_token_capable() with LSM */
	lsm_skel->bss->reject_capable = true;
	lsm_skel->bss->reject_cmd = false;
	skel = priv_prog__open_opts(&opts);
	if (!ASSERT_OK_PTR(skel, "obj_token_lsm_reject_cap_open"))
		return -EINVAL;
	err = priv_prog__load(skel);
	priv_prog__destroy(skel);
	if (!ASSERT_ERR(err, "obj_token_lsm_reject_cap_load"))
		return -EINVAL;

	/* provide BPF token, but reject bpf_token_cmd() with LSM */
	lsm_skel->bss->reject_capable = false;
	lsm_skel->bss->reject_cmd = true;
	skel = priv_prog__open_opts(&opts);
	if (!ASSERT_OK_PTR(skel, "obj_token_lsm_reject_cmd_open"))
		return -EINVAL;
	err = priv_prog__load(skel);
	priv_prog__destroy(skel);
	if (!ASSERT_ERR(err, "obj_token_lsm_reject_cmd_load"))
		return -EINVAL;

	return 0;
}

/* this test is called with BPF FS that doesn't delegate BPF_BTF_LOAD command,
 * which should cause struct_ops application to fail, as BTF won't be uploaded
 * into the kernel, even if STRUCT_OPS programs themselves are allowed
 */
static int validate_struct_ops_load(int mnt_fd, bool expect_success)
{
	LIBBPF_OPTS(bpf_object_open_opts, opts);
	char buf[256];
	struct dummy_st_ops_success *skel;
	int err;

	snprintf(buf, sizeof(buf), "/proc/self/fd/%d", mnt_fd);
	opts.bpf_token_path = buf;
	skel = dummy_st_ops_success__open_opts(&opts);
	if (!ASSERT_OK_PTR(skel, "obj_token_path_open"))
		return -EINVAL;

	err = dummy_st_ops_success__load(skel);
	dummy_st_ops_success__destroy(skel);
	if (expect_success) {
		if (!ASSERT_OK(err, "obj_token_path_load"))
			return -EINVAL;
	} else /* expect failure */ {
		if (!ASSERT_ERR(err, "obj_token_path_load"))
			return -EINVAL;
	}

	return 0;
}

static int userns_obj_priv_btf_fail(int mnt_fd, struct token_lsm *lsm_skel)
{
	return validate_struct_ops_load(mnt_fd, false /* should fail */);
}

static int userns_obj_priv_btf_success(int mnt_fd, struct token_lsm *lsm_skel)
{
	return validate_struct_ops_load(mnt_fd, true /* should succeed */);
}

#define TOKEN_ENVVAR "LIBBPF_BPF_TOKEN_PATH"
#define TOKEN_BPFFS_CUSTOM "/bpf-token-fs"

static int userns_obj_priv_implicit_token(int mnt_fd, struct token_lsm *lsm_skel)
{
	LIBBPF_OPTS(bpf_object_open_opts, opts);
	struct dummy_st_ops_success *skel;
	int err;

	/* before we mount BPF FS with token delegation, struct_ops skeleton
	 * should fail to load
	 */
	skel = dummy_st_ops_success__open_and_load();
	if (!ASSERT_ERR_PTR(skel, "obj_tokenless_load")) {
		dummy_st_ops_success__destroy(skel);
		return -EINVAL;
	}

	/* mount custom BPF FS over /sys/fs/bpf so that libbpf can create BPF
	 * token automatically and implicitly
	 */
	err = sys_move_mount(mnt_fd, "", AT_FDCWD, "/sys/fs/bpf", MOVE_MOUNT_F_EMPTY_PATH);
	if (!ASSERT_OK(err, "move_mount_bpffs"))
		return -EINVAL;

	/* disable implicit BPF token creation by setting
	 * LIBBPF_BPF_TOKEN_PATH envvar to empty value, load should fail
	 */
	err = setenv(TOKEN_ENVVAR, "", 1 /*overwrite*/);
	if (!ASSERT_OK(err, "setenv_token_path"))
		return -EINVAL;
	skel = dummy_st_ops_success__open_and_load();
	if (!ASSERT_ERR_PTR(skel, "obj_token_envvar_disabled_load")) {
		unsetenv(TOKEN_ENVVAR);
		dummy_st_ops_success__destroy(skel);
		return -EINVAL;
	}
	unsetenv(TOKEN_ENVVAR);

	/* now the same struct_ops skeleton should succeed thanks to libppf
	 * creating BPF token from /sys/fs/bpf mount point
	 */
	skel = dummy_st_ops_success__open_and_load();
	if (!ASSERT_OK_PTR(skel, "obj_implicit_token_load"))
		return -EINVAL;

	dummy_st_ops_success__destroy(skel);

	/* now disable implicit token through empty bpf_token_path, should fail */
	opts.bpf_token_path = "";
	skel = dummy_st_ops_success__open_opts(&opts);
	if (!ASSERT_OK_PTR(skel, "obj_empty_token_path_open"))
		return -EINVAL;

	err = dummy_st_ops_success__load(skel);
	dummy_st_ops_success__destroy(skel);
	if (!ASSERT_ERR(err, "obj_empty_token_path_load"))
		return -EINVAL;

	return 0;
}

static int userns_obj_priv_implicit_token_envvar(int mnt_fd, struct token_lsm *lsm_skel)
{
	LIBBPF_OPTS(bpf_object_open_opts, opts);
	struct dummy_st_ops_success *skel;
	int err;

	/* before we mount BPF FS with token delegation, struct_ops skeleton
	 * should fail to load
	 */
	skel = dummy_st_ops_success__open_and_load();
	if (!ASSERT_ERR_PTR(skel, "obj_tokenless_load")) {
		dummy_st_ops_success__destroy(skel);
		return -EINVAL;
	}

	/* mount custom BPF FS over custom location, so libbpf can't create
	 * BPF token implicitly, unless pointed to it through
	 * LIBBPF_BPF_TOKEN_PATH envvar
	 */
	rmdir(TOKEN_BPFFS_CUSTOM);
	if (!ASSERT_OK(mkdir(TOKEN_BPFFS_CUSTOM, 0777), "mkdir_bpffs_custom"))
		goto err_out;
	err = sys_move_mount(mnt_fd, "", AT_FDCWD, TOKEN_BPFFS_CUSTOM, MOVE_MOUNT_F_EMPTY_PATH);
	if (!ASSERT_OK(err, "move_mount_bpffs"))
		goto err_out;

	/* even though we have BPF FS with delegation, it's not at default
	 * /sys/fs/bpf location, so we still fail to load until envvar is set up
	 */
	skel = dummy_st_ops_success__open_and_load();
	if (!ASSERT_ERR_PTR(skel, "obj_tokenless_load2")) {
		dummy_st_ops_success__destroy(skel);
		goto err_out;
	}

	err = setenv(TOKEN_ENVVAR, TOKEN_BPFFS_CUSTOM, 1 /*overwrite*/);
	if (!ASSERT_OK(err, "setenv_token_path"))
		goto err_out;

	/* now the same struct_ops skeleton should succeed thanks to libppf
	 * creating BPF token from custom mount point
	 */
	skel = dummy_st_ops_success__open_and_load();
	if (!ASSERT_OK_PTR(skel, "obj_implicit_token_load"))
		goto err_out;

	dummy_st_ops_success__destroy(skel);

	/* now disable implicit token through empty bpf_token_path, envvar
	 * will be ignored, should fail
	 */
	opts.bpf_token_path = "";
	skel = dummy_st_ops_success__open_opts(&opts);
	if (!ASSERT_OK_PTR(skel, "obj_empty_token_path_open"))
		goto err_out;

	err = dummy_st_ops_success__load(skel);
	dummy_st_ops_success__destroy(skel);
	if (!ASSERT_ERR(err, "obj_empty_token_path_load"))
		goto err_out;

	rmdir(TOKEN_BPFFS_CUSTOM);
	unsetenv(TOKEN_ENVVAR);
	return 0;
err_out:
	rmdir(TOKEN_BPFFS_CUSTOM);
	unsetenv(TOKEN_ENVVAR);
	return -EINVAL;
}

#define bit(n) (1ULL << (n))

void test_token(void)
{
	if (test__start_subtest("map_token")) {
		struct bpffs_opts opts = {
			.cmds_str = "map_create",
			.maps_str = "stack",
		};

		subtest_userns(&opts, userns_map_create);
	}
	if (test__start_subtest("btf_token")) {
		struct bpffs_opts opts = {
			.cmds = 1ULL << BPF_BTF_LOAD,
		};

		subtest_userns(&opts, userns_btf_load);
	}
	if (test__start_subtest("prog_token")) {
		struct bpffs_opts opts = {
			.cmds_str = "PROG_LOAD",
			.progs_str = "XDP",
			.attachs_str = "xdp",
		};

		subtest_userns(&opts, userns_prog_load);
	}
	if (test__start_subtest("obj_priv_map")) {
		struct bpffs_opts opts = {
			.cmds = bit(BPF_MAP_CREATE),
			.maps = bit(BPF_MAP_TYPE_QUEUE),
		};

		subtest_userns(&opts, userns_obj_priv_map);
	}
	if (test__start_subtest("obj_priv_prog")) {
		struct bpffs_opts opts = {
			.cmds = bit(BPF_PROG_LOAD),
			.progs = bit(BPF_PROG_TYPE_KPROBE),
			.attachs = ~0ULL,
		};

		subtest_userns(&opts, userns_obj_priv_prog);
	}
	if (test__start_subtest("obj_priv_btf_fail")) {
		struct bpffs_opts opts = {
			/* disallow BTF loading */
			.cmds = bit(BPF_MAP_CREATE) | bit(BPF_PROG_LOAD),
			.maps = bit(BPF_MAP_TYPE_STRUCT_OPS),
			.progs = bit(BPF_PROG_TYPE_STRUCT_OPS),
			.attachs = ~0ULL,
		};

		subtest_userns(&opts, userns_obj_priv_btf_fail);
	}
	if (test__start_subtest("obj_priv_btf_success")) {
		struct bpffs_opts opts = {
			/* allow BTF loading */
			.cmds = bit(BPF_BTF_LOAD) | bit(BPF_MAP_CREATE) | bit(BPF_PROG_LOAD),
			.maps = bit(BPF_MAP_TYPE_STRUCT_OPS),
			.progs = bit(BPF_PROG_TYPE_STRUCT_OPS),
			.attachs = ~0ULL,
		};

		subtest_userns(&opts, userns_obj_priv_btf_success);
	}
	if (test__start_subtest("obj_priv_implicit_token")) {
		struct bpffs_opts opts = {
			/* allow BTF loading */
			.cmds = bit(BPF_BTF_LOAD) | bit(BPF_MAP_CREATE) | bit(BPF_PROG_LOAD),
			.maps = bit(BPF_MAP_TYPE_STRUCT_OPS),
			.progs = bit(BPF_PROG_TYPE_STRUCT_OPS),
			.attachs = ~0ULL,
		};

		subtest_userns(&opts, userns_obj_priv_implicit_token);
	}
	if (test__start_subtest("obj_priv_implicit_token_envvar")) {
		struct bpffs_opts opts = {
			/* allow BTF loading */
			.cmds = bit(BPF_BTF_LOAD) | bit(BPF_MAP_CREATE) | bit(BPF_PROG_LOAD),
			.maps = bit(BPF_MAP_TYPE_STRUCT_OPS),
			.progs = bit(BPF_PROG_TYPE_STRUCT_OPS),
			.attachs = ~0ULL,
		};

		subtest_userns(&opts, userns_obj_priv_implicit_token_envvar);
	}
}