Debian Codegraph @

src/basic/capability-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stdatomic.h>
4 #include <stdio.h>
5 #include <sys/prctl.h>
6 #include <sys/syscall.h>
7 #include <unistd.h>
8
9 #include "alloc-util.h"
10 #include "bitfield.h"
11 #include "capability-list.h"
12 #include "capability-util.h"
13 #include "errno-util.h"
14 #include "fd-util.h"
15 #include "fileio.h"
16 #include "log.h"
17 #include "parse-util.h"
18 #include "pidref.h"
19 #include "process-util.h"
20 #include "stat-util.h"
21 #include "user-util.h"
22
23 int capability_get(CapabilityQuintet *ret) {
24 assert(ret);
25
26 struct __user_cap_header_struct hdr = {
27 .version = _LINUX_CAPABILITY_VERSION_3,
28 .pid = getpid_cached(),
29 };
30
31 assert_cc(_LINUX_CAPABILITY_U32S_3 == 2);
32 struct __user_cap_data_struct data[_LINUX_CAPABILITY_U32S_3];
33 if (syscall(SYS_capget, &hdr, data) < 0)
34 return -errno;
35
36 *ret = (CapabilityQuintet) {
37 .effective = (uint64_t) data[0].effective | ((uint64_t) data[1].effective << 32),
38 .bounding = UINT64_MAX,
39 .inheritable = (uint64_t) data[0].inheritable | ((uint64_t) data[1].inheritable << 32),
40 .permitted = (uint64_t) data[0].permitted | ((uint64_t) data[1].permitted << 32),
41 .ambient = UINT64_MAX,
42 };
43 return 0;
44 }
45
46 static int capability_apply(const CapabilityQuintet *q) {
47 assert(q);
48
49 struct __user_cap_header_struct hdr = {
50 .version = _LINUX_CAPABILITY_VERSION_3,
51 .pid = getpid_cached(),
52 };
53
54 struct __user_cap_data_struct data[_LINUX_CAPABILITY_U32S_3] = {
55 {
56 .effective = (uint32_t) (q->effective & UINT32_MAX),
57 .inheritable = (uint32_t) (q->inheritable & UINT32_MAX),
58 .permitted = (uint32_t) (q->permitted & UINT32_MAX),
59 },
60 {
61 .effective = (uint32_t) (q->effective >> 32),
62 .inheritable = (uint32_t) (q->inheritable >> 32),
63 .permitted = (uint32_t) (q->permitted >> 32),
64 },
65 };
66 return RET_NERRNO(syscall(SYS_capset, &hdr, data));
67 }
68
69 unsigned cap_last_cap(void) {
70 static atomic_int saved = INT_MAX;
71 int r, c;
72
73 c = saved;
74 if (c != INT_MAX)
75 return c;
76
77 /* Available since linux-3.2 */
78 _cleanup_free_ char *content = NULL;
79 r = read_one_line_file("/proc/sys/kernel/cap_last_cap", &content);
80 if (r < 0)
81 log_debug_errno(r, "Failed to read /proc/sys/kernel/cap_last_cap, ignoring: %m");
82 else {
83 r = safe_atoi(content, &c);
84 if (r < 0)
85 log_debug_errno(r, "Failed to parse /proc/sys/kernel/cap_last_cap, ignoring: %m");
86 else {
87 if (c > CAP_LIMIT) /* Safety for the future: if one day the kernel learns more than
88 * 64 caps, then we are in trouble (since we, as much userspace
89 * and kernel space store capability masks in uint64_t types). We
90 * also want to use UINT64_MAX as marker for "unset". Hence let's
91 * hence protect ourselves against that and always cap at 62 for
92 * now. */
93 c = CAP_LIMIT;
94
95 saved = c;
96 return c;
97 }
98 }
99
100 /* Fall back to syscall-probing for pre linux-3.2, or where /proc/ is not mounted */
101 unsigned long p = (unsigned long) MIN(CAP_LAST_CAP, CAP_LIMIT);
102
103 if (prctl(PR_CAPBSET_READ, p) < 0) {
104
105 /* Hmm, look downwards, until we find one that works */
106 for (p--; p > 0; p--)
107 if (prctl(PR_CAPBSET_READ, p) >= 0)
108 break;
109
110 } else {
111
112 /* Hmm, look upwards, until we find one that doesn't work */
113 for (; p < CAP_LIMIT; p++)
114 if (prctl(PR_CAPBSET_READ, p+1) < 0)
115 break;
116 }
117
118 c = (int) p;
119 saved = c;
120 return c;
121 }
122
123 int have_effective_cap(unsigned cap) {
124 CapabilityQuintet q;
125 int r;
126
127 assert(cap <= CAP_LIMIT);
128
129 r = capability_get(&q);
130 if (r < 0)
131 return r;
132
133 return BIT_SET(q.effective, cap);
134 }
135
136 int have_inheritable_cap(unsigned cap) {
137 CapabilityQuintet q;
138 int r;
139
140 assert(cap <= CAP_LIMIT);
141
142 r = capability_get(&q);
143 if (r < 0)
144 return r;
145
146 return BIT_SET(q.inheritable, cap);
147 }
148
149 int capability_ambient_set_apply(uint64_t set, bool also_inherit) {
150 int r;
151
152 /* Remove capabilities requested in ambient set, but not in the bounding set */
153 for (unsigned i = 0; i <= cap_last_cap(); i++) {
154 if (!BIT_SET(set, i))
155 continue;
156
157 if (prctl(PR_CAPBSET_READ, (unsigned long) i) != 1) {
158 log_debug("Ambient capability %s requested but missing from bounding set, suppressing automatically.",
159 capability_to_name(i));
160 CLEAR_BIT(set, i);
161 }
162 }
163
164 /* Add the capabilities to the ambient set (an possibly also the inheritable set) */
165
166 if (also_inherit) {
167 CapabilityQuintet q;
168
169 r = capability_get(&q);
170 if (r < 0)
171 return r;
172
173 q.inheritable = set;
174
175 r = capability_apply(&q);
176 if (r < 0)
177 return r;
178 }
179
180 for (unsigned i = 0; i <= cap_last_cap(); i++)
181 if (BIT_SET(set, i)) {
182 /* Add the capability to the ambient set. */
183 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, i, 0, 0) < 0)
184 return -errno;
185 } else {
186 /* Drop the capability so we don't inherit capabilities we didn't ask for. */
187 r = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, i, 0, 0);
188 if (r < 0)
189 return -errno;
190 if (r > 0)
191 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_LOWER, i, 0, 0) < 0)
192 return -errno;
193 }
194
195 return 0;
196 }
197
198 int capability_gain_cap_setpcap(void) {
199 CapabilityQuintet q;
200 int r;
201
202 r = capability_get(&q);
203 if (r < 0)
204 return r;
205
206 if (BIT_SET(q.effective, CAP_SETPCAP))
207 return 1; /* We already have capability. */
208
209 SET_BIT(q.effective, CAP_SETPCAP);
210
211 r = capability_apply(&q);
212 if (r < 0) {
213 /* If we didn't manage to acquire the CAP_SETPCAP bit, we continue anyway, after all this
214 * just means we'll fail later, when we actually intend to drop some capabilities or try to
215 * set securebits. */
216 log_debug_errno(r, "Can't acquire effective CAP_SETPCAP bit, ignoring: %m");
217 return 0;
218 }
219
220 return 1; /* acquired */
221 }
222
223 int capability_bounding_set_drop(uint64_t keep, bool right_now) {
224 int k, r;
225
226 /* If we are run as PID 1 we will lack CAP_SETPCAP by default in the effective set (yes, the kernel
227 * drops that when executing init!), so get it back temporarily so that we can call PR_CAPBSET_DROP. */
228
229 CapabilityQuintet q;
230 r = capability_get(&q);
231 if (r < 0)
232 return r;
233 CapabilityQuintet saved = q;
234
235 r = capability_gain_cap_setpcap();
236 if (r < 0)
237 return r;
238
239 for (unsigned i = 0; i <= cap_last_cap(); i++) {
240 if (BIT_SET(keep, i))
241 continue;
242
243 /* Drop it from the bounding set */
244 if (prctl(PR_CAPBSET_DROP, i) < 0) {
245 r = -errno;
246
247 /* If dropping the capability failed, let's see if we didn't have it in the first
248 * place. If so, continue anyway, as dropping a capability we didn't have in the
249 * first place doesn't really matter anyway. */
250 if (prctl(PR_CAPBSET_READ, i) != 0)
251 goto finish;
252 }
253
254 /* Also drop it from the inheritable set, so that anything we exec() loses the capability for
255 * good. */
256 CLEAR_BIT(q.inheritable, i);
257
258 /* If we shall apply this right now drop it also from our own capability sets. */
259 if (right_now) {
260 CLEAR_BIT(q.effective, i);
261 CLEAR_BIT(q.permitted, i);
262 }
263 }
264
265 r = 0;
266
267 finish:
268 k = capability_apply(&q);
269 if (k < 0)
270 /* If there are no actual changes anyway then let's ignore this error. */
271 if (!capability_quintet_equal(&q, &saved))
272 return k;
273
274 return r;
275 }
276
277 static int drop_from_file(const char *fn, uint64_t keep) {
278 _cleanup_free_ char *p = NULL;
279 uint64_t current, after;
280 uint32_t hi, lo;
281 int r, k;
282
283 r = read_one_line_file(fn, &p);
284 if (r < 0)
285 return r;
286
287 k = sscanf(p, "%" PRIu32 " %" PRIu32, &lo, &hi);
288 if (k != 2)
289 return -EIO;
290
291 current = (uint64_t) lo | ((uint64_t) hi << 32);
292 after = current & keep;
293
294 if (current == after)
295 return 0;
296
297 lo = after & UINT32_MAX;
298 hi = (after >> 32) & UINT32_MAX;
299
300 return write_string_filef(fn, 0, "%" PRIu32 " %" PRIu32, lo, hi);
301 }
302
303 int capability_bounding_set_drop_usermode(uint64_t keep) {
304 int r;
305
306 r = drop_from_file("/proc/sys/kernel/usermodehelper/inheritable", keep);
307 if (r < 0)
308 return r;
309
310 r = drop_from_file("/proc/sys/kernel/usermodehelper/bset", keep);
311 if (r < 0)
312 return r;
313
314 return r;
315 }
316
317 int drop_privileges(uid_t uid, gid_t gid, uint64_t keep_capabilities) {
318 int r;
319
320 /* Unfortunately we cannot leave privilege dropping to PID 1 here, since we want to run as user but
321 * want to keep some capabilities. Since file capabilities have been introduced this cannot be done
322 * across exec() anymore, unless our binary has the capability configured in the file system, which
323 * we want to avoid. */
324
325 if (setresgid(gid, gid, gid) < 0)
326 return log_error_errno(errno, "Failed to change group ID: %m");
327
328 r = maybe_setgroups(/* size= */ 0, /* list= */ NULL);
329 if (r < 0)
330 return log_error_errno(r, "Failed to drop auxiliary groups list: %m");
331
332 /* Ensure we keep the permitted caps across the setresuid(). Note that we do this even if we actually
333 * don't want to keep any capabilities, since we want to be able to drop them from the bounding set
334 * too, and we can only do that if we have capabilities. */
335 if (prctl(PR_SET_KEEPCAPS, 1) < 0)
336 return log_error_errno(errno, "Failed to enable keep capabilities flag: %m");
337
338 if (setresuid(uid, uid, uid) < 0)
339 return log_error_errno(errno, "Failed to change user ID: %m");
340
341 if (prctl(PR_SET_KEEPCAPS, 0) < 0)
342 return log_error_errno(errno, "Failed to disable keep capabilities flag: %m");
343
344 /* Drop all caps from the bounding set (as well as the inheritable/permitted/effective sets), except
345 * the ones we want to keep */
346 r = capability_bounding_set_drop(keep_capabilities, /* right_now= */ true);
347 if (r < 0)
348 return log_error_errno(r, "Failed to drop capabilities: %m");
349
350 /* Now upgrade the permitted caps we still kept to effective caps */
351 if (keep_capabilities != 0) {
352 CapabilityQuintet q = {
353 .effective = keep_capabilities,
354 .permitted = keep_capabilities,
355 };
356
357 r = capability_apply(&q);
358 if (r < 0)
359 return log_error_errno(r, "Failed to increase capabilities: %m");
360 }
361
362 return 0;
363 }
364
365 static int change_capability(unsigned cap, bool b) {
366 CapabilityQuintet q;
367 int r;
368
369 assert(cap <= CAP_LIMIT);
370
371 r = capability_get(&q);
372 if (r < 0)
373 return r;
374
375 if (b) {
376 SET_BIT(q.effective, cap);
377 SET_BIT(q.permitted, cap);
378 SET_BIT(q.inheritable, cap);
379 } else {
380 CLEAR_BIT(q.effective, cap);
381 CLEAR_BIT(q.permitted, cap);
382 CLEAR_BIT(q.inheritable, cap);
383 }
384
385 return capability_apply(&q);
386 }
387
388 int drop_capability(unsigned cap) {
389 return change_capability(cap, false);
390 }
391
392 int keep_capability(unsigned cap) {
393 return change_capability(cap, true);
394 }
395
396 bool capability_quintet_mangle(CapabilityQuintet *q) {
397 uint64_t combined, drop = 0;
398
399 assert(q);
400
401 combined = q->effective | q->bounding | q->inheritable | q->permitted | q->ambient;
402
403 for (unsigned i = 0; i <= cap_last_cap(); i++) {
404 if (!BIT_SET(combined, i))
405 continue;
406
407 if (prctl(PR_CAPBSET_READ, (unsigned long) i) > 0)
408 continue;
409
410 SET_BIT(drop, i);
411
412 log_debug("Dropping capability not in the current bounding set: %s", capability_to_name(i));
413 }
414
415 q->effective &= ~drop;
416 q->bounding &= ~drop;
417 q->inheritable &= ~drop;
418 q->permitted &= ~drop;
419 q->ambient &= ~drop;
420
421 return drop != 0; /* Let the caller know we changed something */
422 }
423
424 int capability_quintet_enforce(const CapabilityQuintet *q) {
425 CapabilityQuintet c;
426 bool modified = false;
427 int r;
428
429 if (q->ambient != CAP_MASK_UNSET ||
430 q->inheritable != CAP_MASK_UNSET ||
431 q->permitted != CAP_MASK_UNSET ||
432 q->effective != CAP_MASK_UNSET) {
433 r = capability_get(&c);
434 if (r < 0)
435 return r;
436 }
437
438 if (q->ambient != CAP_MASK_UNSET) {
439 /* In order to raise the ambient caps set we first need to raise the matching
440 * inheritable + permitted cap */
441 if (!FLAGS_SET(c.permitted, q->ambient) ||
442 !FLAGS_SET(c.inheritable, q->ambient)) {
443
444 c.permitted |= q->ambient;
445 c.inheritable |= q->ambient;
446
447 r = capability_apply(&c);
448 if (r < 0)
449 return r;
450 }
451
452 r = capability_ambient_set_apply(q->ambient, /* also_inherit= */ false);
453 if (r < 0)
454 return r;
455 }
456
457 if (q->inheritable != CAP_MASK_UNSET || q->permitted != CAP_MASK_UNSET || q->effective != CAP_MASK_UNSET) {
458 if (!FLAGS_SET(c.effective, q->effective) ||
459 !FLAGS_SET(c.permitted, q->permitted) ||
460 !FLAGS_SET(c.inheritable, q->inheritable)) {
461
462 c.effective |= q->effective;
463 c.permitted |= q->permitted;
464 c.inheritable |= q->inheritable;
465
466 /* Now, let's enforce the caps for the first time. Note that this is where we acquire
467 * caps in any of the sets we currently don't have. We have to do this before
468 * dropping the bounding caps below, since at that point we can never acquire new
469 * caps in inherited/permitted/effective anymore, but only lose them.
470 *
471 * In order to change the bounding caps, we need to keep CAP_SETPCAP for a bit
472 * longer. Let's add it to our list hence for now. */
473 if (q->bounding != CAP_MASK_UNSET &&
474 (!BIT_SET(c.effective, CAP_SETPCAP) || !BIT_SET(c.permitted, CAP_SETPCAP))) {
475 CapabilityQuintet tmp = c;
476
477 SET_BIT(c.effective, CAP_SETPCAP);
478 SET_BIT(c.permitted, CAP_SETPCAP);
479
480 modified = true;
481
482 r = capability_apply(&tmp);
483 } else
484 r = capability_apply(&c);
485 if (r < 0)
486 return r;
487 }
488 }
489
490 if (q->bounding != CAP_MASK_UNSET) {
491 r = capability_bounding_set_drop(q->bounding, /* right_now= */ false);
492 if (r < 0)
493 return r;
494 }
495
496 /* If needed, let's now set the caps again, this time in the final version, which differs from what
497 * we have already set only in the CAP_SETPCAP bit, which we needed for dropping the bounding
498 * bits. This call only undoes bits and doesn't acquire any which means the bounding caps don't
499 * matter. */
500 if (modified) {
501 r = capability_apply(&c);
502 if (r < 0)
503 return r;
504 }
505
506 return 0;
507 }
508
509 int capability_get_ambient(uint64_t *ret) {
510 uint64_t a = 0;
511 int r;
512
513 assert(ret);
514
515 for (unsigned i = 0; i <= cap_last_cap(); i++) {
516 r = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, i, 0, 0);
517 if (r < 0)
518 return -errno;
519 if (r > 0)
520 SET_BIT(a, i);
521 }
522
523 *ret = a;
524 return 1;
525 }
526
527 int pidref_get_capability(const PidRef *pidref, CapabilityQuintet *ret) {
528 int r;
529
530 if (!pidref_is_set(pidref))
531 return -ESRCH;
532 if (pidref_is_remote(pidref))
533 return -EREMOTE;
534
535 const char *path = procfs_file_alloca(pidref->pid, "status");
536 _cleanup_fclose_ FILE *f = fopen(path, "re");
537 if (!f) {
538 if (errno == ENOENT && proc_mounted() == 0)
539 return -ENOSYS;
540
541 return -errno;
542 }
543
544 CapabilityQuintet q = CAPABILITY_QUINTET_NULL;
545 for (;;) {
546 _cleanup_free_ char *line = NULL;
547
548 r = read_line(f, LONG_LINE_MAX, &line);
549 if (r < 0)
550 return r;
551 if (r == 0)
552 break;
553
554 static const struct {
555 const char *field;
556 size_t offset;
557 } fields[] = {
558 { "CapBnd:", offsetof(CapabilityQuintet, bounding) },
559 { "CapInh:", offsetof(CapabilityQuintet, inheritable) },
560 { "CapPrm:", offsetof(CapabilityQuintet, permitted) },
561 { "CapEff:", offsetof(CapabilityQuintet, effective) },
562 { "CapAmb:", offsetof(CapabilityQuintet, ambient) },
563 };
564
565 FOREACH_ELEMENT(i, fields) {
566
567 const char *p = first_word(line, i->field);
568 if (!p)
569 continue;
570
571 uint64_t *v = (uint64_t*) ((uint8_t*) &q + i->offset);
572
573 if (*v != CAP_MASK_UNSET)
574 return -EBADMSG;
575
576 r = safe_atoux64(p, v);
577 if (r < 0)
578 return r;
579
580 if (*v == CAP_MASK_UNSET)
581 return -EBADMSG;
582 }
583 }
584
585 if (!capability_quintet_is_fully_set(&q))
586 return -EBADMSG;
587
588 r = pidref_verify(pidref);
589 if (r < 0)
590 return r;
591
592 if (ret)
593 *ret = q;
594
595 return 0;
596 }