1 /*	$OpenBSD: setresgid_real_exec.c,v 1.1 2014/08/27 07:36:14 blambert Exp $	*/
2 /*
3  *	Written by Bret Stephen Lambert <blambert@openbsd.org> 2014
4  *	Public Domain.
5  */
6 
7 #include <sys/types.h>
8 #include <sys/param.h>
9 #include <sys/proc.h>
10 #include <sys/sysctl.h>
11 #include <sys/wait.h>
12 
13 #include <err.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <pwd.h>
18 #include <unistd.h>
19 
20 #include "setuid_regress.h"
21 
22 int
23 main(int argc, char *argv[])
24 {
25 	struct kinfo_proc	 kproc;
26 	struct passwd		*pw;
27 	char			*toexec = NULL;
28 	gid_t			 gid;
29 
30 	if (argc > 1) {
31 		argv++;
32 		if ((toexec = strdup(argv[0])) == NULL)
33 			err(1, "strdup");
34 	}
35 
36 	gid = getgid();
37 
38 	if ((pw = getpwnam(_SETUID_REGRESS_USER)) == NULL)
39 		err(1, "unknown user \"%s\"", _SETUID_REGRESS_USER);
40 
41 	if (setresgid(pw->pw_gid, -1, -1) == -1)
42 		err(1, "setgid");
43 	checkgids(pw->pw_gid, gid, gid, "setgid");
44 
45 	if (issetugid())
46 		errx(1, "process incorrectly marked as issetugid()");
47 
48 	if (read_kproc_pid(&kproc, getpid()) == -1)
49 		err(1, "kproc read failed");
50 
51 	if (!(kproc.p_psflags & PS_SUGID))
52 		errx(1, "PS_SUGID not set");
53 	if (kproc.p_psflags & PS_SUGIDEXEC)
54 		errx(1, "PS_SUGIDEXEC incorrectly set");
55 
56 	if (toexec != NULL)
57 		if (execv(toexec, argv) == -1)
58 			err(1, "exec of %s failed", toexec);
59 	free(toexec);
60 
61 	exit(0);
62 }
63