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