• 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 #include "tst_uid.h"
41 
42 #define MODE_RWX	(mode_t)(S_IRWXU | S_IRWXG | S_IRWXO)
43 #define DIR_MODE	(mode_t)(S_ISVTX | S_ISGID | S_IFDIR)
44 #define PERMS		(mode_t)(MODE_RWX | DIR_MODE)
45 #define TESTDIR		"testdir"
46 
test_chmod(void)47 static void test_chmod(void)
48 {
49 	struct stat stat_buf;
50 	mode_t dir_mode;
51 
52 	TEST(chmod(TESTDIR, PERMS));
53 	if (TST_RET == -1) {
54 		tst_res(TFAIL, "chmod(%s, %#o) failed", TESTDIR, PERMS);
55 		return;
56 	}
57 
58 	SAFE_STAT(TESTDIR, &stat_buf);
59 	dir_mode = stat_buf.st_mode;
60 	if ((PERMS & ~S_ISGID) != dir_mode) {
61 		tst_res(TFAIL, "%s: Incorrect modes 0%03o, "
62 				"Expected 0%03o", TESTDIR, dir_mode,
63 				PERMS & ~S_ISGID);
64 	} else {
65 		tst_res(TPASS, "Functionality of chmod(%s, %#o) successful",
66 				TESTDIR, PERMS);
67 	}
68 }
69 
setup(void)70 static void setup(void)
71 {
72 	struct passwd *nobody_u;
73 	gid_t free_gid;
74 
75 	nobody_u = SAFE_GETPWNAM("nobody");
76 	free_gid = tst_get_free_gid(nobody_u->pw_gid);
77 
78 	/*
79 	 * Create a test directory under temporary directory with specified
80 	 * mode permissions and change the gid of test directory to nobody's
81 	 * gid.
82 	 */
83 	SAFE_MKDIR(TESTDIR, MODE_RWX);
84 	if (setgroups(1, &nobody_u->pw_gid) == -1)
85 		tst_brk(TBROK | TERRNO, "setgroups to nobody's gid failed");
86 
87 	SAFE_CHOWN(TESTDIR, nobody_u->pw_uid, free_gid);
88 
89 	/* change to nobody:nobody */
90 	SAFE_SETEGID(nobody_u->pw_gid);
91 	SAFE_SETEUID(nobody_u->pw_uid);
92 }
93 
94 static struct tst_test test = {
95 	.needs_root	= 1,
96 	.needs_tmpdir	= 1,
97 	.setup		= setup,
98 	.test_all	= test_chmod,
99 };
100