• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /// SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (c) International Business Machines  Corp., 2001
4  */
5 
6 /*
7  * Test Name: chmod05
8  *
9  * Test Description:
10  *  Verify that, chmod(2) will succeed to change the mode of a directory
11  *  but fails to set the setgid bit on it if invoked by non-root (uid != 0)
12  *  process with the following constraints,
13  *	- the process is the owner of the directory.
14  *	- the effective group ID or one of the supplementary group ID's of the
15  *	  process is not equal to the group ID of the directory.
16  *
17  * Expected Result:
18  *  chmod() should return value 0 on success and though succeeds to change
19  *  the mode of a directory but fails to set setgid bit on it.
20  *
21  */
22 
23 #ifndef _GNU_SOURCE
24 # define _GNU_SOURCE
25 #endif
26 
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <errno.h>
33 #include <string.h>
34 #include <signal.h>
35 #include <unistd.h>
36 #include <grp.h>
37 #include <pwd.h>
38 
39 #include "tst_test.h"
40 
41 #define MODE_RWX	(mode_t)(S_IRWXU | S_IRWXG | S_IRWXO)
42 #define DIR_MODE	(mode_t)(S_ISVTX | S_ISGID | S_IFDIR)
43 #define PERMS		(mode_t)(MODE_RWX | DIR_MODE)
44 #define TESTDIR		"testdir"
45 
test_chmod(void)46 static void test_chmod(void)
47 {
48 	struct stat stat_buf;
49 	mode_t dir_mode;
50 
51 	TEST(chmod(TESTDIR, PERMS));
52 	if (TST_RET == -1) {
53 		tst_res(TFAIL, "chmod(%s, %#o) failed", TESTDIR, PERMS);
54 		return;
55 	}
56 
57 	SAFE_STAT(TESTDIR, &stat_buf);
58 	dir_mode = stat_buf.st_mode;
59 	if ((PERMS & ~S_ISGID) != dir_mode) {
60 		tst_res(TFAIL, "%s: Incorrect modes 0%03o, "
61 				"Expected 0%03o", TESTDIR, dir_mode,
62 				PERMS & ~S_ISGID);
63 	} else {
64 		tst_res(TPASS, "Functionality of chmod(%s, %#o) successful",
65 				TESTDIR, PERMS);
66 	}
67 }
68 
setup(void)69 static void setup(void)
70 {
71 	struct passwd *nobody_u;
72 	struct group *bin_gr;
73 
74 	nobody_u = SAFE_GETPWNAM("nobody");
75 	bin_gr = SAFE_GETGRNAM("bin");
76 
77 	/*
78 	 * Create a test directory under temporary directory with specified
79 	 * mode permissions and change the gid of test directory to nobody's
80 	 * gid.
81 	 */
82 	SAFE_MKDIR(TESTDIR, MODE_RWX);
83 	if (setgroups(1, &nobody_u->pw_gid) == -1)
84 		tst_brk(TBROK | TERRNO, "setgroups to nobody's gid failed");
85 
86 	SAFE_CHOWN(TESTDIR, nobody_u->pw_uid, bin_gr->gr_gid);
87 
88 	/* change to nobody:nobody */
89 	SAFE_SETEGID(nobody_u->pw_gid);
90 	SAFE_SETEUID(nobody_u->pw_uid);
91 }
92 
93 static struct tst_test test = {
94 	.needs_root	= 1,
95 	.needs_tmpdir	= 1,
96 	.setup		= setup,
97 	.test_all	= test_chmod,
98 };
99