5 Author: Tatu Ylonen <ylo@cs.hut.fi>
7 Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
10 Created: Sat Sep 9 01:56:14 1995 ylo
12 Code for uid-swapping.
22 /* Note: all these functions must work in all of the following cases:
28 Additionally, they must work regardless of whether the system has
29 POSIX saved uids or not. */
31 #ifdef _POSIX_SAVED_IDS
32 /* Lets assume that posix saved ids also work with seteuid, even though that
33 is not part of the posix specification. */
34 #define SAVED_IDS_WORK_WITH_SETEUID
35 #endif /* _POSIX_SAVED_IDS */
37 /* Saved effective uid. */
38 static uid_t saved_euid = 0;
40 /* Temporarily changes to the given uid. If the effective user id is not
41 root, this does nothing. This call cannot be nested. */
43 void temporarily_use_uid(uid_t uid)
45 #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 %d: %.100s", (int)uid, strerror(errno));
54 #else /* SAVED_IDS_WORK_WITH_SETUID */
56 /* Propagate the privileged uid to all of our uids. */
57 if (setuid(geteuid()) < 0)
58 debug("setuid %d: %.100s", (int)geteuid(), strerror(errno));
60 /* Set the effective uid to the given (unprivileged) uid. */
61 if (seteuid(uid) == -1)
62 debug("seteuid %d: %.100s", (int)uid, strerror(errno));
64 #endif /* SAVED_IDS_WORK_WITH_SETEUID */
68 /* Restores to the original uid. */
72 #ifdef SAVED_IDS_WORK_WITH_SETEUID
74 /* Set the effective uid back to the saved uid. */
75 if (seteuid(saved_euid) < 0)
76 debug("seteuid %d: %.100s", (int)saved_euid, strerror(errno));
78 #else /* SAVED_IDS_WORK_WITH_SETEUID */
80 /* We are unable to restore the real uid to its unprivileged value. */
81 /* Propagate the real uid (usually more privileged) to effective uid
85 #endif /* SAVED_IDS_WORK_WITH_SETEUID */
88 /* Permanently sets all uids to the given uid. This cannot be called while
89 temporarily_use_uid is effective. */
91 void permanently_set_uid(uid_t uid)
94 debug("setuid %d: %.100s", (int)uid, strerror(errno));