xref: /openbsd-src/regress/sys/kern/setuid/setresuid_effective_exec.c (revision 49a6e16f2c2c8e509184b1f777366d1a6f337e1c)
1 /*	$OpenBSD: setresuid_effective_exec.c,v 1.2 2021/12/13 16:56:50 deraadt 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/proc.h>
9 #include <sys/sysctl.h>
10 #include <sys/wait.h>
11 
12 #include <err.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <pwd.h>
17 #include <unistd.h>
18 
19 #include "setuid_regress.h"
20 
21 int
22 main(int argc, char *argv[])
23 {
24 	struct kinfo_proc	 kproc;
25 	struct passwd		*pw;
26 	char			*toexec = NULL;
27 	uid_t			 uid;
28 
29 	if (argc > 1) {
30 		argv ++;
31 		if ((toexec = strdup(argv[0])) == NULL)
32 			err(1, "strdup");
33 	}
34 
35 	if ((pw = getpwnam(_SETUID_REGRESS_USER)) == NULL)
36 		err(1, "unknown user \"%s\"", _SETUID_REGRESS_USER);
37 
38 	uid = getuid();
39 
40 	if (setresuid(-1, pw->pw_uid, -1) == -1)
41 		err(1, "setuid");
42 	checkuids(uid, pw->pw_uid, uid, "setuid");
43 
44 	/* should only respond to setuid upon exec */
45 	if (issetugid())
46 		errx(1, "process incorrectly 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