3 * $Id: become.c,v 1.23 2003/10/12 10:00:06 mdw Exp $
5 * Main code for `become'
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of `become'
14 * `Become' is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
19 * `Become' is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with `become'; if not, write to the Free Software Foundation,
26 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 /*----- Revision history --------------------------------------------------*
32 * Revision 1.23 2003/10/12 10:00:06 mdw
33 * Fix for daemon mode. Oops.
35 * Revision 1.22 2003/10/12 00:14:55 mdw
36 * Major overhaul. Now uses DSA signatures rather than the bogus symmetric
37 * encrypt-and-hope thing. Integrated with mLib and Catacomb.
39 * Revision 1.21 1999/07/28 09:31:01 mdw
40 * Empty path components are equivalent to `.'.
42 * Revision 1.20 1999/05/04 16:17:11 mdw
43 * Change to header file name for parser. See log for `parse.h' for
46 * Revision 1.19 1998/06/29 13:10:41 mdw
47 * Add some commentary regarding an issue in `sudo' which affects `become';
48 * I'm not fixing it yet because I don't think it's important.
50 * Fixed the PATH lookup code to use the right binary name: `binary' rather
51 * than `todo[0]'. The two only differ when `style' is `l_login', in which
52 * case `binary' has an initial `/' anyway, and the PATH lookup code is
53 * never invoked. The name is used in a buffer-overflow precheck, though,
54 * and auditing is easier if the naming is consistent.
56 * Revision 1.18 1998/06/26 10:32:54 mdw
57 * Cosmetic change: use sizeof(destination) in memcpy.
59 * Revision 1.17 1998/06/18 15:06:59 mdw
60 * Close log before execing program to avoid leaving a socket open.
62 * Revision 1.16 1998/04/23 13:21:04 mdw
63 * Small tweaks. Support no-network configuration option, and rearrange
64 * the help text a little.
66 * Revision 1.15 1998/01/13 11:10:44 mdw
67 * Add `TZ' to the list of variables to be preserved.
69 * Revision 1.14 1998/01/12 16:45:39 mdw
72 * Revision 1.13 1997/09/26 09:14:57 mdw
73 * Merged blowfish branch into trunk.
75 * Revision 1.12 1997/09/25 16:04:48 mdw
76 * Change directory after becoming someone else, instead of before. This
77 * avoids problems with root-squashed NFS mounts.
79 * Revision 1.11.2.1 1997/09/26 09:07:58 mdw
80 * Use the Blowfish encryption algorithm instead of IDEA. This is partly
81 * because I prefer Blowfish (without any particularly strong evidence) but
82 * mainly because IDEA is patented and Blowfish isn't.
84 * Revision 1.11 1997/09/24 09:48:45 mdw
85 * Fix (scary) overrun bug in group allocation stuff.
87 * Revision 1.10 1997/09/17 10:14:10 mdw
88 * Fix a typo. Support service names in `--port' option.
90 * Revision 1.9 1997/09/10 10:28:05 mdw
91 * Allow default port to be given as a service name or port number. Handle
92 * groups properly (lots of options here).
94 * Revision 1.8 1997/09/08 13:56:24 mdw
95 * Change criteria for expunging items from the user's PATH: instead of
96 * removing things starting with `.', remove things not starting with `/'.
98 * Revision 1.7 1997/09/08 13:43:20 mdw
99 * Change userid when creating tracefiles rather than fiddling with
100 * `access': it works rather better. Also, insert some stdio buffer
101 * flushing to ensure tracedumps are completely written.
103 * Revision 1.6 1997/09/05 13:47:44 mdw
104 * Make the `-L' (trace-level) option's argument optional, like the long
107 * Revision 1.5 1997/09/05 11:45:19 mdw
108 * Add support for different login styles, and environment variable
109 * manipulation in a safe and useful way.
111 * Revision 1.4 1997/08/20 16:15:13 mdw
112 * Overhaul of environment handling. Fix daft bug in path search code.
114 * Revision 1.3 1997/08/07 16:28:59 mdw
115 * Do something useful when users attempt to become themselves.
117 * Revision 1.2 1997/08/04 10:24:20 mdw
118 * Sources placed under CVS control.
120 * Revision 1.1 1997/07/21 13:47:54 mdw
125 /*----- Header files ------------------------------------------------------*/
127 /* --- ANSI headers --- */
137 /* --- Unix headers --- */
139 #include <sys/types.h>
140 #include <sys/stat.h>
141 #include <sys/socket.h>
142 #include <sys/utsname.h>
144 #include <netinet/in.h>
146 #include <arpa/inet.h>
154 extern char **environ;
158 #include <mLib/alloc.h>
159 #include <mLib/mdwopt.h>
160 #include <mLib/quis.h>
161 #include <mLib/report.h>
162 #include <mLib/sym.h>
163 #include <mLib/trace.h>
165 /* --- Local headers --- */
177 /*----- Type definitions --------------------------------------------------*/
179 /* --- Symbol table entry for an environment variable --- */
181 typedef struct sym_env {
182 sym_base _base; /* Symbol table information */
183 unsigned f; /* Flags word (see below) */
184 char *val; /* Pointer to variable value */
187 /* --- Environment variable flags --- */
193 /* --- Login behaviour types --- */
195 #define l_preserve 0 /* Preserve the environment */
196 #define l_setuser 1 /* Update who I am */
197 #define l_login 2 /* Do a full login */
199 /* --- Group behaviour types --- *
201 * Note that these make a handy bitfield.
204 #ifdef HAVE_SETGROUPS
207 g_unset = 0, /* Nobody's set a preference */
208 g_keep = 1, /* Leave the group memberships */
209 g_replace = 2, /* Replace group memberships */
210 g_merge = (g_keep | g_replace) /* Merge the group memberships */
215 /*----- Static variables --------------------------------------------------*/
217 static sym_table bc__env;
219 /*----- Main code ---------------------------------------------------------*/
221 /* --- @bc__write@ --- *
223 * Arguments: @FILE *fp@ = pointer to a stream to write on
224 * @const char *p@ = pointer to a string
228 * Use: Writes the string to the stream, substituting the program
229 * name (as returned by @quis@) for each occurrence of the
233 static void bc__write(FILE *fp, const char *p)
235 const char *n = quis();
237 size_t nl = strlen(n);
239 /* --- Try to be a little efficient --- *
241 * Gather up non-`$' characters using @strcspn@ and spew them out really
252 fwrite(n, nl, 1, fp);
257 /* --- @bc__setenv@ --- *
259 * Arguments: @sym_env *e@ = pointer to environment variable block
260 * @const char *val@ = value to set
264 * Use: Sets an environment variable block to the right value.
267 static void bc__setenv(sym_env *e, const char *val)
269 e->val = xmalloc(strlen(e->_base.name) + 1 + strlen(val) + 1);
270 sprintf(e->val, "%s=%s", e->_base.name, val);
273 /* --- @bc__putenv@ --- *
275 * Arguments: @const char *var@ = name of the variable to set, or 0 if
276 * this is embedded in the value string
277 * @const char *val@ = value to set, or 0 if the variable must
279 * @unsigned int fl@ = flags to set
280 * @unsigned int force@ = force overwrite of preserved variables
282 * Returns: Pointer to symbol block, or zero if it was deleted.
284 * Use: Puts an item into the environment.
287 static sym_env *bc__putenv(const char *var, const char *val,
288 unsigned int fl, unsigned int force)
295 /* --- Sort out embedded variable names --- */
298 const char *p = strchr(val, '=');
313 /* --- Find the variable block --- */
316 e = sym_find(&bc__env, var, -1, sizeof(*e), &f);
317 if (!f || ~e->f & envFlag_preserve || force) {
323 e = sym_find(&bc__env, var, -1, 0, 0);
324 if (e && (force || ~e->f & envFlag_preserve))
325 sym_remove(&bc__env, e);
329 /* --- Tidy up and return --- */
338 /* --- @bc__addGroups@ --- *
340 * Arguments: @gid_t *g@ = pointer to a group array
341 * @int *png@ = pointer to number of entries in the array
342 * @const gid_t *a@ = pointer to groups to add
343 * @int na@ = number of groups to add
345 * Returns: Zero if it was OK, nonzero if we should stop now.
347 * Use: Adds groups to a groups array.
350 static int bc__addGroups(gid_t *g, int *png, const gid_t *a, int na)
355 for (i = 0; i < na; i++) {
357 /* --- Ensure this group isn't already in the list --- */
359 for (j = 0; j < ng; j++) {
364 /* --- See if there's room for more --- */
366 if (ng >= NGROUPS_MAX) {
367 moan("too many groups (system limit exceeded) -- some have been lost");
372 /* --- Add the group --- */
382 /* --- @bc__banner@ --- *
384 * Arguments: @FILE *fp@ = stream to write on
388 * Use: Writes a banner containing copyright information.
391 static void bc__banner(FILE *fp)
393 bc__write(fp, "$ version " VERSION "\n");
396 /* --- @bc__usage@ --- *
398 * Arguments: @FILE *fp@ = stream to write on
402 * Use: Writes a terse reminder of command line syntax.
405 static void bc__usage(FILE *fp)
409 " $ -c <shell-command> <user>\n"
410 " $ [<env-var>] <user> [<command> [<arguments>]...]\n"
412 " $ -d [-p <port>] [-f <config-file>]\n"
417 /* --- @bc__help@ --- *
419 * Arguments: @FILE *fp@ = stream to write on
420 * @int suid@ = whether we're running set-uid
424 * Use: Displays a help message for this excellent piece of software.
427 static void bc__help(FILE *fp, int suid)
434 "The `$' program allows you to run a process as another user.\n"
435 "If a command name is given, this is the process executed. If the `-c'\n"
436 "option is used, the process is assumed to be `/bin/sh'. If no command is\n"
437 "given, your default login shell is used.\n"
439 "Your user id, the user id you wish to become, the name of the process\n"
440 "you wish to run, and the identity of the current host are looked up to\n"
441 "ensure that you have permission to do this.\n"
443 "Note that logs are kept of all uses of this program.\n"
445 "Options available are:\n"
447 "-h, --help Display this help text\n"
448 "-u, --usage Display a short usage summary\n"
449 "-v, --version Display $'s version number\n"
451 "-e, --preserve-environment Try to preserve the current environment\n"
452 "-s, --su, --set-user Set environment variables to reflect USER\n"
453 "-l, --login Really log in as USER\n"
455 #if DEFAULT_LOGIN_STYLE == l_preserve
456 "preserve-environment"
457 #elif DEFAULT_LOGIN_STYLE == l_setuser
459 #elif DEFAULT_LOGIN_STYLE == l_login
465 "-g GROUP, --group=GROUP Set primary group-id to be GROUP\n"
466 #ifdef HAVE_SETGROUPS
467 "-k, --keep-groups Keep your current set of groups\n"
468 "-m, --merge-groups Merge the lists of groups\n"
469 "-r, --replace-groups Replace the list of groups\n"
472 "-c CMD, --command=CMD Run the (Bourne) shell command CMD\n"
475 "-d, --daemon Start a daemon\n"
476 "-n, --nofork In daemon mode, don't fork into background\n"
477 "-p PORT, --port=PORT In daemon mode, listen on PORT\n"
478 "-f FILE, --config-file=FILE In daemon mode, read config from FILE\n"
485 "-I USER, --impersonate=USER Claim to be USER when asking the server\n");
488 "-T FILE, --trace=FILE Dump trace information to FILE (boring)\n"
489 "-L OPTS, --trace-level=OPTS Set level of tracing information\n");
495 * Arguments: @int argc@ = number of command line arguments
496 * @char *argv[]@ = pointer to the various arguments
498 * Returns: Zero if successful.
500 * Use: Allows a user to change UID.
503 int main(int argc, char *argv[])
505 /* --- Request block setup parameters --- */
507 request rq; /* Request buffer to build */
508 char *cmd = 0; /* Shell command to execute */
509 char *binary = "/bin/sh"; /* Default binary to execute */
510 char **env = environ; /* Default environment to pass */
511 char **todo = 0; /* Pointer to argument list */
512 char *who = 0; /* Who we're meant to become */
513 struct passwd *from_pw = 0; /* User we are right now */
514 struct passwd *to_pw = 0; /* User we want to become */
516 /* --- Become server setup parameters --- */
519 char *conffile = file_RULES; /* Default config file for daemon */
520 int port = 0; /* Default port for daemon */
523 /* --- Miscellanous shared variables --- */
525 unsigned flags = 0; /* Various useful flags */
526 int style = DEFAULT_LOGIN_STYLE; /* Login style */
527 gid_t group = -1; /* Default group to set */
528 int gstyle = g_unset; /* No group style set yet */
530 #ifdef HAVE_SETGROUPS
531 gid_t groups[NGROUPS_MAX]; /* Set of groups */
532 int ngroups; /* Number of groups in the set */
535 /* --- Default argument list executes a shell command --- */
537 static char *shell[] = {
538 "/bin/sh", /* Bourne shell */
539 "-c", /* Read from command line */
540 0, /* Pointer to shell command */
544 /* --- Definitions for the various flags --- */
546 #define f_daemon 1u /* Start up in daemon mode */
547 #define f_duff 2u /* Fault in arguments */
548 #define f_shell 4u /* Run a default shell */
549 #define f_dummy 8u /* Don't actually do anything */
550 #define f_setuid 16u /* We're running setuid */
551 #define f_havegroup 32u /* Set a default group */
552 #define f_nofork 64u /* Don't fork into background */
554 /* --- Set up the program name --- */
558 if (getuid() != geteuid())
561 /* --- Read the environment into a hashtable --- */
566 sym_create(&bc__env);
567 for (p = environ; *p; p++)
568 bc__putenv(0, *p, 0, 0);
571 /* --- Parse some command line arguments --- */
575 static struct option opts[] = {
577 /* --- Asking for help --- */
579 { "help", 0, 0, 'h' },
580 { "usage", 0, 0, 'u' },
581 { "version", 0, 0, 'v' },
583 /* --- Login style options --- */
585 { "preserve-environment", 0, 0, 'e' },
587 { "set-user", 0, 0, 's' },
588 { "login", 0, 0, 'l' },
590 /* --- Group style options --- */
592 { "group", gFlag_argReq, 0, 'g' },
593 #ifdef HAVE_SETGROUPS
594 { "keep-groups", 0, 0, 'k' },
595 { "merge-groups", 0, 0, 'm' },
596 { "replace-groups", 0, 0, 'r' },
599 /* --- Command to run options --- */
601 { "command", gFlag_argReq, 0, 'c' },
603 /* --- Server options --- */
606 { "daemon", 0, 0, 'd' },
607 { "nofork", 0, 0, 'n' },
608 { "port", gFlag_argReq, 0, 'p' },
609 { "config-file", gFlag_argReq, 0, 'f' },
612 /* --- Tracing options --- */
615 { "impersonate", gFlag_argReq, 0, 'I' },
616 { "trace", gFlag_argOpt, 0, 'T' },
617 { "trace-level", gFlag_argOpt, 0, 'L' },
623 i = mdwopt(argc, argv,
624 "-" /* Return non-options as options */
625 "huv" /* Asking for help */
626 "esl" /* Login style options */
627 #ifdef HAVE_SETGROUPS
628 "g:kmr" /* Group style options */
630 "g:" /* Group (without @setgroups@) */
632 "c:" /* Command to run options */
634 "dnp:f:" /* Server options */
637 "I:T::L::" /* Tracing options */
640 opts, 0, 0, gFlag_envVar);
646 /* --- Asking for help --- */
649 bc__help(stdout, flags & f_setuid);
661 /* --- Login style options --- */
673 /* --- Group style options --- */
676 if (isdigit((unsigned char)optarg[0]))
677 group = atoi(optarg);
679 struct group *gr = getgrnam(optarg);
681 die(1, "unknown group `%s'", optarg);
684 flags |= f_havegroup;
697 /* --- Command to run options --- */
703 /* --- Server options --- */
707 if (isdigit((unsigned char)optarg[0]))
708 port = htons(atoi(optarg));
710 struct servent *s = getservbyname(optarg, "udp");
712 die(1, "unknown service name `%s'", optarg);
727 /* --- Pretend to be a different user --- *
729 * There are all sorts of nasty implications for this option. Don't
730 * allow it if we're running setuid. Disable the actual login anyway.
736 if (flags & f_setuid)
737 moan("shan't allow impersonation while running setuid");
740 if (isdigit((unsigned char)optarg[0]))
741 pw = getpwuid(atoi(optarg));
743 pw = getpwnam(optarg);
745 die(1, "can't impersonate unknown user `%s'", optarg);
746 from_pw = userdb_copyUser(pw);
747 rq.from = from_pw->pw_uid;
754 /* --- Tracing support --- *
756 * Be careful not to zap a file I wouldn't normally be allowed to write
765 if (optarg == 0 || strcmp(optarg, "-") == 0)
768 uid_t eu = geteuid(), ru = getuid();
771 if (setreuid(eu, ru))
776 die(1, "couldn't temporarily give up privileges: %s",
780 if ((fp = fopen(optarg, "w")) == 0) {
781 die(1, "couldn't open trace file `%s' for writing: %s",
782 optarg, strerror(errno));
786 if (setreuid(ru, eu))
790 die(1, "couldn't regain privileges: %s", strerror(errno));
792 trace_on(fp, TRACE_DFL);
793 trace(TRACE_MISC, "become: tracing enabled");
798 /* --- Setting trace levels --- */
804 /* --- Table of tracing facilities --- */
806 static trace_opt lvltbl[] = {
807 { 'm', TRACE_MISC, "miscellaneous messages" },
808 { 's', TRACE_SETUP, "building the request block" },
809 { 'r', TRACE_RULE, "ruleset scanning" },
810 { 'c', TRACE_CHECK, "request checking" },
812 { 'd', TRACE_DAEMON, "server process" },
813 { 'l', TRACE_CLIENT, "client process" },
814 { 'R', TRACE_RAND, "random number generator" },
815 { 'C', TRACE_CRYPTO, "cryptographic processing of requests" },
817 { 'y', TRACE_YACC, "parsing configuration file" },
818 { 'D', TRACE_DFL, "default tracing options" },
819 { 'A', TRACE_ALL, "all tracing options" },
823 /* --- Output some help if there's no arguemnt --- */
825 trace_level(traceopt(lvltbl, optarg, TRACE_DFL,
826 (flags & f_setuid) ? TRACE_PRIV : 0));
831 /* --- Something that wasn't an option --- *
833 * The following nasties are supported:
835 * * NAME=VALUE -- preserve NAME, and give it a VALUE
836 * * NAME= -- preserve NAME, and give it an empty value
837 * * NAME- -- delete NAME
838 * * NAME! -- preserve NAME with existing value
840 * Anything else is either the user name (which is OK) or the start of
841 * the command (in which case I stop and read the rest of the command).
845 size_t sz = strcspn(optarg, "=-!");
848 /* --- None of the above --- */
850 if (optarg[sz] == 0 || (optarg[sz] != '=' && optarg[sz + 1] != 0)) {
860 /* --- Do the appropriate thing --- */
862 switch (optarg[sz]) {
864 bc__putenv(0, optarg, envFlag_preserve, 1);
868 bc__putenv(optarg, 0, 0, 1);
872 if ((e = sym_find(&bc__env, optarg, -1, 0, 0)) != 0)
873 e->f |= envFlag_preserve;
878 /* --- Something I didn't understand has occurred --- */
887 if (flags & f_duff) {
892 /* --- Switch to daemon mode if requested --- */
895 if (flags & f_daemon) {
896 T( trace(TRACE_MISC, "become: daemon mode requested"); )
897 daemon_init(conffile, port, (flags & f_nofork) ? df_nofork : 0);
902 /* --- Open a syslog --- */
904 openlog(quis(), 0, LOG_AUTH);
906 /* --- Pick out the uid --- */
916 if (isdigit((unsigned char)who[0]))
917 pw = getpwuid(atoi(who));
921 die(1, "unknown user `%s'", who);
922 to_pw = userdb_copyUser(pw);
926 /* --- Fill in the easy bits of the request --- */
932 pw = getpwuid(rq.from);
934 die(1, "who are you? (can't find user %li)", (long)rq.from);
935 from_pw = userdb_copyUser(pw);
938 /* --- Find the local host address --- */
944 if ((he = gethostbyname(u.nodename)) == 0)
945 die(1, "who am I? (can't resolve `%s')", u.nodename);
946 memcpy(&rq.host, he->h_addr, sizeof(rq.host));
949 /* --- Fiddle with group ownerships a bit --- */
952 #ifdef HAVE_SETGROUPS
953 gid_t from_gr[NGROUPS_MAX], to_gr[NGROUPS_MAX];
957 /* --- Set the default login group, if there is one --- */
959 if (~flags & f_havegroup)
960 group = (style == l_preserve) ? from_pw->pw_gid : to_pw->pw_gid;
962 #ifndef HAVE_SETGROUPS
964 /* --- Check that it's valid --- */
966 if (group != from_pw->pw_gid && group != to_pw->pw_gid)
967 die(1, "invalid default group");
971 /* --- Set the default group style --- */
973 if (gstyle == g_unset)
974 gstyle = (style == l_login) ? g_replace : g_merge;
976 /* --- Read in my current set of groups --- */
978 n_fgr = getgroups(NGROUPS_MAX, from_gr);
980 /* --- Now read the groups for the target user --- *
982 * Do this even if I'm using the @g_keep@ style -- I'll use it for
983 * checking that @group@ is valid.
991 to_gr[n_tgr++] = to_pw->pw_gid;
994 while ((gr = getgrent()) != 0) {
995 if (gr->gr_gid == to_gr[0])
997 for (p = gr->gr_mem; *p; p++) {
998 if (strcmp(to_pw->pw_name, *p) == 0) {
999 to_gr[n_tgr++] = gr->gr_gid;
1000 if (n_tgr >= NGROUPS_MAX)
1011 /* --- Check that @group@ is reasonable --- */
1016 if (group == getgid() || group == from_pw->pw_gid)
1018 for (i = 0; i < n_fgr; i++) {
1019 if (group == from_gr[i])
1022 for (i = 0; i < n_tgr; i++) {
1023 if (group == to_gr[i])
1026 die(1, "invalid default group");
1030 /* --- Phew. Now comes the hard bit --- */
1038 if (gstyle & g_keep) {
1040 ga[i++] = from_pw->pw_gid;
1042 if (gstyle & g_replace)
1043 ga[i++] = to_pw->pw_gid;
1045 /* --- Style authorities will become apoplectic if shown this --- *
1047 * As far as I can see, it's the neatest way of writing it.
1051 (void)(bc__addGroups(groups, &ngroups, ga, i) ||
1052 ((gstyle & g_keep) &&
1053 bc__addGroups(groups, &ngroups, from_gr, n_fgr)) ||
1054 ((gstyle & g_replace) &&
1055 bc__addGroups(groups, &ngroups, to_gr, n_tgr)));
1060 /* --- Trace the results of all this --- */
1062 T( trace(TRACE_SETUP, "setup: default group == %i", (int)group); )
1064 #ifdef HAVE_SETGROUPS
1065 IF_TRACING(TRACE_SETUP, {
1068 for (i = 1; i < ngroups; i++)
1069 trace(TRACE_SETUP, "setup: subsidiary group %i", (int)groups[i]);
1074 /* --- Shell commands are easy --- */
1081 /* --- A command given on the command line isn't too hard --- */
1083 else if (optind < argc) {
1084 todo = argv + optind;
1093 /* --- An unadorned becoming requires little work --- */
1096 shell[0] = getenv("SHELL");
1098 shell[0] = from_pw->pw_shell;
1104 /* --- An su-like login needs slightly less effort --- */
1107 shell[0] = to_pw->pw_shell;
1113 /* --- A login request needs a little bit of work --- */
1116 const char *p = strrchr(to_pw->pw_shell, '/');
1121 p = to_pw->pw_shell;
1122 shell[0] = xmalloc(strlen(p) + 2);
1124 strcpy(shell[0] + 1, p);
1127 binary = to_pw->pw_shell;
1132 /* --- Mangle the environment --- *
1134 * This keeps getting more complicated all the time. (How true. Now I've
1135 * got all sorts of nasty environment mangling to do.)
1137 * The environment stuff now happens in seven phases:
1139 * 1. Mark very special variables to be preserved. Currently only TERM
1140 * and DISPLAY are treated in this way.
1142 * 2. Set and preserve Become's own environment variables.
1144 * 3. Set and preserve the user identity variables (USER, LOGNAME, HOME,
1145 * SHELL and MAIL) if we're being `su'-like or `login'-like.
1147 * 4. If we're preserving the environment or being `su'-like, process the
1148 * PATH variable a little. Otherwise reset it to something
1151 * 5. If we're being `login'-like, expunge all unpreserved variables.
1153 * 6. Expunge any security-critical variables.
1155 * 7. Build a new environment table to pass to child processes.
1159 /* --- Variables to be preserved always --- *
1161 * A user can explicitly expunge a variable in this list, in which case
1162 * we never get to see it here.
1165 static char *preserve[] = {
1166 "TERM", "DISPLAY", "TZ", 0
1169 /* --- Variables to be expunged --- *
1171 * Any environment string which has one of the following as a prefix will
1172 * be expunged from the environment passed to the called process. The
1173 * first line lists variables which have been used to list search paths
1174 * for shared libraries: by manipulating these, an attacker could replace
1175 * a standard library with one of his own. The second line lists other
1176 * well-known dangerous environment variables.
1179 static char *banned[] = {
1180 "-LD_", "SHLIB_PATH", "LIBPATH", "-_RLD_",
1181 "IFS", "ENV", "BASH_ENV", "KRB_CONF",
1185 /* --- Other useful variables --- */
1194 /* --- Stage one. Preserve display-specific variables --- */
1196 for (pp = preserve; *pp; pp++) {
1197 if ((e = sym_find(&bc__env, *pp, -1, 0, 0)) != 0)
1198 e->f |= envFlag_preserve;
1201 /* --- Stage two. Set Become's own variables --- */
1203 e = sym_find(&bc__env, "BECOME_ORIGINAL_USER", -1, sizeof(*e), &f);
1205 bc__setenv(e, from_pw->pw_name);
1206 e->f |= envFlag_preserve;
1208 e = sym_find(&bc__env, "BECOME_ORIGINAL_HOME", -1, sizeof(*e), &f);
1210 bc__setenv(e, from_pw->pw_dir);
1211 e->f |= envFlag_preserve;
1213 bc__putenv("BECOME_OLD_USER", from_pw->pw_name, envFlag_preserve, 0);
1214 bc__putenv("BECOME_OLD_HOME", from_pw->pw_dir, envFlag_preserve, 0);
1215 bc__putenv("BECOME_USER", to_pw->pw_name, envFlag_preserve, 0);
1216 bc__putenv("BECOME_HOME", to_pw->pw_dir, envFlag_preserve, 0);
1218 /* --- Stage three. Set user identity --- */
1222 static char *maildirs[] = {
1223 "/var/spool/mail", "/var/mail",
1224 "/usr/spool/mail", "/usr/mail",
1230 for (pp = maildirs; *pp; pp++) {
1231 if (stat(*pp, &s) == 0 && S_ISDIR(s.st_mode)) {
1232 sprintf(b, "%s/%s", *pp, to_pw->pw_name);
1233 bc__putenv("MAIL", b, envFlag_preserve, 0);
1237 } /* Fall through */
1240 bc__putenv("USER", to_pw->pw_name, envFlag_preserve, 0);
1241 bc__putenv("LOGNAME", to_pw->pw_name, envFlag_preserve, 0);
1242 bc__putenv("HOME", to_pw->pw_dir, envFlag_preserve, 0);
1243 bc__putenv("SHELL", to_pw->pw_shell, envFlag_preserve, 0);
1247 /* --- Stage four. Set the user's PATH properly --- */
1250 /* --- Find an existing path --- *
1252 * If there's no path, or this is a login, then set a default path,
1253 * unless we're meant to preserve the existing one. Whew!
1256 e = sym_find(&bc__env, "PATH", -1, sizeof(*e), &f);
1258 if (!f || (style == l_login && ~e->f & envFlag_preserve)) {
1260 rq.to ? "/usr/bin:/bin" : "/usr/bin:/usr/sbin:/bin:/sbin",
1261 envFlag_preserve, 0);
1264 /* --- Find the string --- */
1266 e->f = envFlag_preserve;
1267 p = strchr(e->val, '=') + 1;
1270 /* --- Write the new version to a dynamically allocated buffer --- */
1272 e->val = xmalloc(4 + 1 + strlen(p) + 1);
1273 strcpy(e->val, "PATH=");
1276 for (p = strtok(p, ":"); p; p = strtok(0, ":")) {
1291 /* --- Stages five and six. Expunge variables and count numbers --- *
1293 * Folded together, so I only need one pass through the table. Also
1294 * count the number of variables needed at this time.
1299 for (sym_mkiter(&i, &bc__env); (e = sym_next(&i)) != 0; ) {
1301 /* --- Login style expunges all unpreserved variables --- */
1303 if (style == l_login && ~e->f & envFlag_preserve)
1306 /* --- Otherwise just check the name against the list --- */
1308 for (pp = banned; *pp; pp++) {
1311 if (memcmp(e->_base.name, p, strlen(p)) == 0)
1313 } else if (strcmp(e->_base.name, *pp) == 0)
1321 sym_remove(&bc__env, e);
1324 /* --- Stage seven. Build the new environment block --- */
1326 env = qq = xmalloc((sz + 1) * sizeof(*qq));
1328 for (sym_mkiter(&i, &bc__env); (e = sym_next(&i)) != 0; )
1333 /* --- Trace the command --- */
1335 IF_TRACING(TRACE_SETUP, {
1338 trace(TRACE_SETUP, "setup: from user %s to user %s",
1339 from_pw->pw_name, to_pw->pw_name);
1340 trace(TRACE_SETUP, "setup: binary == `%s'", binary);
1341 for (i = 0; todo[i]; i++)
1342 trace(TRACE_SETUP, "setup: arg %i == `%s'", i, todo[i]);
1343 for (i = 0; env[i]; i++)
1344 trace(TRACE_SETUP, "setup: env %i == `%s'", i, env[i]);
1347 /* --- If necessary, resolve the path to the command --- */
1349 if (!strchr(binary, '/')) {
1353 if ((p = getenv("PATH")) == 0)
1354 p = "/bin:/usr/bin";
1357 for (p = strtok(path, ":"); p; p = strtok(0, ":")) {
1359 /* --- Check length of string before copying --- */
1361 if (strlen(p) + strlen(binary) + 2 > sizeof(rq.cmd))
1364 /* --- Now build the pathname and check it --- *
1366 * Issue: user can take advantage of these privileges to decide whether
1367 * a program with a given name exists. I'm not sure that's
1368 * particularly significant: it only works on regular files with
1369 * execute permissions, and if you're relying on the names of these
1370 * being secret to keep your security up, then you're doing something
1371 * deeply wrong anyway. On the other hand, it's useful to allow people
1372 * to be able to execute programs and scripts which they wouldn't
1373 * otherwise have access to. [This problem was brought up on
1374 * Bugtraq, as a complaint against sudo.]
1378 sprintf(rq.cmd, "%s/%s", p, binary);
1379 if (stat(rq.cmd, &st) == 0 && /* Check it exists */
1380 st.st_mode & 0111 && /* Check it's executable */
1381 S_ISREG(st.st_mode)) /* Check it's a file */
1386 die(1, "couldn't find `%s' in path", todo[0]);
1390 T( trace(TRACE_SETUP, "setup: resolve binary to `%s'", binary); )
1392 /* --- Canonicalise the path string, if necessary --- */
1399 /* --- Insert current directory name if path not absolute --- */
1404 if (!getcwd(b, sizeof(b)))
1405 die(1, "couldn't read current directory: %s", strerror(errno));
1410 /* --- Now copy over characters from the path string --- */
1414 /* --- Check for buffer overflows here --- *
1416 * I write at most one byte per iteration so this is OK. Remember to
1417 * allow one for the null byte.
1420 if (p >= b + sizeof(b) - 1)
1421 die(1, "internal error: buffer overflow while canonifying path");
1423 /* --- Reduce multiple slashes to just one --- */
1431 /* --- Handle dots in filenames --- *
1433 * @p[-1]@ is valid here, because if @*q@ is not a `/' then either
1434 * we've just stuck the current directory on the end of the buffer,
1435 * or we've just put something else on the end.
1438 else if (*q == '.' && p[-1] == '/') {
1440 /* --- A simple `./' just gets removed --- */
1442 if (q[1] == 0 || q[1] == '/') {
1448 /* --- A `../' needs to be peeled back to the previous `/' --- */
1450 if (q[1] == '.' && (q[2] == 0 || q[2] == '/')) {
1453 while (p > b && p[-1] != '/')
1466 T( trace(TRACE_SETUP, "setup: canonify binary to `%s'", rq.cmd); )
1468 /* --- Run the check --- *
1470 * If the user is already what she wants to be, then print a warning.
1471 * Then, if I was just going to spawn a shell, quit, to reduce user
1472 * confusion. Otherwise, do what was wanted anyway. Also, don't bother
1473 * checking if we're already root -- root can do anything anyway, and at
1474 * least this way we get some logging done, and offer a more friendly
1478 if (rq.from == rq.to) {
1479 moan("you already are `%s'!", to_pw->pw_name);
1480 if (flags & f_shell) {
1481 moan("(to prevent confusion, I'm not spawning a shell)");
1485 int a = (rq.from == 0) || check(&rq);
1488 "permission %s for %s to become %s to run `%s'",
1489 a ? "granted" : "denied", from_pw->pw_name, to_pw->pw_name,
1493 die(1, "permission denied");
1496 /* --- Now do the job --- */
1498 T( trace(TRACE_MISC, "become: permission granted"); )
1500 if (flags & f_dummy) {
1501 puts("permission granted");
1505 #ifdef HAVE_SETGROUPS
1506 if (setgroups(ngroups, groups) < 0)
1507 die(1, "couldn't set groups: %s", strerror(errno));
1510 if (setgid(group) < 0)
1511 die(1, "couldn't set default group: %s", strerror(errno));
1512 if (setuid(rq.to) < 0)
1513 die(1, "couldn't set uid: %s", strerror(errno));
1515 /* --- If this was a login, change current directory --- */
1517 if ((flags & f_shell) &&
1519 chdir(to_pw->pw_dir) < 0) {
1520 moan("couldn't change directory to `%s': %s",
1521 to_pw->pw_dir, strerror(errno));
1524 /* --- Finally, call the program --- */
1528 execve(rq.cmd, todo, env);
1529 die(1, "couldn't exec `%s': %s", rq.cmd, strerror(errno));
1533 /*----- That's all, folks -------------------------------------------------*/