1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) Linux Test Project, 2003-2021
4 * Copyright (c) 2014 Cyril Hrubis <chrubis@suse.cz>
5 * Copyright (c) International Business Machines Corp., 2001
6 * 07/2001 Ported by Wayne Boyer
7 */
8
9 /*\
10 * [Description]
11 *
12 * Verify that fchown(2) invoked by super-user:
13 *
14 * - clears setuid and setgid bits set on an executable file
15 * - preserves setgid bit set on a non-group-executable file
16 */
17
18 #include <stdio.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <fcntl.h>
22
23 #include "tst_test.h"
24 #include "compat_tst_16.h"
25 #include "tst_safe_macros.h"
26
27 #define FILE_MODE (S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
28 #define NEW_PERMS1 (S_IFREG|S_IRWXU|S_IRWXG|S_ISUID|S_ISGID)
29 #define NEW_PERMS2 (S_IFREG|S_IRWXU|S_ISGID)
30 #define EXP_PERMS (S_IFREG|S_IRWXU|S_IRWXG)
31 #define TESTFILE1 "testfile1"
32 #define TESTFILE2 "testfile2"
33
34 static int fd1, fd2;
35
36 struct test_case_t {
37 int *fd;
38 const char *filename;
39 mode_t set_mode;
40 mode_t exp_mode;
41 } tc[] = {
42 {&fd1, TESTFILE1, NEW_PERMS1, EXP_PERMS},
43 {&fd2, TESTFILE2, NEW_PERMS2, NEW_PERMS2}
44 };
45
run(unsigned int i)46 static void run(unsigned int i)
47 {
48 struct stat stat_buf;
49 uid_t uid;
50 gid_t gid;
51
52 UID16_CHECK((uid = geteuid()), "fchown");
53 GID16_CHECK((gid = getegid()), "fchown");
54
55 SAFE_CHMOD(tc[i].filename, tc[i].set_mode);
56
57 TST_EXP_PASS(FCHOWN(*tc[i].fd, uid, gid),
58 "fchown(%i, %i, %i)", *tc[i].fd, uid, gid);
59
60 SAFE_STAT(tc[i].filename, &stat_buf);
61
62 if (stat_buf.st_uid != uid || stat_buf.st_gid != gid)
63 tst_res(TFAIL, "%s: owner set to (uid=%d, gid=%d), expected (uid=%d, gid=%d)",
64 tc[i].filename, stat_buf.st_uid, stat_buf.st_gid, uid, gid);
65
66 if (stat_buf.st_mode != tc[i].exp_mode)
67 tst_res(TFAIL, "%s: wrong mode permissions %#o, expected %#o",
68 tc[i].filename, stat_buf.st_mode, tc[i].exp_mode);
69 }
70
setup(void)71 static void setup(void)
72 {
73 unsigned int i;
74
75 for (i = 0; i < ARRAY_SIZE(tc); i++)
76 *tc[i].fd = SAFE_OPEN(tc[i].filename, O_RDWR | O_CREAT, FILE_MODE);
77 }
78
cleanup(void)79 static void cleanup(void)
80 {
81 unsigned int i;
82
83 for (i = 0; i < ARRAY_SIZE(tc); i++) {
84 if (*tc[i].fd > 0)
85 SAFE_CLOSE(*tc[i].fd);
86 }
87 }
88
89 static struct tst_test test = {
90 .tcnt = ARRAY_SIZE(tc),
91 .needs_root = 1,
92 .needs_tmpdir = 1,
93 .setup = setup,
94 .cleanup = cleanup,
95 .test = run,
96 };
97