xref: /openbsd/regress/sys/kern/setuid/setresuid.c (revision 5dea098c)
1 /*	$OpenBSD: setresuid.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 	if ((pw = getpwnam(_SETUID_REGRESS_USER)) == NULL)
29 		err(1, "unknown user \"%s\"", _SETUID_REGRESS_USER);
30 
31 	uid = getuid();
32 
33 	if (setresuid(pw->pw_uid, -1, -1) == -1)
34 		err(1, "setuid 0");
35 	checkuids(pw->pw_uid, uid, uid, "0");
36 
37 	/* should only respond to setuid upon exec */
38 	if (issetugid())
39 		errx(1, "process incorrectly marked as issetugid()");
40 
41 	if (read_kproc_pid(&kproc, getpid()) == -1)
42 		err(1, "kproc read failed");
43 
44 	if (!(kproc.p_psflags & PS_SUGID))
45 		errx(1, "PS_SUGID not set");
46 	if (kproc.p_psflags & PS_SUGIDEXEC)
47 		errx(1, "PS_SUGIDEXEC incorrectly set");
48 
49 	/* we should be able to roll back our uids for now */
50 	if (setresuid(uid, -1, -1) == -1)
51 		err(1, "setuid 1");
52 	checkuids(uid, uid, uid, "1");
53 
54 	if (setresuid(-1, pw->pw_uid, -1) == -1)
55 		err(1, "setuid 2");
56 	checkuids(uid, pw->pw_uid, uid, "2");
57 
58 	/* we should be able to roll back our uids for now */
59 	if (setresuid(-1, uid, -1) == -1)
60 		err(1, "setuid 3");
61 	checkuids(uid, uid, uid, "3");
62 
63 	/*
64 	 * after changing our saved uid, we should be able to change
65 	 * our real and effective uids to that of our saved uid,
66 	 * but not to anything else
67 	 */
68 
69 	if (setresuid(-1, -1, pw->pw_uid) == -1)
70 		err(1, "setuid 4");
71 	checkuids(uid, uid, pw->pw_uid, "4");
72 
73 	if (setresuid(pw->pw_uid, -1, -1) == -1)
74 		err(1, "setuid 5");
75 	checkuids(pw->pw_uid, uid, pw->pw_uid, "5");
76 
77 	if (setresuid(-1, pw->pw_uid, -1) == -1)
78 		err(1, "setuid 6");
79 	checkuids(pw->pw_uid, pw->pw_uid, pw->pw_uid, "6");
80 
81 	if (setresuid(uid, -1, -1) != -1)
82 		errx(1, "incorrectly capable of setting real uid");
83 	checkuids(pw->pw_uid, pw->pw_uid, pw->pw_uid, "7");
84 
85 	if (setresuid(-1, uid, -1) != -1)
86 		errx(1, "incorrectly capable of setting effective uid");
87 	checkuids(pw->pw_uid, pw->pw_uid, pw->pw_uid, "9");
88 
89 	if (setresuid(-1, -1, uid) != -1)
90 		errx(1, "incorrectly capable of setting saved uid");
91 	checkuids(pw->pw_uid, pw->pw_uid, pw->pw_uid, "9");
92 
93 	/* sanity-check use of -1 as noop */
94 	if (setresuid(-1, -1, -1) == -1)
95 		errx(1, "-1 not properly recognized as noop");
96 	checkuids(pw->pw_uid, pw->pw_uid, pw->pw_uid, "9");
97 
98 	exit(0);
99 }
100