xref: /freebsd/contrib/sendmail/test/t_setgid.c (revision 0b3105a37d7adcadcb720112fed4dc4e8040be99)
1 /*
2  * Copyright (c) 2001 Proofpoint, Inc. and its suppliers.
3  *	All rights reserved.
4  *
5  * By using this file, you agree to the terms and conditions set
6  * forth in the LICENSE file which can be found at the top level of
7  * the sendmail distribution.
8  *
9  */
10 
11 /*
12 **  This program checks to see if your version of setgid works.
13 **  Compile it, make it set-group-ID guest, and run it as yourself (NOT as
14 **  root and not as member of the group guest).
15 **
16 **  Compilation is trivial -- just "cc t_setgid.c".  Make it set-group-ID,
17 **  guest and then execute it as a non-root user.
18 */
19 
20 #include <sys/types.h>
21 #include <unistd.h>
22 #include <stdio.h>
23 
24 #ifndef lint
25 static char id[] = "@(#)$Id: t_setgid.c,v 1.7 2013-11-22 20:52:01 ca Exp $";
26 #endif /* ! lint */
27 
28 static void
29 printgids(str, r, e)
30 	char *str;
31 	gid_t r, e;
32 {
33 	printf("%s (should be %d/%d): r/egid=%d/%d\n", str, (int) r, (int) e,
34 	       (int) getgid(), (int) getegid());
35 }
36 
37 int
38 main(argc, argv)
39 	int argc;
40 	char **argv;
41 {
42 	int fail = 0;
43 	int res;
44 	gid_t realgid = getgid();
45 	gid_t effgid = getegid();
46 
47 	printgids("initial gids", realgid, effgid);
48 
49 	if (effgid == realgid)
50 	{
51 		printf("SETUP ERROR: re-run set-group-ID guest\n");
52 		exit(1);
53 	}
54 
55 #if SM_CONF_SETREGID
56 	res = setregid(effgid, effgid);
57 #else /* SM_CONF_SETREGID */
58 	res = setgid(effgid);
59 #endif /* SM_CONF_SETREGID */
60 
61 	printf("setgid(%d)=%d %s\n", (int) effgid, res,
62 		res < 0 ? "failure" : "ok");
63 #if SM_CONF_SETREGID
64 	printgids("after setregid()", effgid, effgid);
65 #else /* SM_CONF_SETREGID */
66 	printgids("after setgid()", effgid, effgid);
67 #endif /* SM_CONF_SETREGID */
68 
69 	if (getegid() != effgid)
70 	{
71 		fail++;
72 		printf("MAYDAY!  Wrong effective gid\n");
73 	}
74 
75 	if (getgid() != effgid)
76 	{
77 		fail++;
78 		printf("MAYDAY!  Wrong real gid\n");
79 	}
80 
81 	/* do activity here */
82 	if (setgid(0) == 0)
83 	{
84 		fail++;
85 		printf("MAYDAY!  setgid(0) succeeded (should have failed)\n");
86 	}
87 	else
88 	{
89 		printf("setgid(0) failed (this is correct)\n");
90 	}
91 	printgids("after setgid(0)", effgid, effgid);
92 
93 	if (getegid() != effgid)
94 	{
95 		fail++;
96 		printf("MAYDAY!  Wrong effective gid\n");
97 	}
98 	if (getgid() != effgid)
99 	{
100 		fail++;
101 		printf("MAYDAY!  Wrong real gid\n");
102 	}
103 	printf("\n");
104 
105 	if (fail > 0)
106 	{
107 		printf("\nThis system cannot use %s to set the real gid to the effective gid\nand clear the saved gid.\n",
108 #if SM_CONF_SETREGID
109 			"setregid"
110 #else /* SM_CONF_SETREGID */
111 			"setgid"
112 #endif /* SM_CONF_SETREGID */
113 			);
114 		exit(1);
115 	}
116 
117 	printf("\nIt is possible to use setgid on this system\n");
118 	exit(0);
119 }
120