1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2001
4 * Author: Wayne Boyer
5 *
6 * Test Description:
7 * Verify that, fchmod(2) will succeed to change the mode of a directory
8 * but fails to set the setgid bit on it if invoked by non-root (uid != 0)
9 * process with the following constraints,
10 * - the process is the owner of the directory.
11 * - the effective group ID or one of the supplementary group ID's of the
12 * process is not equal to the group ID of the directory.
13 *
14 * Expected Result:
15 * fchmod() should return value 0 on success and though succeeds to change
16 * the mode of a directory but fails to set setgid bit on it.
17 */
18
19 #include <pwd.h>
20 #include <errno.h>
21
22 #include "tst_test.h"
23 #include "tst_uid.h"
24 #include "fchmod.h"
25
26 #define PERMS_DIR 043777
27
28 static int fd;
29
verify_fchmod(void)30 static void verify_fchmod(void)
31 {
32 struct stat stat_buf;
33 mode_t dir_mode;
34
35 TEST(fchmod(fd, PERMS_DIR));
36 if (TST_RET == -1)
37 tst_res(TFAIL | TTERRNO, "fchmod() failed unexpectly");
38
39 SAFE_FSTAT(fd, &stat_buf);
40 dir_mode = stat_buf.st_mode;
41
42 if ((PERMS_DIR & ~S_ISGID) != dir_mode) {
43 tst_res(TFAIL, "%s: Incorrect modes 0%03o, Expected 0%03o",
44 TESTDIR, dir_mode & ~S_ISGID, PERMS_DIR);
45 } else {
46 tst_res(TPASS, "Functionality of fchmod(%d, %#o) successful",
47 fd, PERMS_DIR);
48 }
49 }
50
setup(void)51 static void setup(void)
52 {
53 struct passwd *ltpuser;
54 gid_t free_gid;
55
56 ltpuser = SAFE_GETPWNAM("nobody");
57 free_gid = tst_get_free_gid(ltpuser->pw_gid);
58
59 SAFE_MKDIR(TESTDIR, DIR_MODE);
60
61 if (setgroups(1, <puser->pw_gid) == -1) {
62 tst_brk(TBROK, "Couldn't change supplementary group Id: %s",
63 tst_strerrno(TST_ERR));
64 }
65
66 SAFE_CHOWN(TESTDIR, ltpuser->pw_uid, free_gid);
67
68 SAFE_SETEGID(ltpuser->pw_gid);
69 SAFE_SETEUID(ltpuser->pw_uid);
70
71 fd = SAFE_OPEN(TESTDIR, O_RDONLY);
72 }
73
cleanup(void)74 static void cleanup(void)
75 {
76 if (fd > 0)
77 SAFE_CLOSE(fd);
78
79 SAFE_SETEGID(0);
80 SAFE_SETEUID(0);
81 }
82
83 static struct tst_test test = {
84 .test_all = verify_fchmod,
85 .needs_root = 1,
86 .setup = setup,
87 .cleanup = cleanup,
88 .needs_tmpdir = 1,
89 };
90