1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2001
4 * 07/2001 Ported by Wayne Boyer
5 * Copyright (c) 2021 Xie Ziyao <xieziyao@huawei.com>
6 */
7
8 /*\
9 * [Description]
10 *
11 * Verify that chown(2) invoked by super-user:
12 * - clears setuid and setgid bits set on an executable file
13 * - preserves setgid bit set on a non-group-executable file
14 */
15
16 #include "tst_test.h"
17 #include "compat_tst_16.h"
18 #include "tst_safe_macros.h"
19
20 #define NEW_PERMS1 (S_IFREG|S_IRWXU|S_IRWXG|S_ISUID|S_ISGID)
21 #define NEW_PERMS2 (S_IFREG|S_IRWXU|S_ISGID)
22 #define EXP_PERMS (S_IFREG|S_IRWXU|S_IRWXG)
23 #define TESTFILE1 "testfile1"
24 #define TESTFILE2 "testfile2"
25
26 struct test_case_t {
27 const char *filename;
28 mode_t set_mode;
29 mode_t exp_mode;
30 } tc[] = {
31 {TESTFILE1, NEW_PERMS1, EXP_PERMS},
32 {TESTFILE2, NEW_PERMS2, NEW_PERMS2}
33 };
34
run(unsigned int i)35 static void run(unsigned int i)
36 {
37 uid_t uid;
38 gid_t gid;
39
40 UID16_CHECK((uid = geteuid()), "chown");
41 GID16_CHECK((gid = getegid()), "chown");
42
43 SAFE_CHMOD(tc[i].filename, tc[i].set_mode);
44
45 TST_EXP_PASS(CHOWN(tc[i].filename, uid, gid), "chown(%s, %d, %d)",
46 tc[i].filename, uid, gid);
47
48 struct stat stat_buf;
49 SAFE_STAT(tc[i].filename, &stat_buf);
50
51 if (stat_buf.st_uid != uid || stat_buf.st_gid != gid) {
52 tst_res(TFAIL, "%s: owner set to (uid=%d, gid=%d), expected (uid=%d, gid=%d)",
53 tc[i].filename, stat_buf.st_uid, stat_buf.st_gid, uid, gid);
54 }
55
56 if (stat_buf.st_mode != tc[i].exp_mode) {
57 tst_res(TFAIL, "%s: wrong mode permissions %#o, expected %#o",
58 tc[i].filename, stat_buf.st_mode, tc[i].exp_mode);
59 }
60 }
61
setup(void)62 static void setup(void)
63 {
64 unsigned int i;
65
66 for (i = 0; i < ARRAY_SIZE(tc); i++)
67 SAFE_TOUCH(tc[i].filename, tc[i].set_mode, NULL);
68 }
69
70 static struct tst_test test = {
71 .tcnt = ARRAY_SIZE(tc),
72 .needs_root = 1,
73 .needs_tmpdir = 1,
74 .setup = setup,
75 .test = run,
76 };
77