1 /* $OpenBSD: setresgid_saved_exec.c,v 1.3 2021/12/15 18:42:38 anton 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/signal.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
main(int argc,char * argv[])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(-1, -1, pw->pw_gid) == -1)
42 err(1, "setgid");
43 checkgids(gid, gid, pw->pw_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