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.18 2008/03/13 11:34:57 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[] = {
144 #endif /* HAVE_KERB4 */
148 #endif /* HAVE_KERB5 */
153 #endif /* HAVE_SECURID */
154 "TERMINFO", /* terminfo, exclusive path to terminfo files */
155 "TERMINFO_DIRS", /* terminfo, path(s) to terminfo files */
156 "TERMPATH", /* termcap, path(s) to termcap files */
157 "TERMCAP", /* XXX - only if it starts with '/' */
158 "ENV", /* ksh, file to source before script runs */
159 "BASH_ENV", /* bash, file to source before script runs */
160 "PS4", /* bash, prefix for lines in xtrace mode */
161 "GLOBIGNORE", /* bash, globbing patterns to ignore */
162 "SHELLOPTS", /* bash, extra command line options */
163 "JAVA_TOOL_OPTIONS", /* java, extra command line options */
164 "PERLIO_DEBUG ", /* perl, debugging output file */
165 "PERLLIB", /* perl, search path for modules/includes */
166 "PERL5LIB", /* perl 5, search path for modules/includes */
167 "PERL5OPT", /* perl 5, extra command line options */
168 "PERL5DB", /* perl 5, command used to load debugger */
169 "FPATH", /* ksh, search path for functions */
170 "NULLCMD", /* zsh, command for null file redirection */
171 "READNULLCMD", /* zsh, command for null file redirection */
172 "ZDOTDIR", /* zsh, search path for dot files */
173 "TMPPREFIX", /* zsh, prefix for temporary files */
174 "PYTHONHOME", /* python, module search path */
175 "PYTHONPATH", /* python, search path */
176 "PYTHONINSPECT", /* python, allow inspection */
177 "RUBYLIB", /* ruby, library load path */
178 "RUBYOPT", /* ruby, extra command line options */
183 * Default table of variables to check for '%' and '/' characters.
185 static const char *initial_checkenv_table[] = {
196 * Default table of variables to preserve in the environment.
198 static const char *initial_keepenv_table[] = {
216 * Given a variable and value, allocate and format an environment string.
220 format_env(char *var, ...)
222 format_env(var, va_alist)
237 esize = strlen(var) + 2;
238 while ((val = va_arg(ap, char *)) != NULL)
239 esize += strlen(val);
241 estring = (char *) emalloc(esize);
243 /* Store variable name and the '=' separator. */
244 if (strlcpy(estring, var, esize) >= esize ||
245 strlcat(estring, "=", esize) >= esize) {
247 errx(1, "internal error, format_env() overflow");
250 /* Now store the variable's value (if any) */
256 while ((val = va_arg(ap, char *)) != NULL) {
257 if (strlcat(estring, val, esize) >= esize)
258 errx(1, "internal error, format_env() overflow");
266 * Insert str into e->envp, assumes str has an '=' in it.
269 insert_env(str, e, dupcheck)
271 struct environment *e;
277 /* Make sure there is room for the new entry plus a NULL. */
278 if (e->env_len + 2 > e->env_size) {
280 e->envp = erealloc3(e->envp, e->env_size, sizeof(char *));
284 varlen = (strchr(str, '=') - str) + 1;
286 for (nep = e->envp; *nep; nep++) {
287 if (strncmp(str, *nep, varlen) == 0) {
293 nep = e->envp + e->env_len;
301 * Check the env_delete blacklist.
302 * Returns TRUE if the variable was found, else false.
305 matches_env_delete(var)
308 struct list_member *cur;
310 int iswild, match = FALSE;
312 /* Skip anything listed in env_delete. */
313 for (cur = def_env_delete; cur; cur = cur->next) {
314 len = strlen(cur->value);
315 /* Deal with '*' wildcard */
316 if (cur->value[len - 1] == '*') {
321 if (strncmp(cur->value, var, len) == 0 &&
322 (iswild || var[len] == '=')) {
331 * Apply the env_check list.
332 * Returns TRUE if the variable is allowed, FALSE if denied
336 matches_env_check(var)
339 struct list_member *cur;
341 int iswild, keepit = -1;
343 for (cur = def_env_check; cur; cur = cur->next) {
344 len = strlen(cur->value);
345 /* Deal with '*' wildcard */
346 if (cur->value[len - 1] == '*') {
351 if (strncmp(cur->value, var, len) == 0 &&
352 (iswild || var[len] == '=')) {
353 keepit = !strpbrk(var, "/%");
361 * Check the env_keep list.
362 * Returns TRUE if the variable is allowed else FALSE.
365 matches_env_keep(var)
368 struct list_member *cur;
370 int iswild, keepit = FALSE;
372 for (cur = def_env_keep; cur; cur = cur->next) {
373 len = strlen(cur->value);
374 /* Deal with '*' wildcard */
375 if (cur->value[len - 1] == '*') {
380 if (strncmp(cur->value, var, len) == 0 &&
381 (iswild || var[len] == '=')) {
390 * Build a new environment and ether clear potentially dangerous
391 * variables from the old one or start with a clean slate.
392 * Also adds sudo-specific variables (SUDO_*).
395 rebuild_env(envp, sudo_mode, noexec)
400 char **ep, *cp, *ps1;
404 * Either clean out the environment or reset to a safe default.
408 memset(&env, 0, sizeof(env));
410 /* Pull in vars we want to keep from the old environment. */
411 for (ep = envp; *ep; ep++) {
414 /* Skip variables with values beginning with () (bash functions) */
415 if ((cp = strchr(*ep, '=')) != NULL) {
416 if (strncmp(cp, "=() ", 3) == 0)
421 * First check certain variables for '%' and '/' characters.
422 * If no match there, check the keep list.
423 * If nothing matched, we remove it from the environment.
425 keepit = matches_env_check(*ep);
427 keepit = matches_env_keep(*ep);
429 /* For SUDO_PS1 -> PS1 conversion. */
430 if (strncmp(*ep, "SUDO_PS1=", 8) == 0)
434 /* Preserve variable. */
437 if (strncmp(*ep, "HOME=", 5) == 0)
438 SET(didvar, DID_HOME);
441 if (strncmp(*ep, "LOGNAME=", 8) == 0)
442 SET(didvar, DID_LOGNAME);
445 if (strncmp(*ep, "PATH=", 5) == 0)
446 SET(didvar, DID_PATH);
449 if (strncmp(*ep, "SHELL=", 6) == 0)
450 SET(didvar, DID_SHELL);
453 if (strncmp(*ep, "TERM=", 5) == 0)
454 SET(didvar, DID_TERM);
457 if (strncmp(*ep, "USER=", 5) == 0)
458 SET(didvar, DID_USER);
459 if (strncmp(*ep, "USERNAME=", 5) == 0)
460 SET(didvar, DID_USERNAME);
463 insert_env(*ep, &env, 0);
466 didvar |= didvar << 8; /* convert DID_* to KEPT_* */
469 * Add in defaults. In -i mode these come from the runas user,
470 * otherwise they may be from the user's environment (depends
471 * on sudoers options).
473 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
474 insert_env(format_env("HOME", runas_pw->pw_dir, VNULL), &env,
475 ISSET(didvar, DID_HOME));
476 insert_env(format_env("SHELL", runas_pw->pw_shell, VNULL), &env,
477 ISSET(didvar, DID_SHELL));
478 insert_env(format_env("LOGNAME", runas_pw->pw_name, VNULL), &env,
479 ISSET(didvar, DID_LOGNAME));
480 insert_env(format_env("USER", runas_pw->pw_name, VNULL), &env,
481 ISSET(didvar, DID_USER));
482 insert_env(format_env("USERNAME", runas_pw->pw_name, VNULL), &env,
483 ISSET(didvar, DID_USERNAME));
485 if (!ISSET(didvar, DID_HOME))
486 insert_env(format_env("HOME", user_dir, VNULL), &env, 0);
487 if (!ISSET(didvar, DID_SHELL))
488 insert_env(format_env("SHELL", sudo_user.pw->pw_shell, VNULL),
490 if (!ISSET(didvar, DID_LOGNAME))
491 insert_env(format_env("LOGNAME", user_name, VNULL), &env, 0);
492 if (!ISSET(didvar, DID_USER))
493 insert_env(format_env("USER", user_name, VNULL), &env, 0);
494 if (!ISSET(didvar, DID_USERNAME))
495 insert_env(format_env("USERNAME", user_name, VNULL), &env, 0);
499 * Copy envp entries as long as they don't match env_delete or
502 for (ep = envp; *ep; ep++) {
505 /* Skip variables with values beginning with () (bash functions) */
506 if ((cp = strchr(*ep, '=')) != NULL) {
507 if (strncmp(cp, "=() ", 3) == 0)
512 * First check variables against the blacklist in env_delete.
513 * If no match there check for '%' and '/' characters.
515 okvar = matches_env_delete(*ep) != TRUE;
517 okvar = matches_env_check(*ep) != FALSE;
520 if (strncmp(*ep, "SUDO_PS1=", 9) == 0)
522 else if (strncmp(*ep, "PATH=", 5) == 0)
523 SET(didvar, DID_PATH);
524 else if (strncmp(*ep, "TERM=", 5) == 0)
525 SET(didvar, DID_TERM);
526 insert_env(*ep, &env, 0);
532 /* Replace the PATH envariable with a secure one. */
533 if (!user_is_exempt()) {
534 insert_env(format_env("PATH", SECURE_PATH, VNULL), &env, 1);
535 SET(didvar, DID_PATH);
539 /* Set $USER, $LOGNAME and $USERNAME to target if "set_logname" is true. */
540 if (def_set_logname && runas_pw->pw_name) {
541 if (!ISSET(didvar, KEPT_LOGNAME))
542 insert_env(format_env("LOGNAME", runas_pw->pw_name, VNULL), &env, 1);
543 if (!ISSET(didvar, KEPT_USER))
544 insert_env(format_env("USER", runas_pw->pw_name, VNULL), &env, 1);
545 if (!ISSET(didvar, KEPT_USERNAME))
546 insert_env(format_env("USERNAME", runas_pw->pw_name, VNULL), &env, 1);
549 /* Set $HOME for `sudo -H'. Only valid at PERM_FULL_RUNAS. */
550 if (runas_pw->pw_dir) {
551 if (ISSET(sudo_mode, MODE_RESET_HOME) ||
552 (ISSET(sudo_mode, MODE_RUN) && (def_always_set_home ||
553 (ISSET(sudo_mode, MODE_SHELL) && def_set_home))))
554 insert_env(format_env("HOME", runas_pw->pw_dir, VNULL), &env, 1);
557 /* Provide default values for $TERM and $PATH if they are not set. */
558 if (!ISSET(didvar, DID_TERM))
559 insert_env("TERM=unknown", &env, 0);
560 if (!ISSET(didvar, DID_PATH))
561 insert_env(format_env("PATH", _PATH_DEFPATH, VNULL), &env, 0);
564 * Preload a noexec file? For a list of LD_PRELOAD-alikes, see
565 * http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html
566 * XXX - should prepend to original value, if any
568 if (noexec && def_noexec_file != NULL) {
569 #if defined(__darwin__) || defined(__APPLE__)
570 insert_env(format_env("DYLD_INSERT_LIBRARIES", def_noexec_file, VNULL),
572 insert_env(format_env("DYLD_FORCE_FLAT_NAMESPACE", VNULL), &env, 1);
574 # if defined(__osf__) || defined(__sgi)
575 insert_env(format_env("_RLD_LIST", def_noexec_file, ":DEFAULT", VNULL),
579 insert_env(format_env("LDR_PRELOAD", def_noexec_file, VNULL), &env, 1);
581 insert_env(format_env("LD_PRELOAD", def_noexec_file, VNULL), &env, 1);
583 # endif /* __osf__ || __sgi */
584 #endif /* __darwin__ || __APPLE__ */
587 /* Set PS1 if SUDO_PS1 is set. */
589 insert_env(ps1, &env, 1);
591 /* Add the SUDO_COMMAND envariable (cmnd + args). */
593 insert_env(format_env("SUDO_COMMAND", user_cmnd, " ", user_args, VNULL),
596 insert_env(format_env("SUDO_COMMAND", user_cmnd, VNULL), &env, 1);
598 /* Add the SUDO_USER, SUDO_UID, SUDO_GID environment variables. */
599 insert_env(format_env("SUDO_USER", user_name, VNULL), &env, 1);
600 easprintf(&cp, "SUDO_UID=%lu", (unsigned long) user_uid);
601 insert_env(cp, &env, 1);
602 easprintf(&cp, "SUDO_GID=%lu", (unsigned long) user_gid);
603 insert_env(cp, &env, 1);
609 insert_env_vars(envp, env_vars)
611 struct list_member *env_vars;
613 struct list_member *cur;
615 if (env_vars == NULL)
619 * Make sure we still own the environment and steal it back if not.
621 if (env.envp != envp) {
625 for (ep = envp; *ep != NULL; ep++)
628 if (evlen + 1 > env.env_size) {
630 env.env_size = evlen + 1 + 128;
631 env.envp = emalloc2(env.env_size, sizeof(char *));
633 memcpy(env.envp, envp, (evlen + 1) * sizeof(char *));
637 /* Add user-specified environment variables. */
638 for (cur = env_vars; cur != NULL; cur = cur->next)
639 insert_env(cur->value, &env, 1);
645 * Validate the list of environment variables passed in on the command
646 * line against env_delete, env_check, and env_keep.
647 * Calls log_error() if any specified variables are not allowed.
650 validate_env_vars(env_vars)
651 struct list_member *env_vars;
653 struct list_member *var;
654 char *eq, *bad = NULL;
655 size_t len, blen = 0, bsize = 0;
658 for (var = env_vars; var != NULL; var = var->next) {
660 if (!user_is_exempt() && strncmp(var->value, "PATH=", 5) == 0) {
665 okvar = matches_env_check(var->value);
667 okvar = matches_env_keep(var->value);
669 okvar = matches_env_delete(var->value) == FALSE;
671 okvar = matches_env_check(var->value) != FALSE;
673 if (okvar == FALSE) {
674 /* Not allowed, add to error string, allocating as needed. */
675 if ((eq = strchr(var->value, '=')) != NULL)
677 len = strlen(var->value) + 2;
678 if (blen + len >= bsize) {
681 } while (blen + len >= bsize);
682 bad = erealloc(bad, bsize);
685 strlcat(bad, var->value, bsize);
686 strlcat(bad, ", ", bsize);
693 bad[blen - 2] = '\0'; /* remove trailing ", " */
695 "sorry, you are not allowed to set the following environment variables: %s", bad);
704 struct list_member *cur;
707 /* Fill in the "env_delete" list. */
708 for (p = initial_badenv_table; *p; p++) {
709 cur = emalloc(sizeof(struct list_member));
710 cur->value = estrdup(*p);
711 cur->next = def_env_delete;
712 def_env_delete = cur;
715 /* Fill in the "env_check" list. */
716 for (p = initial_checkenv_table; *p; p++) {
717 cur = emalloc(sizeof(struct list_member));
718 cur->value = estrdup(*p);
719 cur->next = def_env_check;
723 /* Fill in the "env_keep" list. */
724 for (p = initial_keepenv_table; *p; p++) {
725 cur = emalloc(sizeof(struct list_member));
726 cur->value = estrdup(*p);
727 cur->next = def_env_keep;