2 * Copyright (c) 2000-2007 Todd C. Miller <Todd.Miller@courtesan.com>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 * Sponsored in part by the Defense Advanced Research Projects
17 * Agency (DARPA) and Air Force Research Laboratory, Air Force
18 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
23 #include <sys/types.h>
24 #include <sys/param.h>
34 #endif /* STDC_HEADERS */
38 # ifdef HAVE_STRINGS_H
41 #endif /* HAVE_STRING_H */
44 #endif /* HAVE_UNISTD_H */
48 # include "emul/err.h"
49 #endif /* HAVE_ERR_H */
55 __unused static const char rcsid[] = "$Sudo: env.c,v 1.39.2.17 2007/07/31 18:04:31 millert Exp $";
59 * Flags used in rebuild_env()
62 #define DID_TERM 0x0001
64 #define DID_PATH 0x0002
66 #define DID_HOME 0x0004
68 #define DID_SHELL 0x0008
70 #define DID_LOGNAME 0x0010
72 #define DID_USER 0x0020
74 #define DID_USERNAME 0x0040
76 #define DID_MAX 0x00ff
79 #define KEPT_TERM 0x0100
81 #define KEPT_PATH 0x0200
83 #define KEPT_HOME 0x0400
85 #define KEPT_SHELL 0x0800
87 #define KEPT_LOGNAME 0x1000
89 #define KEPT_USER 0x2000
91 #define KEPT_USERNAME 0x4000
93 #define KEPT_MAX 0xff00
96 #define VNULL (VOID *)NULL
99 char **envp; /* pointer to the new environment */
100 size_t env_size; /* size of new_environ in char **'s */
101 size_t env_len; /* number of slots used, not counting NULL */
107 char **rebuild_env __P((char **, int, int));
108 static void insert_env __P((char *, struct environment *, int));
109 static char *format_env __P((char *, ...));
112 * Copy of the sudo-managed environment.
114 static struct environment env;
117 * Default table of "bad" variables to remove from the environment.
118 * XXX - how to omit TERMCAP if it starts with '/'?
120 static const char *initial_badenv_table[] = {
146 #endif /* HAVE_KERB4 */
150 #endif /* HAVE_KERB5 */
155 #endif /* HAVE_SECURID */
156 "TERMINFO", /* terminfo, exclusive path to terminfo files */
157 "TERMINFO_DIRS", /* terminfo, path(s) to terminfo files */
158 "TERMPATH", /* termcap, path(s) to termcap files */
159 "TERMCAP", /* XXX - only if it starts with '/' */
160 "ENV", /* ksh, file to source before script runs */
161 "BASH_ENV", /* bash, file to source before script runs */
162 "PS4", /* bash, prefix for lines in xtrace mode */
163 "GLOBIGNORE", /* bash, globbing patterns to ignore */
164 "SHELLOPTS", /* bash, extra command line options */
165 "JAVA_TOOL_OPTIONS", /* java, extra command line options */
166 "PERLIO_DEBUG ", /* perl, debugging output file */
167 "PERLLIB", /* perl, search path for modules/includes */
168 "PERL5LIB", /* perl 5, search path for modules/includes */
169 "PERL5OPT", /* perl 5, extra command line options */
170 "PERL5DB", /* perl 5, command used to load debugger */
171 "FPATH", /* ksh, search path for functions */
172 "NULLCMD", /* zsh, command for null file redirection */
173 "READNULLCMD", /* zsh, command for null file redirection */
174 "ZDOTDIR", /* zsh, search path for dot files */
175 "TMPPREFIX", /* zsh, prefix for temporary files */
176 "PYTHONHOME", /* python, module search path */
177 "PYTHONPATH", /* python, search path */
178 "PYTHONINSPECT", /* python, allow inspection */
179 "RUBYLIB", /* ruby, library load path */
180 "RUBYOPT", /* ruby, extra command line options */
185 * Default table of variables to check for '%' and '/' characters.
187 static const char *initial_checkenv_table[] = {
198 * Default table of variables to preserve in the environment.
200 static const char *initial_keepenv_table[] = {
217 * Given a variable and value, allocate and format an environment string.
221 format_env(char *var, ...)
223 format_env(var, va_alist)
238 esize = strlen(var) + 2;
239 while ((val = va_arg(ap, char *)) != NULL)
240 esize += strlen(val);
242 estring = (char *) emalloc(esize);
244 /* Store variable name and the '=' separator. */
245 if (strlcpy(estring, var, esize) >= esize ||
246 strlcat(estring, "=", esize) >= esize) {
248 errx(1, "internal error, format_env() overflow");
251 /* Now store the variable's value (if any) */
257 while ((val = va_arg(ap, char *)) != NULL) {
258 if (strlcat(estring, val, esize) >= esize)
259 errx(1, "internal error, format_env() overflow");
267 * Insert str into e->envp, assumes str has an '=' in it.
270 insert_env(str, e, dupcheck)
272 struct environment *e;
278 /* Make sure there is room for the new entry plus a NULL. */
279 if (e->env_len + 2 > e->env_size) {
281 e->envp = erealloc3(e->envp, e->env_size, sizeof(char *));
285 varlen = (strchr(str, '=') - str) + 1;
287 for (nep = e->envp; *nep; nep++) {
288 if (strncmp(str, *nep, varlen) == 0) {
294 nep = e->envp + e->env_len;
302 * Check the env_delete blacklist.
303 * Returns TRUE if the variable was found, else false.
306 matches_env_delete(var)
309 struct list_member *cur;
311 int iswild, match = FALSE;
313 /* Skip anything listed in env_delete. */
314 for (cur = def_env_delete; cur; cur = cur->next) {
315 len = strlen(cur->value);
316 /* Deal with '*' wildcard */
317 if (cur->value[len - 1] == '*') {
322 if (strncmp(cur->value, var, len) == 0 &&
323 (iswild || var[len] == '=')) {
332 * Apply the env_check list.
333 * Returns TRUE if the variable is allowed, FALSE if denied
337 matches_env_check(var)
340 struct list_member *cur;
342 int iswild, keepit = -1;
344 for (cur = def_env_check; cur; cur = cur->next) {
345 len = strlen(cur->value);
346 /* Deal with '*' wildcard */
347 if (cur->value[len - 1] == '*') {
352 if (strncmp(cur->value, var, len) == 0 &&
353 (iswild || var[len] == '=')) {
354 keepit = !strpbrk(var, "/%");
362 * Check the env_keep list.
363 * Returns TRUE if the variable is allowed else FALSE.
366 matches_env_keep(var)
369 struct list_member *cur;
371 int iswild, keepit = FALSE;
373 for (cur = def_env_keep; cur; cur = cur->next) {
374 len = strlen(cur->value);
375 /* Deal with '*' wildcard */
376 if (cur->value[len - 1] == '*') {
381 if (strncmp(cur->value, var, len) == 0 &&
382 (iswild || var[len] == '=')) {
391 * Build a new environment and ether clear potentially dangerous
392 * variables from the old one or start with a clean slate.
393 * Also adds sudo-specific variables (SUDO_*).
396 rebuild_env(envp, sudo_mode, noexec)
401 char **ep, *cp, *ps1;
405 * Either clean out the environment or reset to a safe default.
409 memset(&env, 0, sizeof(env));
411 /* Pull in vars we want to keep from the old environment. */
412 for (ep = envp; *ep; ep++) {
415 /* Skip variables with values beginning with () (bash functions) */
416 if ((cp = strchr(*ep, '=')) != NULL) {
417 if (strncmp(cp, "=() ", 3) == 0)
422 * First check certain variables for '%' and '/' characters.
423 * If no match there, check the keep list.
424 * If nothing matched, we remove it from the environment.
426 keepit = matches_env_check(*ep);
428 keepit = matches_env_keep(*ep);
430 if (!strncmp (*ep, "DISPLAY=",8)
431 || !strncmp (*ep, "XAUTHORITY=", 11)
432 || !strncmp (*ep, "XAUTHORIZATION=", 15)
433 || !strncmp (*ep, "XAPPLRESDIR=", 12)
434 || !strncmp (*ep, "XFILESEARCHPATH=", 16)
435 || !strncmp (*ep, "XUSERFILESEARCHPATH=", 20)
436 || !strncmp (*ep, "LANG=", 5)
437 || !strncmp (*ep, "LANGUAGE=", 9)
438 || !strncmp (*ep, "LC_", 3))
441 /* For SUDO_PS1 -> PS1 conversion. */
442 if (strncmp(*ep, "SUDO_PS1=", 8) == 0)
446 /* Preserve variable. */
449 if (strncmp(*ep, "HOME=", 5) == 0)
450 SET(didvar, DID_HOME);
453 if (strncmp(*ep, "LOGNAME=", 8) == 0)
454 SET(didvar, DID_LOGNAME);
457 if (strncmp(*ep, "PATH=", 5) == 0)
458 SET(didvar, DID_PATH);
461 if (strncmp(*ep, "SHELL=", 6) == 0)
462 SET(didvar, DID_SHELL);
465 if (strncmp(*ep, "TERM=", 5) == 0)
466 SET(didvar, DID_TERM);
469 if (strncmp(*ep, "USER=", 5) == 0)
470 SET(didvar, DID_USER);
471 if (strncmp(*ep, "USERNAME=", 5) == 0)
472 SET(didvar, DID_USERNAME);
475 insert_env(*ep, &env, 0);
478 didvar |= didvar << 8; /* convert DID_* to KEPT_* */
481 * Add in defaults. In -i mode these come from the runas user,
482 * otherwise they may be from the user's environment (depends
483 * on sudoers options).
485 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
486 insert_env(format_env("HOME", runas_pw->pw_dir, VNULL), &env,
487 ISSET(didvar, DID_HOME));
488 insert_env(format_env("SHELL", runas_pw->pw_shell, VNULL), &env,
489 ISSET(didvar, DID_SHELL));
490 insert_env(format_env("LOGNAME", runas_pw->pw_name, VNULL), &env,
491 ISSET(didvar, DID_LOGNAME));
492 insert_env(format_env("USER", runas_pw->pw_name, VNULL), &env,
493 ISSET(didvar, DID_USER));
494 insert_env(format_env("USERNAME", runas_pw->pw_name, VNULL), &env,
495 ISSET(didvar, DID_USERNAME));
497 if (!ISSET(didvar, DID_HOME))
498 insert_env(format_env("HOME", user_dir, VNULL), &env, 0);
499 if (!ISSET(didvar, DID_SHELL))
500 insert_env(format_env("SHELL", sudo_user.pw->pw_shell, VNULL),
502 if (!ISSET(didvar, DID_LOGNAME))
503 insert_env(format_env("LOGNAME", user_name, VNULL), &env, 0);
504 if (!ISSET(didvar, DID_USER))
505 insert_env(format_env("USER", user_name, VNULL), &env, 0);
506 if (!ISSET(didvar, DID_USERNAME))
507 insert_env(format_env("USERNAME", user_name, VNULL), &env, 0);
511 * Copy envp entries as long as they don't match env_delete or
514 for (ep = envp; *ep; ep++) {
517 /* Skip variables with values beginning with () (bash functions) */
518 if ((cp = strchr(*ep, '=')) != NULL) {
519 if (strncmp(cp, "=() ", 3) == 0)
524 * First check variables against the blacklist in env_delete.
525 * If no match there check for '%' and '/' characters.
527 okvar = matches_env_delete(*ep) != TRUE;
529 okvar = matches_env_check(*ep) != FALSE;
532 if (strncmp(*ep, "SUDO_PS1=", 9) == 0)
534 else if (strncmp(*ep, "PATH=", 5) == 0)
535 SET(didvar, DID_PATH);
536 else if (strncmp(*ep, "TERM=", 5) == 0)
537 SET(didvar, DID_TERM);
538 insert_env(*ep, &env, 0);
544 /* Replace the PATH envariable with a secure one. */
545 if (!user_is_exempt()) {
546 insert_env(format_env("PATH", SECURE_PATH, VNULL), &env, 1);
547 SET(didvar, DID_PATH);
551 /* Set $USER, $LOGNAME and $USERNAME to target if "set_logname" is true. */
552 if (def_set_logname && runas_pw->pw_name) {
553 if (!ISSET(didvar, KEPT_LOGNAME))
554 insert_env(format_env("LOGNAME", runas_pw->pw_name, VNULL), &env, 1);
555 if (!ISSET(didvar, KEPT_USER))
556 insert_env(format_env("USER", runas_pw->pw_name, VNULL), &env, 1);
557 if (!ISSET(didvar, KEPT_USERNAME))
558 insert_env(format_env("USERNAME", runas_pw->pw_name, VNULL), &env, 1);
561 /* Set $HOME for `sudo -H'. Only valid at PERM_FULL_RUNAS. */
562 if (runas_pw->pw_dir) {
563 if (ISSET(sudo_mode, MODE_RESET_HOME) ||
564 (ISSET(sudo_mode, MODE_RUN) && (def_always_set_home ||
565 (ISSET(sudo_mode, MODE_SHELL) && def_set_home))))
566 insert_env(format_env("HOME", runas_pw->pw_dir, VNULL), &env, 1);
569 /* Provide default values for $TERM and $PATH if they are not set. */
570 if (!ISSET(didvar, DID_TERM))
571 insert_env("TERM=unknown", &env, 0);
572 if (!ISSET(didvar, DID_PATH))
573 insert_env(format_env("PATH", _PATH_DEFPATH, VNULL), &env, 0);
576 * Preload a noexec file? For a list of LD_PRELOAD-alikes, see
577 * http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html
578 * XXX - should prepend to original value, if any
580 if (noexec && def_noexec_file != NULL) {
581 #if defined(__darwin__) || defined(__APPLE__)
582 insert_env(format_env("DYLD_INSERT_LIBRARIES", def_noexec_file, VNULL),
584 insert_env(format_env("DYLD_FORCE_FLAT_NAMESPACE", VNULL), &env, 1);
586 # if defined(__osf__) || defined(__sgi)
587 insert_env(format_env("_RLD_LIST", def_noexec_file, ":DEFAULT", VNULL),
591 insert_env(format_env("LDR_PRELOAD", def_noexec_file, VNULL), &env, 1);
593 insert_env(format_env("LD_PRELOAD", def_noexec_file, VNULL), &env, 1);
595 # endif /* __osf__ || __sgi */
596 #endif /* __darwin__ || __APPLE__ */
599 /* Set PS1 if SUDO_PS1 is set. */
601 insert_env(ps1, &env, 1);
603 /* Add the SUDO_COMMAND envariable (cmnd + args). */
605 insert_env(format_env("SUDO_COMMAND", user_cmnd, " ", user_args, VNULL),
608 insert_env(format_env("SUDO_COMMAND", user_cmnd, VNULL), &env, 1);
610 /* Add the SUDO_USER, SUDO_UID, SUDO_GID environment variables. */
611 insert_env(format_env("SUDO_USER", user_name, VNULL), &env, 1);
612 easprintf(&cp, "SUDO_UID=%lu", (unsigned long) user_uid);
613 insert_env(cp, &env, 1);
614 easprintf(&cp, "SUDO_GID=%lu", (unsigned long) user_gid);
615 insert_env(cp, &env, 1);
621 insert_env_vars(envp, env_vars)
623 struct list_member *env_vars;
625 struct list_member *cur;
627 if (env_vars == NULL)
631 * Make sure we still own the environment and steal it back if not.
633 if (env.envp != envp) {
637 for (ep = envp; *ep != NULL; ep++)
640 if (evlen + 1 > env.env_size) {
642 env.env_size = evlen + 1 + 128;
643 env.envp = emalloc2(env.env_size, sizeof(char *));
645 memcpy(env.envp, envp, (evlen + 1) * sizeof(char *));
649 /* Add user-specified environment variables. */
650 for (cur = env_vars; cur != NULL; cur = cur->next)
651 insert_env(cur->value, &env, 1);
657 * Validate the list of environment variables passed in on the command
658 * line against env_delete, env_check, and env_keep.
659 * Calls log_error() if any specified variables are not allowed.
662 validate_env_vars(env_vars)
663 struct list_member *env_vars;
665 struct list_member *var;
666 char *eq, *bad = NULL;
667 size_t len, blen = 0, bsize = 0;
670 for (var = env_vars; var != NULL; var = var->next) {
672 if (!user_is_exempt() && strncmp(var->value, "PATH=", 5) == 0) {
677 okvar = matches_env_check(var->value);
679 okvar = matches_env_keep(var->value);
681 okvar = matches_env_delete(var->value) == FALSE;
683 okvar = matches_env_check(var->value) != FALSE;
685 if (okvar == FALSE) {
686 /* Not allowed, add to error string, allocating as needed. */
687 if ((eq = strchr(var->value, '=')) != NULL)
689 len = strlen(var->value) + 2;
690 if (blen + len >= bsize) {
693 } while (blen + len >= bsize);
694 bad = erealloc(bad, bsize);
697 strlcat(bad, var->value, bsize);
698 strlcat(bad, ", ", bsize);
705 bad[blen - 2] = '\0'; /* remove trailing ", " */
707 "sorry, you are not allowed to set the following environment variables: %s", bad);
716 struct list_member *cur;
719 /* Fill in the "env_delete" list. */
720 for (p = initial_badenv_table; *p; p++) {
721 cur = emalloc(sizeof(struct list_member));
722 cur->value = estrdup(*p);
723 cur->next = def_env_delete;
724 def_env_delete = cur;
727 /* Fill in the "env_check" list. */
728 for (p = initial_checkenv_table; *p; p++) {
729 cur = emalloc(sizeof(struct list_member));
730 cur->value = estrdup(*p);
731 cur->next = def_env_check;
735 /* Fill in the "env_keep" list. */
736 for (p = initial_keepenv_table; *p; p++) {
737 cur = emalloc(sizeof(struct list_member));
738 cur->value = estrdup(*p);
739 cur->next = def_env_keep;