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[] = {
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[] = {
215 * Given a variable and value, allocate and format an environment string.
219 format_env(char *var, ...)
221 format_env(var, va_alist)
236 esize = strlen(var) + 2;
237 while ((val = va_arg(ap, char *)) != NULL)
238 esize += strlen(val);
240 estring = (char *) emalloc(esize);
242 /* Store variable name and the '=' separator. */
243 if (strlcpy(estring, var, esize) >= esize ||
244 strlcat(estring, "=", esize) >= esize) {
246 errx(1, "internal error, format_env() overflow");
249 /* Now store the variable's value (if any) */
255 while ((val = va_arg(ap, char *)) != NULL) {
256 if (strlcat(estring, val, esize) >= esize)
257 errx(1, "internal error, format_env() overflow");
265 * Insert str into e->envp, assumes str has an '=' in it.
268 insert_env(str, e, dupcheck)
270 struct environment *e;
276 /* Make sure there is room for the new entry plus a NULL. */
277 if (e->env_len + 2 > e->env_size) {
279 e->envp = erealloc3(e->envp, e->env_size, sizeof(char *));
283 varlen = (strchr(str, '=') - str) + 1;
285 for (nep = e->envp; *nep; nep++) {
286 if (strncmp(str, *nep, varlen) == 0) {
292 nep = e->envp + e->env_len;
300 * Check the env_delete blacklist.
301 * Returns TRUE if the variable was found, else false.
304 matches_env_delete(var)
307 struct list_member *cur;
309 int iswild, match = FALSE;
311 /* Skip anything listed in env_delete. */
312 for (cur = def_env_delete; cur; cur = cur->next) {
313 len = strlen(cur->value);
314 /* Deal with '*' wildcard */
315 if (cur->value[len - 1] == '*') {
320 if (strncmp(cur->value, var, len) == 0 &&
321 (iswild || var[len] == '=')) {
330 * Apply the env_check list.
331 * Returns TRUE if the variable is allowed, FALSE if denied
335 matches_env_check(var)
338 struct list_member *cur;
340 int iswild, keepit = -1;
342 for (cur = def_env_check; cur; cur = cur->next) {
343 len = strlen(cur->value);
344 /* Deal with '*' wildcard */
345 if (cur->value[len - 1] == '*') {
350 if (strncmp(cur->value, var, len) == 0 &&
351 (iswild || var[len] == '=')) {
352 keepit = !strpbrk(var, "/%");
360 * Check the env_keep list.
361 * Returns TRUE if the variable is allowed else FALSE.
364 matches_env_keep(var)
367 struct list_member *cur;
369 int iswild, keepit = FALSE;
371 for (cur = def_env_keep; cur; cur = cur->next) {
372 len = strlen(cur->value);
373 /* Deal with '*' wildcard */
374 if (cur->value[len - 1] == '*') {
379 if (strncmp(cur->value, var, len) == 0 &&
380 (iswild || var[len] == '=')) {
389 * Build a new environment and ether clear potentially dangerous
390 * variables from the old one or start with a clean slate.
391 * Also adds sudo-specific variables (SUDO_*).
394 rebuild_env(envp, sudo_mode, noexec)
399 char **ep, *cp, *ps1;
403 * Either clean out the environment or reset to a safe default.
407 memset(&env, 0, sizeof(env));
409 /* Pull in vars we want to keep from the old environment. */
410 for (ep = envp; *ep; ep++) {
413 /* Skip variables with values beginning with () (bash functions) */
414 if ((cp = strchr(*ep, '=')) != NULL) {
415 if (strncmp(cp, "=() ", 3) == 0)
420 * First check certain variables for '%' and '/' characters.
421 * If no match there, check the keep list.
422 * If nothing matched, we remove it from the environment.
424 keepit = matches_env_check(*ep);
426 keepit = matches_env_keep(*ep);
428 /* For SUDO_PS1 -> PS1 conversion. */
429 if (strncmp(*ep, "SUDO_PS1=", 8) == 0)
433 /* Preserve variable. */
436 if (strncmp(*ep, "HOME=", 5) == 0)
437 SET(didvar, DID_HOME);
440 if (strncmp(*ep, "LOGNAME=", 8) == 0)
441 SET(didvar, DID_LOGNAME);
444 if (strncmp(*ep, "PATH=", 5) == 0)
445 SET(didvar, DID_PATH);
448 if (strncmp(*ep, "SHELL=", 6) == 0)
449 SET(didvar, DID_SHELL);
452 if (strncmp(*ep, "TERM=", 5) == 0)
453 SET(didvar, DID_TERM);
456 if (strncmp(*ep, "USER=", 5) == 0)
457 SET(didvar, DID_USER);
458 if (strncmp(*ep, "USERNAME=", 5) == 0)
459 SET(didvar, DID_USERNAME);
462 insert_env(*ep, &env, 0);
465 didvar |= didvar << 8; /* convert DID_* to KEPT_* */
468 * Add in defaults. In -i mode these come from the runas user,
469 * otherwise they may be from the user's environment (depends
470 * on sudoers options).
472 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
473 insert_env(format_env("HOME", runas_pw->pw_dir, VNULL), &env,
474 ISSET(didvar, DID_HOME));
475 insert_env(format_env("SHELL", runas_pw->pw_shell, VNULL), &env,
476 ISSET(didvar, DID_SHELL));
477 insert_env(format_env("LOGNAME", runas_pw->pw_name, VNULL), &env,
478 ISSET(didvar, DID_LOGNAME));
479 insert_env(format_env("USER", runas_pw->pw_name, VNULL), &env,
480 ISSET(didvar, DID_USER));
481 insert_env(format_env("USERNAME", runas_pw->pw_name, VNULL), &env,
482 ISSET(didvar, DID_USERNAME));
484 if (!ISSET(didvar, DID_HOME))
485 insert_env(format_env("HOME", user_dir, VNULL), &env, 0);
486 if (!ISSET(didvar, DID_SHELL))
487 insert_env(format_env("SHELL", sudo_user.pw->pw_shell, VNULL),
489 if (!ISSET(didvar, DID_LOGNAME))
490 insert_env(format_env("LOGNAME", user_name, VNULL), &env, 0);
491 if (!ISSET(didvar, DID_USER))
492 insert_env(format_env("USER", user_name, VNULL), &env, 0);
493 if (!ISSET(didvar, DID_USERNAME))
494 insert_env(format_env("USERNAME", user_name, VNULL), &env, 0);
498 * Copy envp entries as long as they don't match env_delete or
501 for (ep = envp; *ep; ep++) {
504 /* Skip variables with values beginning with () (bash functions) */
505 if ((cp = strchr(*ep, '=')) != NULL) {
506 if (strncmp(cp, "=() ", 3) == 0)
511 * First check variables against the blacklist in env_delete.
512 * If no match there check for '%' and '/' characters.
514 okvar = matches_env_delete(*ep) != TRUE;
516 okvar = matches_env_check(*ep) != FALSE;
519 if (strncmp(*ep, "SUDO_PS1=", 9) == 0)
521 else if (strncmp(*ep, "PATH=", 5) == 0)
522 SET(didvar, DID_PATH);
523 else if (strncmp(*ep, "TERM=", 5) == 0)
524 SET(didvar, DID_TERM);
525 insert_env(*ep, &env, 0);
531 /* Replace the PATH envariable with a secure one. */
532 if (!user_is_exempt()) {
533 insert_env(format_env("PATH", SECURE_PATH, VNULL), &env, 1);
534 SET(didvar, DID_PATH);
538 /* Set $USER, $LOGNAME and $USERNAME to target if "set_logname" is true. */
539 if (def_set_logname && runas_pw->pw_name) {
540 if (!ISSET(didvar, KEPT_LOGNAME))
541 insert_env(format_env("LOGNAME", runas_pw->pw_name, VNULL), &env, 1);
542 if (!ISSET(didvar, KEPT_USER))
543 insert_env(format_env("USER", runas_pw->pw_name, VNULL), &env, 1);
544 if (!ISSET(didvar, KEPT_USERNAME))
545 insert_env(format_env("USERNAME", runas_pw->pw_name, VNULL), &env, 1);
548 /* Set $HOME for `sudo -H'. Only valid at PERM_FULL_RUNAS. */
549 if (runas_pw->pw_dir) {
550 if (ISSET(sudo_mode, MODE_RESET_HOME) ||
551 (ISSET(sudo_mode, MODE_RUN) && (def_always_set_home ||
552 (ISSET(sudo_mode, MODE_SHELL) && def_set_home))))
553 insert_env(format_env("HOME", runas_pw->pw_dir, VNULL), &env, 1);
556 /* Provide default values for $TERM and $PATH if they are not set. */
557 if (!ISSET(didvar, DID_TERM))
558 insert_env("TERM=unknown", &env, 0);
559 if (!ISSET(didvar, DID_PATH))
560 insert_env(format_env("PATH", _PATH_DEFPATH, VNULL), &env, 0);
563 * Preload a noexec file? For a list of LD_PRELOAD-alikes, see
564 * http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html
565 * XXX - should prepend to original value, if any
567 if (noexec && def_noexec_file != NULL) {
568 #if defined(__darwin__) || defined(__APPLE__)
569 insert_env(format_env("DYLD_INSERT_LIBRARIES", def_noexec_file, VNULL),
571 insert_env(format_env("DYLD_FORCE_FLAT_NAMESPACE", VNULL), &env, 1);
573 # if defined(__osf__) || defined(__sgi)
574 insert_env(format_env("_RLD_LIST", def_noexec_file, ":DEFAULT", VNULL),
578 insert_env(format_env("LDR_PRELOAD", def_noexec_file, VNULL), &env, 1);
580 insert_env(format_env("LD_PRELOAD", def_noexec_file, VNULL), &env, 1);
582 # endif /* __osf__ || __sgi */
583 #endif /* __darwin__ || __APPLE__ */
586 /* Set PS1 if SUDO_PS1 is set. */
588 insert_env(ps1, &env, 1);
590 /* Add the SUDO_COMMAND envariable (cmnd + args). */
592 insert_env(format_env("SUDO_COMMAND", user_cmnd, " ", user_args, VNULL),
595 insert_env(format_env("SUDO_COMMAND", user_cmnd, VNULL), &env, 1);
597 /* Add the SUDO_USER, SUDO_UID, SUDO_GID environment variables. */
598 insert_env(format_env("SUDO_USER", user_name, VNULL), &env, 1);
599 easprintf(&cp, "SUDO_UID=%lu", (unsigned long) user_uid);
600 insert_env(cp, &env, 1);
601 easprintf(&cp, "SUDO_GID=%lu", (unsigned long) user_gid);
602 insert_env(cp, &env, 1);
608 insert_env_vars(envp, env_vars)
610 struct list_member *env_vars;
612 struct list_member *cur;
614 if (env_vars == NULL)
618 * Make sure we still own the environment and steal it back if not.
620 if (env.envp != envp) {
624 for (ep = envp; *ep != NULL; ep++)
627 if (evlen + 1 > env.env_size) {
629 env.env_size = evlen + 1 + 128;
630 env.envp = emalloc2(env.env_size, sizeof(char *));
632 memcpy(env.envp, envp, (evlen + 1) * sizeof(char *));
636 /* Add user-specified environment variables. */
637 for (cur = env_vars; cur != NULL; cur = cur->next)
638 insert_env(cur->value, &env, 1);
644 * Validate the list of environment variables passed in on the command
645 * line against env_delete, env_check, and env_keep.
646 * Calls log_error() if any specified variables are not allowed.
649 validate_env_vars(env_vars)
650 struct list_member *env_vars;
652 struct list_member *var;
653 char *eq, *bad = NULL;
654 size_t len, blen = 0, bsize = 0;
657 for (var = env_vars; var != NULL; var = var->next) {
659 if (!user_is_exempt() && strncmp(var->value, "PATH=", 5) == 0) {
664 okvar = matches_env_check(var->value);
666 okvar = matches_env_keep(var->value);
668 okvar = matches_env_delete(var->value) == FALSE;
670 okvar = matches_env_check(var->value) != FALSE;
672 if (okvar == FALSE) {
673 /* Not allowed, add to error string, allocating as needed. */
674 if ((eq = strchr(var->value, '=')) != NULL)
676 len = strlen(var->value) + 2;
677 if (blen + len >= bsize) {
680 } while (blen + len >= bsize);
681 bad = erealloc(bad, bsize);
684 strlcat(bad, var->value, bsize);
685 strlcat(bad, ", ", bsize);
692 bad[blen - 2] = '\0'; /* remove trailing ", " */
694 "sorry, you are not allowed to set the following environment variables: %s", bad);
703 struct list_member *cur;
706 /* Fill in the "env_delete" list. */
707 for (p = initial_badenv_table; *p; p++) {
708 cur = emalloc(sizeof(struct list_member));
709 cur->value = estrdup(*p);
710 cur->next = def_env_delete;
711 def_env_delete = cur;
714 /* Fill in the "env_check" list. */
715 for (p = initial_checkenv_table; *p; p++) {
716 cur = emalloc(sizeof(struct list_member));
717 cur->value = estrdup(*p);
718 cur->next = def_env_check;
722 /* Fill in the "env_keep" list. */
723 for (p = initial_keepenv_table; *p; p++) {
724 cur = emalloc(sizeof(struct list_member));
725 cur->value = estrdup(*p);
726 cur->next = def_env_keep;