xref: /openbsd/regress/sys/kern/setuid/seteuid.c (revision 5dea098c)
1 /*	$OpenBSD: seteuid.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 <pwd.h>
17 #include <unistd.h>
18 
19 #include "setuid_regress.h"
20 
21 int
22 main(int argc, const char *argv[])
23 {
24 	struct kinfo_proc	 kproc;
25 	struct passwd		*pw;
26 	uid_t			 uid;
27 
28 	uid = getuid();
29 
30 	if ((pw = getpwnam(_SETUID_REGRESS_USER)) == NULL)
31 		err(1, "unknown user \"%s\"", _SETUID_REGRESS_USER);
32 
33 	if (seteuid(pw->pw_uid) == -1)
34 		err(1, "seteuid 0");
35 
36 	if (geteuid() != pw->pw_uid)
37 		errx(1, "mismatched effective uids");
38 
39 	checkuids(uid, pw->pw_uid, uid, "seteuid");
40 
41 	/* should only respond to setuid upon exec */
42 	if (issetugid())
43 		errx(1, "process incorrectly marked as issetugid()");
44 
45 	if (read_kproc_pid(&kproc, getpid()) == -1)
46 		err(1, "kproc read 0 failed");
47 
48 	if (!(kproc.p_psflags & PS_SUGID))
49 		errx(1, "PS_SUGID not set");
50 	if (kproc.p_psflags & PS_SUGIDEXEC)
51 		errx(1, "PS_SUGIDEXEC incorrectly set");
52 
53 	/* at this point, we should be able to reset our uid */
54 	if (seteuid(uid) == -1)
55 		err(1, "seteuid 1");
56 
57 	if (read_kproc_pid(&kproc, getpid()) == -1)
58 		err(1, "kproc read 1 failed");
59 
60 	if (!(kproc.p_psflags & PS_SUGID))
61 		errx(1, "PS_SUGID not set");
62 	if (kproc.p_psflags & PS_SUGIDEXEC)
63 		errx(1, "PS_SUGIDEXEC incorrectly set");
64 
65 	exit(0);
66 }
67