xref: /freebsd/crypto/openssh/openbsd-compat/bsd-setres_id.c (revision 8d20be1e22095c27faf8fe8b2f0d089739cc742e)
1 /* $Id: bsd-setres_id.c,v 1.1 2012/11/05 06:04:37 dtucker Exp $ */
2 
3 /*
4  * Copyright (c) 2012 Darren Tucker (dtucker at zip com au).
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include "includes.h"
20 
21 #include <sys/types.h>
22 
23 #include <stdarg.h>
24 #include <unistd.h>
25 
26 #include "log.h"
27 
28 #if !defined(HAVE_SETRESGID) || defined(BROKEN_SETRESGID)
29 int
30 setresgid(gid_t rgid, gid_t egid, gid_t sgid)
31 {
32 	int ret = 0, saved_errno;
33 
34 	if (rgid != sgid) {
35 		errno = ENOSYS;
36 		return -1;
37 	}
38 #if defined(HAVE_SETREGID) && !defined(BROKEN_SETREGID)
39 	if (setregid(rgid, egid) < 0) {
40 		saved_errno = errno;
41 		error("setregid %u: %.100s", rgid, strerror(errno));
42 		errno = saved_errno;
43 		ret = -1;
44 	}
45 #else
46 	if (setegid(egid) < 0) {
47 		saved_errno = errno;
48 		error("setegid %u: %.100s", (u_int)egid, strerror(errno));
49 		errno = saved_errno;
50 		ret = -1;
51 	}
52 	if (setgid(rgid) < 0) {
53 		saved_errno = errno;
54 		error("setgid %u: %.100s", rgid, strerror(errno));
55 		errno = saved_errno;
56 		ret = -1;
57 	}
58 #endif
59 	return ret;
60 }
61 #endif
62 
63 #if !defined(HAVE_SETRESUID) || defined(BROKEN_SETRESUID)
64 int
65 setresuid(uid_t ruid, uid_t euid, uid_t suid)
66 {
67 	int ret = 0, saved_errno;
68 
69 	if (ruid != suid) {
70 		errno = ENOSYS;
71 		return -1;
72 	}
73 #if defined(HAVE_SETREUID) && !defined(BROKEN_SETREUID)
74 	if (setreuid(ruid, euid) < 0) {
75 		saved_errno = errno;
76 		error("setreuid %u: %.100s", ruid, strerror(errno));
77 		errno = saved_errno;
78 		ret = -1;
79 	}
80 #else
81 
82 # ifndef SETEUID_BREAKS_SETUID
83 	if (seteuid(euid) < 0) {
84 		saved_errno = errno;
85 		error("seteuid %u: %.100s", euid, strerror(errno));
86 		errno = saved_errno;
87 		ret = -1;
88 	}
89 # endif
90 	if (setuid(ruid) < 0) {
91 		saved_errno = errno;
92 		error("setuid %u: %.100s", ruid, strerror(errno));
93 		errno = saved_errno;
94 		ret = -1;
95 	}
96 #endif
97 	return ret;
98 }
99 #endif
100