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