xref: /aosp_15_r20/external/ltp/testcases/kernel/containers/userns/userns01.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) Huawei Technologies Co., Ltd., 2015
4  * Copyright (C) 2022 SUSE LLC Andrea Cervesato <[email protected]>
5  */
6 
7 /*\
8  * [Description]
9  *
10  * Verify that if a user ID has no mapping inside the namespace, user ID and
11  * group ID will be the value defined in the file /proc/sys/kernel/overflowuid
12  * (defaults to 65534) and /proc/sys/kernel/overflowgid (defaults to 65534). A
13  * child process has a full set of permitted and effective capabilities, even
14  * though the program was run from an unprivileged account.
15  */
16 
17 #include "tst_test.h"
18 
19 #ifdef HAVE_LIBCAP
20 #define _GNU_SOURCE
21 
22 #include <stdio.h>
23 #include "config.h"
24 #include <sys/capability.h>
25 #include "lapi/sched.h"
26 
27 #define OVERFLOWUIDPATH "/proc/sys/kernel/overflowuid"
28 #define OVERFLOWGIDPATH "/proc/sys/kernel/overflowgid"
29 
30 static long overflowuid;
31 static long overflowgid;
32 
child_fn1(void)33 static void child_fn1(void)
34 {
35 	int uid, gid;
36 	cap_t caps;
37 	int i, last_cap;
38 	cap_flag_value_t flag_val;
39 
40 	uid = geteuid();
41 	gid = getegid();
42 
43 	tst_res(TINFO, "USERNS test is running in a new user namespace.");
44 
45 	TST_EXP_EQ_LI(uid, overflowuid);
46 	TST_EXP_EQ_LI(gid, overflowgid);
47 
48 	caps = cap_get_proc();
49 
50 	SAFE_FILE_SCANF("/proc/sys/kernel/cap_last_cap", "%d", &last_cap);
51 
52 	for (i = 0; i <= last_cap; i++) {
53 		cap_get_flag(caps, i, CAP_EFFECTIVE, &flag_val);
54 		if (!flag_val)
55 			break;
56 
57 		cap_get_flag(caps, i, CAP_PERMITTED, &flag_val);
58 		if (!flag_val)
59 			break;
60 	}
61 
62 	if (!flag_val)
63 		tst_res(TFAIL, "unexpected effective/permitted caps at %d", i);
64 	else
65 		tst_res(TPASS, "expected capabilities");
66 }
67 
setup(void)68 static void setup(void)
69 {
70 	SAFE_FILE_SCANF(OVERFLOWUIDPATH, "%ld", &overflowuid);
71 	SAFE_FILE_SCANF(OVERFLOWGIDPATH, "%ld", &overflowgid);
72 }
73 
run(void)74 static void run(void)
75 {
76 	const struct tst_clone_args args = {
77 		.flags = CLONE_NEWUSER,
78 		.exit_signal = SIGCHLD,
79 	};
80 
81 	if (!SAFE_CLONE(&args)) {
82 		child_fn1();
83 		return;
84 	}
85 }
86 
87 static struct tst_test test = {
88 	.setup = setup,
89 	.test_all = run,
90 	.needs_root = 1,
91 	.forks_child = 1,
92 	.caps = (struct tst_cap []) {
93 		TST_CAP(TST_CAP_DROP, CAP_NET_RAW),
94 		{}
95 	},
96 	.needs_kconfigs = (const char *[]) {
97 		"CONFIG_USER_NS",
98 		NULL,
99 	},
100 };
101 
102 #else
103 TST_TEST_TCONF("System is missing libcap");
104 #endif
105