1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2019 Richard Palethorpe <rpalethorpe@suse.com>
4 */
5
6 #include <string.h>
7
8 #define TST_NO_DEFAULT_MAIN
9 #include "tst_test.h"
10 #include "tst_capability.h"
11
12 #include "lapi/syscalls.h"
13
tst_capget(struct tst_cap_user_header * hdr,struct tst_cap_user_data * data)14 int tst_capget(struct tst_cap_user_header *hdr,
15 struct tst_cap_user_data *data)
16 {
17 return tst_syscall(__NR_capget, hdr, data);
18 }
19
tst_capset(struct tst_cap_user_header * hdr,const struct tst_cap_user_data * data)20 int tst_capset(struct tst_cap_user_header *hdr,
21 const struct tst_cap_user_data *data)
22 {
23 return tst_syscall(__NR_capset, hdr, data);
24 }
25
do_cap_drop(uint32_t * set,uint32_t mask,const struct tst_cap * cap)26 static void do_cap_drop(uint32_t *set, uint32_t mask, const struct tst_cap *cap)
27 {
28 if (*set & mask) {
29 tst_res(TINFO, "Dropping %s(%d)", cap->name, cap->id);
30 *set &= ~mask;
31 }
32 }
33
do_cap_req(uint32_t * permitted,uint32_t * effective,uint32_t mask,const struct tst_cap * cap)34 static void do_cap_req(uint32_t *permitted, uint32_t *effective, uint32_t mask,
35 const struct tst_cap *cap)
36 {
37 if (!(*permitted & mask))
38 tst_brk(TCONF, "Need %s(%d)", cap->name, cap->id);
39
40 if (!(*effective & mask)) {
41 tst_res(TINFO, "Permitting %s(%d)", cap->name, cap->id);
42 *effective |= mask;
43 }
44 }
45
tst_cap_action(struct tst_cap * cap)46 void tst_cap_action(struct tst_cap *cap)
47 {
48 struct tst_cap_user_header hdr = {
49 .version = 0x20080522,
50 .pid = tst_syscall(__NR_gettid),
51 };
52 struct tst_cap_user_data cur[2] = { {0} };
53 struct tst_cap_user_data new[2] = { {0} };
54 uint32_t act = cap->action;
55 uint32_t *pE = &new[CAP_TO_INDEX(cap->id)].effective;
56 uint32_t *pP = &new[CAP_TO_INDEX(cap->id)].permitted;
57 uint32_t mask = CAP_TO_MASK(cap->id);
58
59 if (tst_capget(&hdr, cur))
60 tst_brk(TBROK | TERRNO, "tst_capget()");
61
62 memcpy(new, cur, sizeof(new));
63
64 switch (act) {
65 case TST_CAP_DROP:
66 do_cap_drop(pE, mask, cap);
67 break;
68 case TST_CAP_REQ:
69 do_cap_req(pP, pE, mask, cap);
70 break;
71 default:
72 tst_brk(TBROK, "Unrecognised action %d", cap->action);
73 }
74
75 if (!memcmp(cur, new, sizeof(new)))
76 return;
77
78 if (tst_capset(&hdr, new))
79 tst_brk(TBROK | TERRNO, "tst_capset(%s)", cap->name);
80 }
81
tst_cap_setup(struct tst_cap * caps,unsigned int action_mask)82 void tst_cap_setup(struct tst_cap *caps, unsigned int action_mask)
83 {
84 struct tst_cap *cap;
85
86 for (cap = caps; cap->action; cap++) {
87 if (cap->action & action_mask)
88 tst_cap_action(cap);
89 }
90 }
91