• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) Linux Test Project, 2001-2021
4  * Copyright (c) International Business Machines  Corp., 2001
5  * 07/2001 Ported by Wayne Boyer
6  */
7 
8 /*\
9  * [Description]
10  *
11  * Verify that, fchown(2) succeeds to change the group of a file specified
12  * by path when called by non-root user with the following constraints:
13  *
14  * - euid of the process is equal to the owner of the file
15  * - the intended gid is either egid, or one of the supplementary gids
16  *   of the process.
17  *
18  * Also verify that fchown() clears the setuid/setgid bits set on the file.
19  */
20 
21 #include <grp.h>
22 #include <pwd.h>
23 #include <fcntl.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 
27 #include "tst_test.h"
28 #include "compat_tst_16.h"
29 
30 #define FILE_MODE	(S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
31 #define NEW_PERMS	(S_IFREG|S_IRWXU|S_IRWXG|S_ISUID|S_ISGID)
32 #define FILENAME	"fchown03_testfile"
33 
34 static int fd;
35 static struct passwd *ltpuser;
36 
check_owner(struct stat * s,uid_t exp_uid,gid_t exp_gid)37 static void check_owner(struct stat *s, uid_t exp_uid, gid_t exp_gid)
38 {
39 	if (s->st_uid != exp_uid || s->st_gid != exp_gid)
40 		tst_res(TFAIL, "%s: wrong owner set to (uid=%d, gid=%d), expected (uid=%d, gid=%d)",
41 			FILENAME, s->st_uid, s->st_gid, exp_uid, exp_gid);
42 }
43 
check_mode(struct stat * s,mode_t exp_mode)44 static void check_mode(struct stat *s, mode_t exp_mode)
45 {
46 	if (s->st_mode != exp_mode)
47 		tst_res(TFAIL, "%s: wrong mode permissions %#o, expected %#o",
48 			FILENAME, s->st_mode, exp_mode);
49 }
50 
run(void)51 static void run(void)
52 {
53 	uid_t uid;
54 	gid_t gid;
55 	struct stat stat_buf;
56 
57 	SAFE_SETEUID(0);
58 	SAFE_FCHOWN(fd, -1, 0);
59 	SAFE_FCHMOD(fd, NEW_PERMS);
60 	SAFE_SETEUID(ltpuser->pw_uid);
61 
62 	UID16_CHECK((uid = geteuid()), "fchown");
63 	GID16_CHECK((gid = getegid()), "fchown");
64 
65 	SAFE_STAT(FILENAME, &stat_buf);
66 	check_owner(&stat_buf, uid, 0);
67 	check_mode(&stat_buf, NEW_PERMS);
68 
69 	TST_EXP_PASS(FCHOWN(fd, -1, gid), "fchown(fd, %d, %d)", -1, gid);
70 	SAFE_STAT(FILENAME, &stat_buf);
71 	check_owner(&stat_buf, uid, gid);
72 	check_mode(&stat_buf, NEW_PERMS & ~(S_ISUID | S_ISGID));
73 }
74 
setup(void)75 static void setup(void)
76 {
77 	ltpuser = SAFE_GETPWNAM("nobody");
78 	SAFE_SETEGID(ltpuser->pw_gid);
79 	SAFE_SETEUID(ltpuser->pw_uid);
80 
81 	fd = SAFE_OPEN(FILENAME, O_RDWR | O_CREAT, FILE_MODE);
82 }
83 
cleanup(void)84 static void cleanup(void)
85 {
86 	SAFE_SETEGID(0);
87 	SAFE_SETEUID(0);
88 
89 	if (fd > 0)
90 		SAFE_CLOSE(fd);
91 }
92 
93 static struct tst_test test = {
94 	.needs_root = 1,
95 	.needs_tmpdir = 1,
96 	.setup = setup,
97 	.cleanup = cleanup,
98 	.test_all = run,
99 };
100