File: cap.c

package info (click to toggle)
linux 6.19.2-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 1,759,612 kB
  • sloc: ansic: 27,004,852; asm: 273,402; sh: 151,313; python: 81,277; makefile: 58,544; perl: 34,311; xml: 21,064; cpp: 5,984; yacc: 4,841; lex: 2,901; awk: 1,707; sed: 30; ruby: 25
file content (49 lines) | stat: -rw-r--r-- 1,269 bytes parent folder | download | duplicates (10)
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
// SPDX-License-Identifier: GPL-2.0
/*
 * Capability utilities
 */

#include "cap.h"
#include "debug.h"
#include <errno.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>

#define MAX_LINUX_CAPABILITY_U32S _LINUX_CAPABILITY_U32S_3

bool perf_cap__capable(int cap, bool *used_root)
{
	struct __user_cap_header_struct header = {
		.version = _LINUX_CAPABILITY_VERSION_3,
		.pid = 0,
	};
	struct __user_cap_data_struct data[MAX_LINUX_CAPABILITY_U32S] = {};
	__u32 cap_val;

	*used_root = false;
	while (syscall(SYS_capget, &header, &data[0]) == -1) {
		/* Retry, first attempt has set the header.version correctly. */
		if (errno == EINVAL && header.version != _LINUX_CAPABILITY_VERSION_3 &&
		    header.version == _LINUX_CAPABILITY_VERSION_1)
			continue;

		pr_debug2("capget syscall failed (%s - %d) fall back on root check\n",
			  strerror(errno), errno);
		*used_root = true;
		return geteuid() == 0;
	}

	/* Extract the relevant capability bit. */
	if (cap >= 32) {
		if (header.version == _LINUX_CAPABILITY_VERSION_3) {
			cap_val = data[1].effective;
		} else {
			/* Capability beyond 32 is requested but only 32 are supported. */
			return false;
		}
	} else {
		cap_val = data[0].effective;
	}
	return (cap_val & (1 << (cap & 0x1f))) != 0;
}