2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Code for uid-swapping.
7 * As far as I am concerned, the code I have written for this software
8 * can be used freely for any purpose. Any derived versions of this
9 * software must be clearly marked as such, and if the derived work is
10 * incompatible with the protocol description in the RFC file, it must be
11 * called by a name other than "ssh" or "Secure Shell".
15 RCSID("$OpenBSD: uidswap.c,v 1.9 2000/09/07 20:27:55 deraadt Exp $");
21 * Note: all these functions must work in all of the following cases:
25 * Additionally, they must work regardless of whether the system has
26 * POSIX saved uids or not.
29 #ifdef _POSIX_SAVED_IDS
30 /* Lets assume that posix saved ids also work with seteuid, even though that
31 is not part of the posix specification. */
32 #define SAVED_IDS_WORK_WITH_SETEUID
34 /* Saved effective uid. */
35 static uid_t saved_euid = 0;
37 #endif /* _POSIX_SAVED_IDS */
40 * Temporarily changes to the given uid. If the effective user
41 * id is not root, this does nothing. This call cannot be nested.
44 temporarily_use_uid(uid_t uid)
46 #ifdef SAVED_IDS_WORK_WITH_SETEUID
47 /* Save the current euid. */
48 saved_euid = geteuid();
50 /* Set the effective uid to the given (unprivileged) uid. */
51 if (seteuid(uid) == -1)
52 debug("seteuid %u: %.100s", (u_int) uid, strerror(errno));
53 #else /* SAVED_IDS_WORK_WITH_SETUID */
54 /* Propagate the privileged uid to all of our uids. */
55 if (setuid(geteuid()) < 0)
56 debug("setuid %u: %.100s", (u_int) geteuid(), strerror(errno));
58 /* Set the effective uid to the given (unprivileged) uid. */
59 if (seteuid(uid) == -1)
60 debug("seteuid %u: %.100s", (u_int) uid, strerror(errno));
61 #endif /* SAVED_IDS_WORK_WITH_SETEUID */
65 * Restores to the original uid.
70 #ifdef SAVED_IDS_WORK_WITH_SETEUID
71 /* Set the effective uid back to the saved uid. */
72 if (seteuid(saved_euid) < 0)
73 debug("seteuid %u: %.100s", (u_int) saved_euid, strerror(errno));
74 #else /* SAVED_IDS_WORK_WITH_SETEUID */
76 * We are unable to restore the real uid to its unprivileged value.
77 * Propagate the real uid (usually more privileged) to effective uid
81 #endif /* SAVED_IDS_WORK_WITH_SETEUID */
85 * Permanently sets all uids to the given uid. This cannot be
86 * called while temporarily_use_uid is effective.
89 permanently_set_uid(uid_t uid)
92 debug("setuid %u: %.100s", (u_int) uid, strerror(errno));