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 * - 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 <stdio.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21
22 #include "tst_test.h"
23 #include "compat_tst_16.h"
24 #include "tst_safe_macros.h"
25
26 #define FILE_MODE (S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
27 #define NEW_PERMS1 (S_IFREG|S_IRWXU|S_IRWXG|S_ISUID|S_ISGID)
28 #define NEW_PERMS2 (S_IFREG|S_IRWXU|S_ISGID)
29 #define EXP_PERMS (S_IFREG|S_IRWXU|S_IRWXG)
30 #define TESTFILE1 "testfile1"
31 #define TESTFILE2 "testfile2"
32
33 static int fd1, fd2;
34
35 struct test_case_t {
36 int *fd;
37 const char *filename;
38 mode_t set_mode;
39 mode_t exp_mode;
40 } tc[] = {
41 {&fd1, TESTFILE1, NEW_PERMS1, EXP_PERMS},
42 {&fd2, TESTFILE2, NEW_PERMS2, NEW_PERMS2}
43 };
44
run(unsigned int i)45 static void run(unsigned int i)
46 {
47 struct stat stat_buf;
48 uid_t uid;
49 gid_t gid;
50
51 UID16_CHECK((uid = geteuid()), "fchown");
52 GID16_CHECK((gid = getegid()), "fchown");
53
54 SAFE_CHMOD(tc[i].filename, tc[i].set_mode);
55
56 TST_EXP_PASS(FCHOWN(*tc[i].fd, uid, gid),
57 "fchown(%i, %i, %i)", *tc[i].fd, uid, gid);
58
59 SAFE_STAT(tc[i].filename, &stat_buf);
60
61 if (stat_buf.st_uid != uid || stat_buf.st_gid != gid)
62 tst_res(TFAIL, "%s: owner set to (uid=%d, gid=%d), expected (uid=%d, gid=%d)",
63 tc[i].filename, stat_buf.st_uid, stat_buf.st_gid, uid, gid);
64
65 if (stat_buf.st_mode != tc[i].exp_mode)
66 tst_res(TFAIL, "%s: wrong mode permissions %#o, expected %#o",
67 tc[i].filename, stat_buf.st_mode, tc[i].exp_mode);
68 }
69
setup(void)70 static void setup(void)
71 {
72 unsigned int i;
73
74 for (i = 0; i < ARRAY_SIZE(tc); i++)
75 *tc[i].fd = SAFE_OPEN(tc[i].filename, O_RDWR | O_CREAT, FILE_MODE);
76 }
77
cleanup(void)78 static void cleanup(void)
79 {
80 unsigned int i;
81
82 for (i = 0; i < ARRAY_SIZE(tc); i++) {
83 if (*tc[i].fd > 0)
84 SAFE_CLOSE(*tc[i].fd);
85 }
86 }
87
88 static struct tst_test test = {
89 .tcnt = ARRAY_SIZE(tc),
90 .needs_root = 1,
91 .needs_tmpdir = 1,
92 .setup = setup,
93 .cleanup = cleanup,
94 .test = run,
95 };
96