1
linux/tools/perf/util/cap.c
Ian Rogers e25ebda78e perf cap: Tidy up and improve capability testing
Remove dependence on libcap. libcap is only used to query whether a
capability is supported, which is just 1 capget system call.

If the capget system call fails, fall back on root permission
checking. Previously if libcap fails then the permission is assumed
not present which may be pessimistic/wrong.

Add a used_root out argument to perf_cap__capable to say whether the
fall back root check was used. This allows the correct error message,
"root" vs "users with the CAP_PERFMON or CAP_SYS_ADMIN capability", to
be selected.

Tidy uses of perf_cap__capable so that tests aren't repeated if capget
isn't supported.

Signed-off-by: Ian Rogers <irogers@google.com>
Cc: Adrian Hunter <adrian.hunter@intel.com>
Cc: Alexander Shishkin <alexander.shishkin@linux.intel.com>
Cc: Athira Rajeev <atrajeev@linux.vnet.ibm.com>
Cc: Changbin Du <changbin.du@huawei.com>
Cc: Ingo Molnar <mingo@redhat.com>
Cc: James Clark <james.clark@arm.com>
Cc: Jiri Olsa <jolsa@kernel.org>
Cc: Kan Liang <kan.liang@linux.intel.com>
Cc: Leo Yan <leo.yan@linux.dev>
Cc: Mark Rutland <mark.rutland@arm.com>
Cc: Namhyung Kim <namhyung@kernel.org>
Cc: Oliver Upton <oliver.upton@linux.dev>
Cc: Peter Zijlstra <peterz@infradead.org>
Link: https://lore.kernel.org/r/20240806220614.831914-1-irogers@google.com
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
2024-08-20 17:53:12 -03:00

55 lines
1.3 KiB
C

// SPDX-License-Identifier: GPL-2.0
/*
* Capability utilities
*/
#include "cap.h"
#include "debug.h"
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <linux/capability.h>
#include <sys/syscall.h>
#ifndef SYS_capget
#define SYS_capget 90
#endif
#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 = getpid(),
};
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;
}