summaryrefslogtreecommitdiff
path: root/tools/testing/selftests/bpf/cap_helpers.c
blob: d5ac507401d7cd03148d5e220b91b0533a50f7d8 (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
// SPDX-License-Identifier: GPL-2.0
#include "cap_helpers.h"

/* Avoid including <sys/capability.h> from the libcap-devel package,
 * so directly declare them here and use them from glibc.
 */
int capget(cap_user_header_t header, cap_user_data_t data);
int capset(cap_user_header_t header, const cap_user_data_t data);

int cap_enable_effective(__u64 caps, __u64 *old_caps)
{
	struct __user_cap_data_struct data[_LINUX_CAPABILITY_U32S_3];
	struct __user_cap_header_struct hdr = {
		.version = _LINUX_CAPABILITY_VERSION_3,
	};
	__u32 cap0 = caps;
	__u32 cap1 = caps >> 32;
	int err;

	err = capget(&hdr, data);
	if (err)
		return err;

	if (old_caps)
		*old_caps = (__u64)(data[1].effective) << 32 | data[0].effective;

	if ((data[0].effective & cap0) == cap0 &&
	    (data[1].effective & cap1) == cap1)
		return 0;

	data[0].effective |= cap0;
	data[1].effective |= cap1;
	err = capset(&hdr, data);
	if (err)
		return err;

	return 0;
}

int cap_disable_effective(__u64 caps, __u64 *old_caps)
{
	struct __user_cap_data_struct data[_LINUX_CAPABILITY_U32S_3];
	struct __user_cap_header_struct hdr = {
		.version = _LINUX_CAPABILITY_VERSION_3,
	};
	__u32 cap0 = caps;
	__u32 cap1 = caps >> 32;
	int err;

	err = capget(&hdr, data);
	if (err)
		return err;

	if (old_caps)
		*old_caps = (__u64)(data[1].effective) << 32 | data[0].effective;

	if (!(data[0].effective & cap0) && !(data[1].effective & cap1))
		return 0;

	data[0].effective &= ~cap0;
	data[1].effective &= ~cap1;
	err = capset(&hdr, data);
	if (err)
		return err;

	return 0;
}