xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/setgroups/setgroups03.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) Bull S.A. 2001
4  * Copyright (c) International Business Machines  Corp., 2001
5  * Copyright (c) Linux Test Project, 2003-2023
6  * 07/2001 Ported by Wayne Boyer
7  * 05/2002 Ported by Andre Merlier
8  */
9 
10 /*\
11  * [Description]
12  *
13  * Test for EINVAL, EPERM, EFAULT errors.
14  *
15  * - setgroups() fails with EINVAL if the size argument value is > NGROUPS.
16  *
17  * - setgroups() fails with EPERM if the calling process is not super-user.
18  *
19  * - setgroups() fails with EFAULT if the list has an invalid address.
20  */
21 
22 #include <pwd.h>
23 #include <stdlib.h>
24 
25 #include "tst_test.h"
26 #include "compat_tst_16.h"
27 
28 #define TESTUSER	"nobody"
29 
30 static GID_T *glist1, *glist2, *glist3;
31 static struct passwd *user_info;
32 
33 static struct tcase {
34 	int gsize;
35 	GID_T **glist;
36 	int exp_errno;
37 } tcases[] = {
38 	{NGROUPS + 1, &glist1, EINVAL},
39 	{1, &glist2, EPERM},
40 	{NGROUPS, &glist3, EFAULT},
41 };
42 
verify_setgroups(unsigned int i)43 static void verify_setgroups(unsigned int i)
44 {
45 	struct tcase *tc = &tcases[i];
46 
47 	if (tc->exp_errno == EPERM)
48 		SAFE_SETEUID(user_info->pw_uid);
49 
50 	TST_EXP_FAIL(SETGROUPS(tc->gsize, *tc->glist), tc->exp_errno,
51 		     "setgroups(%d, groups_list)", tc->gsize);
52 
53 	if (tc->exp_errno == EPERM)
54 		SAFE_SETEUID(0);
55 }
56 
setup(void)57 static void setup(void)
58 {
59 	user_info = SAFE_GETPWNAM(TESTUSER);
60 	glist2[0] = 42;
61 	glist3 = tst_get_bad_addr(NULL);
62 }
63 
64 static struct tst_test test = {
65 	.test = verify_setgroups,
66 	.tcnt = ARRAY_SIZE(tcases),
67 	.bufs = (struct tst_buffers []) {
68 		{&glist1, .size = sizeof(GID_T) * (NGROUPS + 1)},
69 		{&glist2, .size = sizeof(GID_T)},
70 		{&user_info, .size = sizeof(struct passwd)},
71 		{},
72 	},
73 	.setup = setup,
74 	.needs_root = 1,
75 };
76