1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2001
4 * Ported by John George
5 * Copyright (C) 2021 SUSE LLC <mdoucha@suse.cz>
6 */
7
8 /*\
9 * [Description]
10 *
11 * Test setreuid() when executed by root.
12 */
13
14 #include <sys/types.h>
15 #include <pwd.h>
16
17 #include "tst_test.h"
18 #include "tst_uid.h"
19 #include "compat_tst_16.h"
20
21 static uid_t root_uid, nobody_uid, other_uid, neg_one = -1;
22
23 static struct test_data_t {
24 uid_t *real_uid;
25 uid_t *eff_uid;
26 uid_t *exp_real_uid;
27 uid_t *exp_eff_uid;
28 uid_t *exp_sav_uid;
29 const char *test_msg;
30 } test_data[] = {
31 {&neg_one, &neg_one, &root_uid, &root_uid, &root_uid,
32 "setreuid(-1, -1)"},
33 {&nobody_uid, &neg_one, &nobody_uid, &root_uid, &root_uid,
34 "setreuid(nobody, -1)"},
35 {&root_uid, &neg_one, &root_uid, &root_uid, &root_uid,
36 "setreuid(root, -1)"},
37 {&neg_one, &nobody_uid, &root_uid, &nobody_uid, &nobody_uid,
38 "setreuid(-1, nobody)"},
39 {&neg_one, &root_uid, &root_uid, &root_uid, &nobody_uid,
40 "setreuid(-1, root)"},
41 {&other_uid, &neg_one, &other_uid, &root_uid, &root_uid,
42 "setreuid(other, -1)"},
43 {&root_uid, &neg_one, &root_uid, &root_uid, &root_uid,
44 "setreuid(root, -1)"},
45 };
46
setup(void)47 static void setup(void)
48 {
49 uid_t test_users[2];
50 struct passwd *pw;
51
52 root_uid = getuid();
53 pw = SAFE_GETPWNAM("nobody");
54 nobody_uid = test_users[0] = pw->pw_uid;
55 tst_get_uids(test_users, 1, 2);
56 other_uid = test_users[1];
57
58 UID16_CHECK(root_uid, setreuid);
59 UID16_CHECK(nobody_uid, setreuid);
60 UID16_CHECK(other_uid, setreuid);
61
62 /* Make sure that saved UID is also set to root */
63 SAFE_SETUID(root_uid);
64 }
65
run(unsigned int n)66 static void run(unsigned int n)
67 {
68 const struct test_data_t *tc = test_data + n;
69
70 TST_EXP_PASS_SILENT(SETREUID(*tc->real_uid, *tc->eff_uid), "%s",
71 tc->test_msg);
72
73 if (!TST_PASS)
74 return;
75
76 if (tst_check_resuid(tc->test_msg, *tc->exp_real_uid, *tc->exp_eff_uid,
77 *tc->exp_sav_uid))
78 tst_res(TPASS, "%s works as expected", tc->test_msg);
79 }
80
81 static struct tst_test test = {
82 .test = run,
83 .tcnt = ARRAY_SIZE(test_data),
84 .setup = setup,
85 .needs_root = 1,
86 };
87