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