3 * $Id: become.c,v 1.5 1997/09/05 11:45:19 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.5 1997/09/05 11:45:19 mdw
33 * Add support for different login styles, and environment variable
34 * manipulation in a safe and useful way.
36 * Revision 1.4 1997/08/20 16:15:13 mdw
37 * Overhaul of environment handling. Fix daft bug in path search code.
39 * Revision 1.3 1997/08/07 16:28:59 mdw
40 * Do something useful when users attempt to become themselves.
42 * Revision 1.2 1997/08/04 10:24:20 mdw
43 * Sources placed under CVS control.
45 * Revision 1.1 1997/07/21 13:47:54 mdw
50 /*----- Header files ------------------------------------------------------*/
52 /* --- ANSI headers --- */
61 /* --- Unix headers --- */
63 #include <sys/types.h>
65 #include <sys/socket.h>
66 #include <sys/utsname.h>
68 #include <netinet/in.h>
70 #include <arpa/inet.h>
77 extern char **environ;
79 /* --- Local headers --- */
94 /*----- Type definitions --------------------------------------------------*/
96 /* --- Symbol table entry for an environment variable --- */
98 typedef struct sym_env {
99 sym_base _base; /* Symbol table information */
100 unsigned f; /* Flags word (see below) */
101 char *val; /* Pointer to variable value */
104 /* --- Environment variable flags --- */
110 /* --- Login behaviour types --- */
113 l_preserve, /* Preserve the environment */
114 l_user, /* Update who I am */
115 l_login /* Do a full login */
118 /*----- Static variables --------------------------------------------------*/
120 static sym_table bc__env;
122 /*----- Main code ---------------------------------------------------------*/
124 /* --- @bc__write@ --- *
126 * Arguments: @FILE *fp@ = pointer to a stream to write on
127 * @const char *p@ = pointer to a string
131 * Use: Writes the string to the stream, substituting the program
132 * name (as returned by @quis@) for each occurrence of the
136 static void bc__write(FILE *fp, const char *p)
138 const char *n = quis();
140 size_t nl = strlen(n);
142 /* --- Try to be a little efficient --- *
144 * Gather up non-`$' characters using @strcspn@ and spew them out really
155 fwrite(n, nl, 1, fp);
160 /* --- @bc__setenv@ --- *
162 * Arguments: @sym_env *e@ = pointer to environment variable block
163 * @const char *val@ = value to set
167 * Use: Sets an environment variable block to the right value.
170 static void bc__setenv(sym_env *e, const char *val)
172 e->val = xmalloc(strlen(e->_base.name) + 1 + strlen(val) + 1);
173 sprintf(e->val, "%s=%s", e->_base.name, val);
176 /* --- @bc__putenv@ --- *
178 * Arguments: @const char *var@ = name of the variable to set, or 0 if
179 * this is embedded in the value string
180 * @const char *val@ = value to set, or 0 if the variable must
182 * @unsigned int fl@ = flags to set
183 * @unsigned int force@ = force overwrite of preserved variables
185 * Returns: Pointer to symbol block, or zero if it was deleted.
187 * Use: Puts an item into the environment.
190 static sym_env *bc__putenv(const char *var, const char *val,
191 unsigned int fl, unsigned int force)
198 /* --- Sort out embedded variable names --- */
201 const char *p = strchr(val, '=');
216 /* --- Find the variable block --- */
219 e = sym_find(&bc__env, var, -1, sizeof(*e), &f);
220 if (~e->f & envFlag_preserve || force) {
226 e = sym_find(&bc__env, var, -1, 0, 0);
227 if (e && (force || ~e->f & envFlag_preserve))
228 sym_remove(&bc__env, e);
232 /* --- Tidy up and return --- */
241 /* --- @bc__banner@ --- *
243 * Arguments: @FILE *fp@ = stream to write on
247 * Use: Writes a banner containing copyright information.
250 static void bc__banner(FILE *fp)
252 bc__write(fp, "$ version " VERSION "\n");
255 /* --- @bc__usage@ --- *
257 * Arguments: @FILE *fp@ = stream to write on
261 * Use: Writes a terse reminder of command line syntax.
264 static void bc__usage(FILE *fp)
268 " $ -c <shell-command> <user>\n"
269 " $ [<env-var>] <user> [<command> [<arguments>]...]\n"
270 " $ -d [-p <port>] [-f <config-file>]\n");
273 /* --- @bc__help@ --- *
275 * Arguments: @FILE *fp@ = stream to write on
276 * @int suid@ = whether we're running set-uid
280 * Use: Displays a help message for this excellent piece of software.
283 static void bc__help(FILE *fp, int suid)
290 "The `$' program allows you to run a process as another user.\n"
291 "If a command name is given, this is the process executed. If the `-c'\n"
292 "option is used, the process is assumed to be `/bin/sh'. If no command is\n"
293 "given, your default login shell is used.\n"
295 "Your user id, the user id you wish to become, the name of the process\n"
296 "you wish to run, and the identity of the current host are looked up to\n"
297 "ensure that you have permission to do this.\n"
299 "Note that logs are kept of all uses of this program.\n"
301 "Options available are:\n"
303 "-h, --help Display this help text\n"
304 "-u, --usage Display a short usage summary\n"
305 "-v, --version Display $'s version number\n"
307 "-e, --preserve-environment Try to preserve the current environment\n"
308 "-s, --su, --set-user Set environment variables to reflect USER\n"
309 "-l, --login Really log in as USER\n"
311 "-c CMD, --command=CMD Run the (Bourne) shell command CMD\n"
313 "-d, --daemon Start a daemon\n"
314 "-p PORT, --port=PORT In daemon mode, listen on PORT\n"
315 "-f FILE, --config-file=FILE In daemon mode, read config from FILE\n");
320 "-I USER, --impersonate=USER Claim to be USER when asking the server\n");
323 "-T FILE, --trace=FILE Dump trace information to FILE (boring)\n"
324 "-L OPTS, --trace-level=OPTS Set level of tracing information\n");
330 * Arguments: @int argc@ = number of command line arguments
331 * @char *argv[]@ = pointer to the various arguments
333 * Returns: Zero if successful.
335 * Use: Allows a user to change UID.
338 int main(int argc, char *argv[])
340 /* --- Request block setup parameters --- */
342 request rq; /* Request buffer to build */
343 char *cmd = 0; /* Shell command to execute */
344 char *binary = "/bin/sh"; /* Default binary to execute */
345 char **env = environ; /* Default environment to pass */
346 char **todo = 0; /* Pointer to argument list */
347 char *who = 0; /* Who we're meant to become */
348 struct passwd *from_pw = 0; /* User we are right now */
349 struct passwd *to_pw = 0; /* User we want to become */
351 /* --- Become server setup parameters --- */
353 char *conffile = file_RULES; /* Default config file for daemon */
354 int port = -1; /* Default port for daemon */
356 /* --- Miscellanous shared variables --- */
358 unsigned flags = 0; /* Various useful flags */
359 int style = DEFAULT_LOGIN_STYLE; /* Login style */
361 /* --- Default argument list executes a shell command --- */
363 static char *shell[] = {
364 "/bin/sh", /* Bourne shell */
365 "-c", /* Read from command line */
366 0, /* Pointer to shell command */
370 /* --- Definitions for the various flags --- */
373 f_daemon = 1, /* Start up in daemon mode */
374 f_duff = 2, /* Fault in arguments */
375 f_login = 4, /* Execute as a login shell */
376 f_dummy = 8, /* Don't actually do anything */
377 f_setuid = 16 /* We're running setuid */
380 /* --- Set up the program name --- */
384 if (getuid() != geteuid())
387 /* --- Read the environment into a hashtable --- */
392 sym_createTable(&bc__env);
393 for (p = environ; *p; p++)
394 bc__putenv(0, *p, 0, 0);
397 /* --- Parse some command line arguments --- */
401 static struct option opts[] = {
403 /* --- Asking for help --- */
405 { "help", 0, 0, 'h' },
406 { "usage", 0, 0, 'u' },
407 { "version", 0, 0, 'v' },
409 /* --- Login style options --- */
411 { "preserve-environment", 0, 0, 'e' },
413 { "set-user", 0, 0, 's' },
414 { "login", 0, 0, 'l' },
416 /* --- Command to run options --- */
418 { "command", gFlag_argReq, 0, 'c' },
420 /* --- Server options --- */
422 { "daemon", 0, 0, 'd' },
423 { "port", gFlag_argReq, 0, 'p' },
424 { "config-file", gFlag_argReq, 0, 'f' },
426 /* --- Tracing options --- */
429 { "impersonate", gFlag_argReq, 0, 'I' },
430 { "trace", gFlag_argOpt, 0, 'T' },
431 { "trace-level", gFlag_argOpt, 0, 'L' },
437 i = mdwopt(argc, argv,
438 "-" "huv" "esl" "c:" "dp:f:" T("I:T::L:"),
439 opts, 0, 0, gFlag_envVar);
445 /* --- Asking for help --- */
448 bc__help(stdout, flags & f_setuid);
460 /* --- Login style options --- */
472 /* --- Command to run options --- */
478 /* --- Server options --- */
490 /* --- Pretend to be a different user --- *
492 * There are all sorts of nasty implications for this option. Don't
493 * allow it if we're running setuid. Disable the actual login anyway.
499 if (flags & f_setuid)
500 moan("shan't allow impersonation while running setuid");
503 if (isdigit((unsigned char)optarg[0]))
504 pw = getpwuid(atoi(optarg));
506 pw = getpwnam(optarg);
508 die("can't impersonate unknown user `%s'", optarg);
509 from_pw = userdb_copyUser(pw);
510 rq.from = from_pw->pw_uid;
517 /* --- Tracing support --- *
519 * Be careful not to zap a file I wouldn't normally be allowed to write
528 if (optarg == 0 || strcmp(optarg, "-") == 0)
531 if ((flags & f_setuid) && access(optarg, W_OK)) {
532 die("no write permission for trace file file `%s': %s",
533 optarg, strerror(errno));
535 if ((fp = fopen(optarg, "w")) == 0) {
536 die("couldn't open trace file `%s' for writing: %s",
537 optarg, strerror(errno));
540 traceon(fp, TRACE_DFL);
541 trace(TRACE_MISC, "become: tracing enabled");
546 /* --- Setting trace levels --- */
552 unsigned int lvl = 0, l;
553 const char *p = optarg;
555 /* --- Table of tracing facilities --- */
563 static tr lvltbl[] = {
564 { 'm', TRACE_MISC, "miscellaneous messages" },
565 { 's', TRACE_SETUP, "building the request block" },
566 { 'd', TRACE_DAEMON, "server process" },
567 { 'r', TRACE_RULE, "ruleset scanning" },
568 { 'c', TRACE_CHECK, "request checking" },
569 { 'l', TRACE_CLIENT, "client process" },
570 { 'R', TRACE_RAND, "random number generator" },
571 { 'C', TRACE_CRYPTO, "cryptographic processing of requests" },
572 { 'y', TRACE_YACC, "parsing configuration file" },
573 { 'D', TRACE_DFL, "default tracing options" },
574 { 'A', TRACE_ALL, "all tracing options" },
579 /* --- Output some help if there's no arguemnt --- */
587 for (tp = lvltbl; tp->l; tp++) {
588 if ((flags & f_setuid) == 0 || tp->l & ~TRACE_PRIV)
589 printf("%c -- %s\n", tp->ch, tp->help);
593 "Also, `+' and `-' options are recognised to turn on and off vavrious\n"
594 "tracing options. For example, `A-r' enables everything except ruleset\n"
595 "tracing, and `A-D+c' is everything except the defaults, but with request\n"
607 for (tp = lvltbl; tp->l && *p != tp->ch; tp++)
610 if (flags & f_setuid)
613 lvl = sense ? (lvl | l) : (lvl & ~l);
615 moan("unknown trace option `%c'", *p);
621 yydebug = ((lvl & TRACE_YACC) != 0);
626 /* --- Something that wasn't an option --- *
628 * The following nasties are supported:
630 * * NAME=VALUE -- preserve NAME, and give it a VALUE
631 * * NAME= -- preserve NAME, and give it an empty value
632 * * NAME- -- delete NAME
633 * * NAME! -- preserve NAME with existing value
635 * Anything else is either the user name (which is OK) or the start of
636 * the command (in which case I stop and read the rest of the command).
640 size_t sz = strcspn(optarg, "=-!");
643 /* --- None of the above --- */
645 if (optarg[sz] == 0 || (optarg[sz] != '=' && optarg[sz + 1] != 0)) {
654 /* --- Do the appropriate thing --- */
656 switch (optarg[sz]) {
658 bc__putenv(0, optarg, envFlag_preserve, 1);
662 bc__putenv(optarg, 0, 0, 1);
666 if ((e = sym_find(&bc__env, optarg, -1, 0, 0)) != 0)
667 e->f |= envFlag_preserve;
672 /* --- Something I didn't understand has occurred --- */
681 if (flags & f_duff) {
686 /* --- Switch to daemon mode if requested --- */
688 if (flags & f_daemon) {
689 T( trace(TRACE_MISC, "become: daemon mode requested"); )
690 daemon_init(conffile, port);
694 /* --- Open a syslog --- */
696 openlog(quis(), 0, LOG_AUTH);
698 /* --- Pick out the uid --- */
708 if (isdigit((unsigned char)who[0]))
709 pw = getpwuid(atoi(who));
713 die("unknown user `%s'", who);
714 to_pw = userdb_copyUser(pw);
718 /* --- Fill in the easy bits of the request --- */
724 pw = getpwuid(rq.from);
726 die("who are you? (can't find user %li)", (long)rq.from);
727 from_pw = userdb_copyUser(pw);
730 /* --- Find the local host address --- */
736 if ((he = gethostbyname(u.nodename)) == 0)
737 die("who am I? (can't resolve `%s')", u.nodename);
738 memcpy(&rq.host, he->h_addr, sizeof(struct in_addr));
741 /* --- Shell commands are easy --- */
748 /* --- A command given on the command line isn't too hard --- */
750 else if (optind < argc) {
751 todo = argv + optind;
755 else switch (style) {
757 /* --- An unadorned becoming requires little work --- */
760 shell[0] = getenv("SHELL");
762 shell[0] = from_pw->pw_shell;
768 /* --- An su-like login needs slightly less effort --- */
771 shell[0] = to_pw->pw_shell;
777 /* --- A login request needs a little bit of work --- */
780 const char *p = strrchr(to_pw->pw_shell, '/');
786 shell[0] = xmalloc(strlen(p) + 2);
788 strcpy(shell[0] + 1, p);
791 binary = to_pw->pw_shell;
792 chdir(to_pw->pw_dir);
796 /* --- Mangle the environment --- *
798 * This keeps getting more complicated all the time. (How true. Now I've
799 * got all sorts of nasty environment mangling to do.)
801 * The environment stuff now happens in seven phases:
803 * 1. Mark very special variables to be preserved. Currently only TERM
804 * and DISPLAY are treated in this way.
806 * 2. Set and preserve Become's own environment variables.
808 * 3. Set and preserve the user identity variables (USER, LOGNAME, HOME,
809 * SHELL and MAIL) if we're being `su'-like or `login'-like.
811 * 4. If we're preserving the environment or being `su'-like, process the
812 * PATH variable a little. Otherwise reset it to something
815 * 5. If we're being `login'-like, expunge all unpreserved variables.
817 * 6. Expunge any security-critical variables.
819 * 7. Build a new environment table to pass to child processes.
823 /* --- Variables to be preserved always --- *
825 * A user can explicitly expunge a variable in this list, in which case
826 * we never get to see it here.
829 static char *preserve[] = {
833 /* --- Variables to be expunged --- *
835 * Any environment string which has one of the following as a prefix
836 * will be expunged from the environment passed to the called process.
837 * The first line lists variables which have been used to list search
838 * paths for shared libraries: by manipulating these, an attacker could
839 * replace a standard library with one of his own. The second line lists
840 * other well-known dangerous environment variables.
843 static char *banned[] = {
844 "-LD_", "SHLIB_PATH", "LIBPATH", "-_RLD_",
845 "IFS", "ENV", "BASH_ENV", "KRB_CONF",
849 /* --- Other useful variables --- */
858 /* --- Stage one. Preserve display-specific variables --- */
860 for (pp = preserve; *pp; pp++) {
861 if ((e = sym_find(&bc__env, *pp, -1, 0, 0)) != 0)
862 e->f |= envFlag_preserve;
865 /* --- Stage two. Set Become's own variables --- */
867 e = sym_find(&bc__env, "BECOME_ORIGINAL_USER", -1, sizeof(*e), &f);
869 bc__setenv(e, from_pw->pw_name);
870 e->f |= envFlag_preserve;
872 e = sym_find(&bc__env, "BECOME_ORIGINAL_HOME", -1, sizeof(*e), &f);
874 bc__setenv(e, from_pw->pw_dir);
875 e->f |= envFlag_preserve;
877 bc__putenv("BECOME_OLD_USER", from_pw->pw_name, envFlag_preserve, 0);
878 bc__putenv("BECOME_OLD_HOME", from_pw->pw_dir, envFlag_preserve, 0);
879 bc__putenv("BECOME_USER", to_pw->pw_name, envFlag_preserve, 0);
880 bc__putenv("BECOME_HOME", to_pw->pw_dir, envFlag_preserve, 0);
882 /* --- Stage three. Set user identity --- */
886 static char *maildirs[] = {
887 "/var/spool/mail", "/var/mail",
888 "/usr/spool/mail", "/usr/mail",
894 for (pp = maildirs; *pp; pp++) {
895 if (stat(*pp, &s) == 0 && S_ISDIR(s.st_mode)) {
896 sprintf(b, "%s/%s", *pp, to_pw->pw_name);
897 bc__putenv("MAIL", b, envFlag_preserve, 0);
904 bc__putenv("USER", to_pw->pw_name, envFlag_preserve, 0);
905 bc__putenv("LOGNAME", to_pw->pw_name, envFlag_preserve, 0);
906 bc__putenv("HOME", to_pw->pw_dir, envFlag_preserve, 0);
907 bc__putenv("SHELL", to_pw->pw_shell, envFlag_preserve, 0);
911 /* --- Stage four. Set the user's PATH properly --- */
914 /* --- Find an existing path --- *
916 * If there's no path, or this is a login, then set a default path,
917 * unless we're meant to preserve the existing one. Whew!
920 e = sym_find(&bc__env, "PATH", -1, sizeof(*e), &f);
922 if (!f || (style == l_login && ~e->f & envFlag_preserve)) {
924 rq.to ? "/usr/bin:/bin" : "/usr/bin:/usr/sbin:/bin:/sbin",
925 envFlag_preserve, 0);
928 /* --- Find the string --- */
930 e->f = envFlag_preserve;
931 p = strchr(e->val, '=') + 1;
934 /* --- Write the new version to a dynamically allocated buffer --- */
936 e->val = xmalloc(4 + 1 + strlen(p) + 1);
937 strcpy(e->val, "PATH=");
940 for (p = strtok(p, ":"); p; p = strtok(0, ":")) {
955 /* --- Stages five and six. Expunge variables and count numbers --- *
957 * Folded together, so I only need one pass through the table. Also
958 * count the number of variables needed at this time.
963 for (sym_createIter(&i, &bc__env); (e = sym_next(&i)) != 0; ) {
965 /* --- Login style expunges all unpreserved variables --- */
967 if (style == l_login && ~e->f & envFlag_preserve)
970 /* --- Otherwise just check the name against the list --- */
972 for (pp = banned; *pp; pp++) {
975 if (memcmp(e->_base.name, p, strlen(p)) == 0)
977 } else if (strcmp(e->_base.name, p) == 0)
985 sym_remove(&bc__env, e);
988 /* --- Stage seven. Build the new environment block --- */
990 env = qq = xmalloc((sz + 1) * sizeof(*qq));
992 for (sym_createIter(&i, &bc__env); (e = sym_next(&i)) != 0; )
997 /* --- Trace the command --- */
999 IF_TRACING(TRACE_SETUP, {
1002 trace(TRACE_SETUP, "setup: from user %s to user %s",
1003 from_pw->pw_name, to_pw->pw_name);
1004 trace(TRACE_SETUP, "setup: binary == `%s'", binary);
1005 for (i = 0; todo[i]; i++)
1006 trace(TRACE_SETUP, "setup: arg %i == `%s'", i, todo[i]);
1007 for (i = 0; env[i]; i++)
1008 trace(TRACE_SETUP, "setup: env %i == `%s'", i, env[i]);
1011 /* --- If necessary, resolve the path to the command --- */
1013 if (!strchr(binary, '/')) {
1017 if ((p = getenv("PATH")) == 0)
1018 p = "/bin:/usr/bin";
1021 for (p = strtok(path, ":"); p; p = strtok(0, ":")) {
1023 /* --- Check length of string before copying --- */
1025 if (strlen(p) + strlen(binary) + 2 > sizeof(rq.cmd))
1028 /* --- Now build the pathname and check it --- */
1030 sprintf(rq.cmd, "%s/%s", p, todo[0]);
1031 if (stat(rq.cmd, &st) == 0 && /* Check it exists */
1032 st.st_mode & 0111 && /* Check it's executable */
1033 (st.st_mode & S_IFMT) == S_IFREG) /* Check it's a file */
1038 die("couldn't find `%s' in path", todo[0]);
1042 T( trace(TRACE_SETUP, "setup: resolve binary to `%s'", binary); )
1044 /* --- Canonicalise the path string, if necessary --- */
1051 /* --- Insert current directory name if path not absolute --- */
1056 if (!getcwd(b, sizeof(b)))
1057 die("couldn't read current directory: %s", strerror(errno));
1062 /* --- Now copy over characters from the path string --- */
1066 /* --- Check for buffer overflows here --- *
1068 * I write at most one byte per iteration so this is OK. Remember to
1069 * allow one for the null byte.
1072 if (p >= b + sizeof(b) - 1)
1073 die("internal error: buffer overflow while canonifying path");
1075 /* --- Reduce multiple slashes to just one --- */
1083 /* --- Handle dots in filenames --- *
1085 * @p[-1]@ is valid here, because if @*q@ is not a `/' then either
1086 * we've just stuck the current directory on the end of the buffer,
1087 * or we've just put something else on the end.
1090 else if (*q == '.' && p[-1] == '/') {
1092 /* --- A simple `./' just gets removed --- */
1094 if (q[1] == 0 || q[1] == '/') {
1100 /* --- A `../' needs to be peeled back to the previous `/' --- */
1102 if (q[1] == '.' && (q[2] == 0 || q[2] == '/')) {
1105 while (p > b && p[-1] != '/')
1118 T( trace(TRACE_SETUP, "setup: canonify binary to `%s'", rq.cmd); )
1120 /* --- Run the check --- *
1122 * If the user is already what she wants to be, then print a warning.
1123 * Then, if I was just going to spawn a shell, quit, to reduce user
1124 * confusion. Otherwise, do what was wanted anyway.
1127 if (rq.from == rq.to) {
1128 moan("you already are `%s'!", to_pw->pw_name);
1129 if (!cmd && todo == shell) {
1130 moan("(to prevent confusion, I'm not spawning a shell)");
1137 "permission %s for %s to become %s to run `%s'",
1138 a ? "granted" : "denied", from_pw->pw_name, to_pw->pw_name,
1142 die("permission denied");
1145 /* --- Now do the job --- */
1147 T( trace(TRACE_MISC, "become: permission granted"); )
1149 if (flags & f_dummy) {
1150 puts("permission granted");
1153 if (setuid(rq.to) == -1)
1154 die("couldn't set uid: %s", strerror(errno));
1155 execve(rq.cmd, todo, env);
1156 die("couldn't exec `%s': %s", rq.cmd, strerror(errno));
1161 /*----- That's all, folks -------------------------------------------------*/