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[] = {
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[] = {
218 * Given a variable and value, allocate and format an environment string.
222 format_env(char *var, ...)
224 format_env(var, va_alist)
239 esize = strlen(var) + 2;
240 while ((val = va_arg(ap, char *)) != NULL)
241 esize += strlen(val);
243 estring = (char *) emalloc(esize);
245 /* Store variable name and the '=' separator. */
246 if (strlcpy(estring, var, esize) >= esize ||
247 strlcat(estring, "=", esize) >= esize) {
249 errx(1, "internal error, format_env() overflow");
252 /* Now store the variable's value (if any) */
258 while ((val = va_arg(ap, char *)) != NULL) {
259 if (strlcat(estring, val, esize) >= esize)
260 errx(1, "internal error, format_env() overflow");
268 * Insert str into e->envp, assumes str has an '=' in it.
271 insert_env(str, e, dupcheck)
273 struct environment *e;
279 /* Make sure there is room for the new entry plus a NULL. */
280 if (e->env_len + 2 > e->env_size) {
282 e->envp = erealloc3(e->envp, e->env_size, sizeof(char *));
286 varlen = (strchr(str, '=') - str) + 1;
288 for (nep = e->envp; *nep; nep++) {
289 if (strncmp(str, *nep, varlen) == 0) {
295 nep = e->envp + e->env_len;
303 * Check the env_delete blacklist.
304 * Returns TRUE if the variable was found, else false.
307 matches_env_delete(var)
310 struct list_member *cur;
312 int iswild, match = FALSE;
314 /* Skip anything listed in env_delete. */
315 for (cur = def_env_delete; cur; cur = cur->next) {
316 len = strlen(cur->value);
317 /* Deal with '*' wildcard */
318 if (cur->value[len - 1] == '*') {
323 if (strncmp(cur->value, var, len) == 0 &&
324 (iswild || var[len] == '=')) {
333 * Apply the env_check list.
334 * Returns TRUE if the variable is allowed, FALSE if denied
338 matches_env_check(var)
341 struct list_member *cur;
343 int iswild, keepit = -1;
345 for (cur = def_env_check; cur; cur = cur->next) {
346 len = strlen(cur->value);
347 /* Deal with '*' wildcard */
348 if (cur->value[len - 1] == '*') {
353 if (strncmp(cur->value, var, len) == 0 &&
354 (iswild || var[len] == '=')) {
355 keepit = !strpbrk(var, "/%");
363 * Check the env_keep list.
364 * Returns TRUE if the variable is allowed else FALSE.
367 matches_env_keep(var)
370 struct list_member *cur;
372 int iswild, keepit = FALSE;
374 for (cur = def_env_keep; cur; cur = cur->next) {
375 len = strlen(cur->value);
376 /* Deal with '*' wildcard */
377 if (cur->value[len - 1] == '*') {
382 if (strncmp(cur->value, var, len) == 0 &&
383 (iswild || var[len] == '=')) {
392 * Build a new environment and ether clear potentially dangerous
393 * variables from the old one or start with a clean slate.
394 * Also adds sudo-specific variables (SUDO_*).
397 rebuild_env(envp, sudo_mode, noexec)
402 char **ep, *cp, *ps1;
406 * Either clean out the environment or reset to a safe default.
410 memset(&env, 0, sizeof(env));
412 /* Pull in vars we want to keep from the old environment. */
413 for (ep = envp; *ep; ep++) {
416 /* Skip variables with values beginning with () (bash functions) */
417 if ((cp = strchr(*ep, '=')) != NULL) {
418 if (strncmp(cp, "=() ", 3) == 0)
423 * First check certain variables for '%' and '/' characters.
424 * If no match there, check the keep list.
425 * If nothing matched, we remove it from the environment.
427 keepit = matches_env_check(*ep);
429 keepit = matches_env_keep(*ep);
431 if (!strncmp (*ep, "DISPLAY=",8)
432 || !strncmp (*ep, "XAUTHORITY=", 11)
433 || !strncmp (*ep, "XAUTHORIZATION=", 15)
434 || !strncmp (*ep, "XAPPLRESDIR=", 12)
435 || !strncmp (*ep, "XFILESEARCHPATH=", 16)
436 || !strncmp (*ep, "XUSERFILESEARCHPATH=", 20)
437 || !strncmp (*ep, "LANG=", 5)
438 || !strncmp (*ep, "LANGUAGE=", 9)
439 || !strncmp (*ep, "LC_", 3))
442 /* For SUDO_PS1 -> PS1 conversion. */
443 if (strncmp(*ep, "SUDO_PS1=", 8) == 0)
447 /* Preserve variable. */
450 if (strncmp(*ep, "HOME=", 5) == 0)
451 SET(didvar, DID_HOME);
454 if (strncmp(*ep, "LOGNAME=", 8) == 0)
455 SET(didvar, DID_LOGNAME);
458 if (strncmp(*ep, "PATH=", 5) == 0)
459 SET(didvar, DID_PATH);
462 if (strncmp(*ep, "SHELL=", 6) == 0)
463 SET(didvar, DID_SHELL);
466 if (strncmp(*ep, "TERM=", 5) == 0)
467 SET(didvar, DID_TERM);
470 if (strncmp(*ep, "USER=", 5) == 0)
471 SET(didvar, DID_USER);
472 if (strncmp(*ep, "USERNAME=", 5) == 0)
473 SET(didvar, DID_USERNAME);
476 insert_env(*ep, &env, 0);
479 didvar |= didvar << 8; /* convert DID_* to KEPT_* */
482 * Add in defaults. In -i mode these come from the runas user,
483 * otherwise they may be from the user's environment (depends
484 * on sudoers options).
486 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
487 insert_env(format_env("HOME", runas_pw->pw_dir, VNULL), &env,
488 ISSET(didvar, DID_HOME));
489 insert_env(format_env("SHELL", runas_pw->pw_shell, VNULL), &env,
490 ISSET(didvar, DID_SHELL));
491 insert_env(format_env("LOGNAME", runas_pw->pw_name, VNULL), &env,
492 ISSET(didvar, DID_LOGNAME));
493 insert_env(format_env("USER", runas_pw->pw_name, VNULL), &env,
494 ISSET(didvar, DID_USER));
495 insert_env(format_env("USERNAME", runas_pw->pw_name, VNULL), &env,
496 ISSET(didvar, DID_USERNAME));
498 if (!ISSET(didvar, DID_HOME))
499 insert_env(format_env("HOME", user_dir, VNULL), &env, 0);
500 if (!ISSET(didvar, DID_SHELL))
501 insert_env(format_env("SHELL", sudo_user.pw->pw_shell, VNULL),
503 if (!ISSET(didvar, DID_LOGNAME))
504 insert_env(format_env("LOGNAME", user_name, VNULL), &env, 0);
505 if (!ISSET(didvar, DID_USER))
506 insert_env(format_env("USER", user_name, VNULL), &env, 0);
507 if (!ISSET(didvar, DID_USERNAME))
508 insert_env(format_env("USERNAME", user_name, VNULL), &env, 0);
512 * Copy envp entries as long as they don't match env_delete or
515 for (ep = envp; *ep; ep++) {
518 /* Skip variables with values beginning with () (bash functions) */
519 if ((cp = strchr(*ep, '=')) != NULL) {
520 if (strncmp(cp, "=() ", 3) == 0)
525 * First check variables against the blacklist in env_delete.
526 * If no match there check for '%' and '/' characters.
528 okvar = matches_env_delete(*ep) != TRUE;
530 okvar = matches_env_check(*ep) != FALSE;
533 if (strncmp(*ep, "SUDO_PS1=", 9) == 0)
535 else if (strncmp(*ep, "PATH=", 5) == 0)
536 SET(didvar, DID_PATH);
537 else if (strncmp(*ep, "TERM=", 5) == 0)
538 SET(didvar, DID_TERM);
539 insert_env(*ep, &env, 0);
545 /* Replace the PATH envariable with a secure one. */
546 if (!user_is_exempt()) {
547 insert_env(format_env("PATH", SECURE_PATH, VNULL), &env, 1);
548 SET(didvar, DID_PATH);
552 /* Set $USER, $LOGNAME and $USERNAME to target if "set_logname" is true. */
553 if (def_set_logname && runas_pw->pw_name) {
554 if (!ISSET(didvar, KEPT_LOGNAME))
555 insert_env(format_env("LOGNAME", runas_pw->pw_name, VNULL), &env, 1);
556 if (!ISSET(didvar, KEPT_USER))
557 insert_env(format_env("USER", runas_pw->pw_name, VNULL), &env, 1);
558 if (!ISSET(didvar, KEPT_USERNAME))
559 insert_env(format_env("USERNAME", runas_pw->pw_name, VNULL), &env, 1);
562 /* Set $HOME for `sudo -H'. Only valid at PERM_FULL_RUNAS. */
563 if (runas_pw->pw_dir) {
564 if (ISSET(sudo_mode, MODE_RESET_HOME) ||
565 (ISSET(sudo_mode, MODE_RUN) && (def_always_set_home ||
566 (ISSET(sudo_mode, MODE_SHELL) && def_set_home))))
567 insert_env(format_env("HOME", runas_pw->pw_dir, VNULL), &env, 1);
570 /* Provide default values for $TERM and $PATH if they are not set. */
571 if (!ISSET(didvar, DID_TERM))
572 insert_env("TERM=unknown", &env, 0);
573 if (!ISSET(didvar, DID_PATH))
574 insert_env(format_env("PATH", _PATH_DEFPATH, VNULL), &env, 0);
577 * Preload a noexec file? For a list of LD_PRELOAD-alikes, see
578 * http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html
579 * XXX - should prepend to original value, if any
581 if (noexec && def_noexec_file != NULL) {
582 #if defined(__darwin__) || defined(__APPLE__)
583 insert_env(format_env("DYLD_INSERT_LIBRARIES", def_noexec_file, VNULL),
585 insert_env(format_env("DYLD_FORCE_FLAT_NAMESPACE", VNULL), &env, 1);
587 # if defined(__osf__) || defined(__sgi)
588 insert_env(format_env("_RLD_LIST", def_noexec_file, ":DEFAULT", VNULL),
592 insert_env(format_env("LDR_PRELOAD", def_noexec_file, VNULL), &env, 1);
594 insert_env(format_env("LD_PRELOAD", def_noexec_file, VNULL), &env, 1);
596 # endif /* __osf__ || __sgi */
597 #endif /* __darwin__ || __APPLE__ */
600 /* Set PS1 if SUDO_PS1 is set. */
602 insert_env(ps1, &env, 1);
604 /* Add the SUDO_COMMAND envariable (cmnd + args). */
606 insert_env(format_env("SUDO_COMMAND", user_cmnd, " ", user_args, VNULL),
609 insert_env(format_env("SUDO_COMMAND", user_cmnd, VNULL), &env, 1);
611 /* Add the SUDO_USER, SUDO_UID, SUDO_GID environment variables. */
612 insert_env(format_env("SUDO_USER", user_name, VNULL), &env, 1);
613 easprintf(&cp, "SUDO_UID=%lu", (unsigned long) user_uid);
614 insert_env(cp, &env, 1);
615 easprintf(&cp, "SUDO_GID=%lu", (unsigned long) user_gid);
616 insert_env(cp, &env, 1);
622 insert_env_vars(envp, env_vars)
624 struct list_member *env_vars;
626 struct list_member *cur;
628 if (env_vars == NULL)
632 * Make sure we still own the environment and steal it back if not.
634 if (env.envp != envp) {
638 for (ep = envp; *ep != NULL; ep++)
641 if (evlen + 1 > env.env_size) {
643 env.env_size = evlen + 1 + 128;
644 env.envp = emalloc2(env.env_size, sizeof(char *));
646 memcpy(env.envp, envp, (evlen + 1) * sizeof(char *));
650 /* Add user-specified environment variables. */
651 for (cur = env_vars; cur != NULL; cur = cur->next)
652 insert_env(cur->value, &env, 1);
658 * Validate the list of environment variables passed in on the command
659 * line against env_delete, env_check, and env_keep.
660 * Calls log_error() if any specified variables are not allowed.
663 validate_env_vars(env_vars)
664 struct list_member *env_vars;
666 struct list_member *var;
667 char *eq, *bad = NULL;
668 size_t len, blen = 0, bsize = 0;
671 for (var = env_vars; var != NULL; var = var->next) {
673 if (!user_is_exempt() && strncmp(var->value, "PATH=", 5) == 0) {
678 okvar = matches_env_check(var->value);
680 okvar = matches_env_keep(var->value);
682 okvar = matches_env_delete(var->value) == FALSE;
684 okvar = matches_env_check(var->value) != FALSE;
686 if (okvar == FALSE) {
687 /* Not allowed, add to error string, allocating as needed. */
688 if ((eq = strchr(var->value, '=')) != NULL)
690 len = strlen(var->value) + 2;
691 if (blen + len >= bsize) {
694 } while (blen + len >= bsize);
695 bad = erealloc(bad, bsize);
698 strlcat(bad, var->value, bsize);
699 strlcat(bad, ", ", bsize);
706 bad[blen - 2] = '\0'; /* remove trailing ", " */
708 "sorry, you are not allowed to set the following environment variables: %s", bad);
717 struct list_member *cur;
720 /* Fill in the "env_delete" list. */
721 for (p = initial_badenv_table; *p; p++) {
722 cur = emalloc(sizeof(struct list_member));
723 cur->value = estrdup(*p);
724 cur->next = def_env_delete;
725 def_env_delete = cur;
728 /* Fill in the "env_check" list. */
729 for (p = initial_checkenv_table; *p; p++) {
730 cur = emalloc(sizeof(struct list_member));
731 cur->value = estrdup(*p);
732 cur->next = def_env_check;
736 /* Fill in the "env_keep" list. */
737 for (p = initial_keepenv_table; *p; p++) {
738 cur = emalloc(sizeof(struct list_member));
739 cur->value = estrdup(*p);
740 cur->next = def_env_keep;