xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/setreuid/setreuid07.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-later
2 /*
3  * Copyright (c) Kerlabs 2008.
4  * Copyright (c) International Business Machines  Corp., 2008
5  * Created by Renaud Lottiaux
6  * Copyright (c) 2023 SUSE LLC Avinesh Kumar <[email protected]>
7  */
8 
9 /*\
10  * [Description]
11  *
12  * Check if setreuid behaves correctly with file permissions.
13  * The test creates a file as ROOT with permissions 0644, does a setreuid
14  * and then tries to open the file with RDWR permissions.
15  * The same test is done in a fork to check if new UIDs are correctly
16  * passed to the child process.
17  */
18 
19 #include <pwd.h>
20 #include <stdlib.h>
21 
22 #include "tst_test.h"
23 #include "compat_tst_16.h"
24 
25 #define TEMPFILE "testfile"
26 
27 static struct passwd *ltpuser;
28 
setup(void)29 static void setup(void)
30 {
31 	int fd;
32 
33 	ltpuser = SAFE_GETPWNAM("nobody");
34 
35 	UID16_CHECK(ltpuser->pw_uid, setreuid);
36 	fd = SAFE_OPEN(TEMPFILE, O_CREAT | O_RDWR, 0644);
37 	SAFE_CLOSE(fd);
38 }
39 
run(void)40 static void run(void)
41 {
42 	pid_t pid;
43 
44 	TST_EXP_PASS_SILENT(SETREUID(-1, ltpuser->pw_uid));
45 	TST_EXP_FAIL2(open(TEMPFILE, O_RDWR), EACCES);
46 
47 	pid = SAFE_FORK();
48 	if (pid == 0) {
49 		TST_EXP_FAIL2(open(TEMPFILE, O_RDWR), EACCES);
50 		exit(0);
51 	}
52 	tst_reap_children();
53 
54 	TST_EXP_PASS_SILENT(SETREUID(-1, 0));
55 	TST_EXP_FD(open(TEMPFILE, O_RDWR));
56 	SAFE_CLOSE(TST_RET);
57 }
58 
59 static struct tst_test test = {
60 	.setup = setup,
61 	.test_all = run,
62 	.needs_root = 1,
63 	.forks_child = 1,
64 	.needs_tmpdir = 1,
65 };
66