2 * Copyright (c) 2000-2005, 2007-2010
3 * Todd C. Miller <Todd.Miller@courtesan.com>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 * Sponsored in part by the Defense Advanced Research Projects
18 * Agency (DARPA) and Air Force Research Laboratory, Air Force
19 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
24 #include <sys/types.h>
25 #include <sys/param.h>
35 #endif /* STDC_HEADERS */
38 #endif /* HAVE_STRING_H */
41 #endif /* HAVE_STRINGS_H */
44 #endif /* HAVE_UNISTD_H */
52 * Flags used in rebuild_env()
55 #define DID_TERM 0x0001
57 #define DID_PATH 0x0002
59 #define DID_HOME 0x0004
61 #define DID_SHELL 0x0008
63 #define DID_LOGNAME 0x0010
65 #define DID_USER 0x0020
67 #define DID_USERNAME 0x0040
69 #define DID_MAIL 0x0080
71 #define DID_MAX 0x00ff
74 #define KEPT_TERM 0x0100
76 #define KEPT_PATH 0x0200
78 #define KEPT_HOME 0x0400
80 #define KEPT_SHELL 0x0800
82 #define KEPT_LOGNAME 0x1000
84 #define KEPT_USER 0x2000
86 #define KEPT_USERNAME 0x4000
88 #define KEPT_MAIL 0x8000
90 #define KEPT_MAX 0xff00
93 char **envp; /* pointer to the new environment */
94 size_t env_size; /* size of new_environ in char **'s */
95 size_t env_len; /* number of slots used, not counting NULL */
96 int owned; /* do we own envp or is it the system's? */
102 static void sudo_setenv __P((const char *, const char *, int));
103 static void sudo_putenv __P((char *, int, int));
105 extern char **environ; /* global environment */
108 * Copy of the sudo-managed environment.
110 static struct environment env;
113 * Default table of "bad" variables to remove from the environment.
114 * XXX - how to omit TERMCAP if it starts with '/'?
116 static const char *initial_badenv_table[] = {
141 #endif /* HAVE_KERB4 */
145 #endif /* HAVE_KERB5 */
150 #endif /* HAVE_SECURID */
151 "TERMINFO", /* terminfo, exclusive path to terminfo files */
152 "TERMINFO_DIRS", /* terminfo, path(s) to terminfo files */
153 "TERMPATH", /* termcap, path(s) to termcap files */
154 "TERMCAP", /* XXX - only if it starts with '/' */
155 "ENV", /* ksh, file to source before script runs */
156 "BASH_ENV", /* bash, file to source before script runs */
157 "PS4", /* bash, prefix for lines in xtrace mode */
158 "GLOBIGNORE", /* bash, globbing patterns to ignore */
159 "SHELLOPTS", /* bash, extra command line options */
160 "JAVA_TOOL_OPTIONS", /* java, extra command line options */
161 "PERLIO_DEBUG ", /* perl, debugging output file */
162 "PERLLIB", /* perl, search path for modules/includes */
163 "PERL5LIB", /* perl 5, search path for modules/includes */
164 "PERL5OPT", /* perl 5, extra command line options */
165 "PERL5DB", /* perl 5, command used to load debugger */
166 "FPATH", /* ksh, search path for functions */
167 "NULLCMD", /* zsh, command for null file redirection */
168 "READNULLCMD", /* zsh, command for null file redirection */
169 "ZDOTDIR", /* zsh, search path for dot files */
170 "TMPPREFIX", /* zsh, prefix for temporary files */
171 "PYTHONHOME", /* python, module search path */
172 "PYTHONPATH", /* python, search path */
173 "PYTHONINSPECT", /* python, allow inspection */
174 "PYTHONUSERBASE", /* python, per user site-packages directory */
175 "RUBYLIB", /* ruby, library load path */
176 "RUBYOPT", /* ruby, extra command line options */
181 * Default table of variables to check for '%' and '/' characters.
183 static const char *initial_checkenv_table[] = {
194 * Default table of variables to preserve in the environment.
196 static const char *initial_keepenv_table[] = {
215 * Initialize env based on envp.
224 for (ep = environ; *ep != NULL; ep++)
226 len = (size_t)(ep - environ);
230 * If we are already initialized due to lazy init (usualy via getenv())
231 * we need to avoid calling malloc() as it may call getenv() itself.
236 } else if (!env.owned) {
238 env.env_size = len + 1 + 128;
239 env.envp = emalloc2(env.env_size, sizeof(char *));
241 memset(env.envp, 0, env.env_size * sizeof(char *));
243 memcpy(env.envp, environ, len * sizeof(char *));
244 env.envp[len] = '\0';
256 * Similar to setenv(3) but operates on sudo's private copy of the environment
257 * (not environ) and it always overwrites. The dupcheck param determines
258 * whether we need to verify that the variable is not already set.
261 sudo_setenv(var, val, dupcheck)
269 esize = strlen(var) + 1 + strlen(val) + 1;
270 estring = emalloc(esize);
272 /* Build environment string and insert it. */
273 if (strlcpy(estring, var, esize) >= esize ||
274 strlcat(estring, "=", esize) >= esize ||
275 strlcat(estring, val, esize) >= esize) {
277 errorx(1, "internal error, sudo_setenv() overflow");
279 sudo_putenv(estring, dupcheck, TRUE);
283 * Version of getenv(3) that uses our own environ pointer.
290 size_t vlen = strlen(var);
292 if (env.envp == NULL)
295 for (ev = env.envp; (cp = *ev) != NULL; ev++) {
296 if (strncmp(var, cp, vlen) == 0 && cp[vlen] == '=')
297 return cp + vlen + 1;
303 * Version of setenv(3) that uses our own environ pointer.
306 setenv(var, val, overwrite)
315 if (!var || *var == '\0') {
320 if (env.envp == NULL)
324 * POSIX says a var name with '=' is an error but BSD
325 * just ignores the '=' and anything after it.
327 for (cp = var; *cp && *cp != '='; cp++)
329 esize = (size_t)(cp - var) + 2;
331 esize += strlen(val); /* glibc treats a NULL val as "" */
334 /* Allocate and fill in estring. */
335 estring = ep = emalloc(esize);
336 for (cp = var; *cp && *cp != '='; cp++)
340 for (cp = val; *cp; cp++)
346 if (env.envp[env.env_len] != NULL)
347 errorx(1, "setenv: corrupted envp, len mismatch");
349 sudo_putenv(estring, TRUE, overwrite);
354 * Version of unsetenv(3) that uses our own environ pointer.
367 if (var == NULL || *var == '\0' || strchr(var, '=') != NULL) {
376 if (env.envp == NULL)
380 if (env.envp[env.env_len] != NULL)
381 errorx(1, "unsetenv: corrupted envp, len mismatch");
385 for (ep = env.envp; *ep != NULL;) {
386 if (strncmp(var, *ep, len) == 0 && (*ep)[len] == '=') {
387 /* Found it; shift remainder + NULL over by one. */
389 while ((*cur = *(cur + 1)) != NULL)
391 /* Keep going, could be multiple instances of the var. */
396 env.env_len = ep - env.envp;
397 #ifndef UNSETENV_VOID
403 * Version of putenv(3) that uses our own environ pointer.
407 putenv(const char *string)
413 if (env.envp == NULL)
416 if (strchr(string, '=') == NULL) {
421 if (env.envp[env.env_len] != NULL)
422 errorx(1, "putenv: corrupted envp, len mismatch");
424 sudo_putenv((char *)string, TRUE, TRUE);
429 * Similar to putenv(3) but operates on sudo's private copy of the
430 * environment (not environ) and it always overwrites. The dupcheck param
431 * determines whether we need to verify that the variable is not already set.
432 * Will only overwrite an existing variable if overwrite is set.
435 sudo_putenv(str, dupcheck, overwrite)
444 /* Make sure there is room for the new entry plus a NULL. */
445 if (env.env_len + 2 > env.env_size) {
448 env.envp = erealloc3(env.envp, env.env_size, sizeof(char *));
450 /* We don't own env.envp, allocate a new one. */
451 ep = emalloc2(env.env_size, sizeof(char *));
452 memcpy(ep, env.envp, env.env_size * sizeof(char *));
457 memset(env.envp + env.env_len, 0,
458 (env.env_size - env.env_len) * sizeof(char *));
463 if (env.envp[env.env_len] != NULL)
464 errorx(1, "sudo_putenv: corrupted envp, len mismatch");
468 len = (strchr(str, '=') - str) + 1;
469 for (ep = env.envp; !found && *ep != NULL; ep++) {
470 if (strncmp(str, *ep, len) == 0) {
476 /* Prune out duplicate variables. */
477 if (found && overwrite) {
478 while (*ep != NULL) {
479 if (strncmp(str, *ep, len) == 0) {
481 while ((*cur = *(cur + 1)) != NULL)
487 env.env_len = ep - env.envp;
492 ep = env.envp + env.env_len;
500 * Check the env_delete blacklist.
501 * Returns TRUE if the variable was found, else false.
504 matches_env_delete(var)
507 struct list_member *cur;
509 int iswild, match = FALSE;
511 /* Skip anything listed in env_delete. */
512 for (cur = def_env_delete; cur; cur = cur->next) {
513 len = strlen(cur->value);
514 /* Deal with '*' wildcard */
515 if (cur->value[len - 1] == '*') {
520 if (strncmp(cur->value, var, len) == 0 &&
521 (iswild || var[len] == '=')) {
530 * Apply the env_check list.
531 * Returns TRUE if the variable is allowed, FALSE if denied
535 matches_env_check(var)
538 struct list_member *cur;
540 int iswild, keepit = -1;
542 for (cur = def_env_check; cur; cur = cur->next) {
543 len = strlen(cur->value);
544 /* Deal with '*' wildcard */
545 if (cur->value[len - 1] == '*') {
550 if (strncmp(cur->value, var, len) == 0 &&
551 (iswild || var[len] == '=')) {
552 keepit = !strpbrk(var, "/%");
560 * Check the env_keep list.
561 * Returns TRUE if the variable is allowed else FALSE.
564 matches_env_keep(var)
567 struct list_member *cur;
569 int iswild, keepit = FALSE;
571 for (cur = def_env_keep; cur; cur = cur->next) {
572 len = strlen(cur->value);
573 /* Deal with '*' wildcard */
574 if (cur->value[len - 1] == '*') {
579 if (strncmp(cur->value, var, len) == 0 &&
580 (iswild || var[len] == '=')) {
589 * Build a new environment and ether clear potentially dangerous
590 * variables from the old one or start with a clean slate.
591 * Also adds sudo-specific variables (SUDO_*).
597 char **old_envp, **ep, *cp, *ps1;
598 char idbuf[MAX_UID_T_LEN];
600 int reset_home = FALSE;
603 * Either clean out the environment or reset to a safe default.
610 env.envp = emalloc2(env.env_size, sizeof(char *));
612 memset(env.envp, 0, env.env_size * sizeof(char *));
615 /* Reset HOME based on target user if configured to. */
616 if (ISSET(sudo_mode, MODE_RUN)) {
617 if (def_always_set_home ||
618 ISSET(sudo_mode, MODE_RESET_HOME | MODE_LOGIN_SHELL) ||
619 (ISSET(sudo_mode, MODE_SHELL) && def_set_home))
623 if (def_env_reset || ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
624 /* Pull in vars we want to keep from the old environment. */
625 for (ep = old_envp; *ep; ep++) {
628 /* Skip variables with values beginning with () (bash functions) */
629 if ((cp = strchr(*ep, '=')) != NULL) {
630 if (strncmp(cp, "=() ", 3) == 0)
635 * First check certain variables for '%' and '/' characters.
636 * If no match there, check the keep list.
637 * If nothing matched, we remove it from the environment.
639 keepit = matches_env_check(*ep);
641 keepit = matches_env_keep(*ep);
643 /* For SUDO_PS1 -> PS1 conversion. */
644 if (strncmp(*ep, "SUDO_PS1=", 8) == 0)
648 /* Preserve variable. */
651 if (strncmp(*ep, "HOME=", 5) == 0)
652 SET(didvar, DID_HOME);
655 if (strncmp(*ep, "LOGNAME=", 8) == 0)
656 SET(didvar, DID_LOGNAME);
659 if (strncmp(*ep, "MAIL=", 5) == 0)
660 SET(didvar, DID_MAIL);
663 if (strncmp(*ep, "PATH=", 5) == 0)
664 SET(didvar, DID_PATH);
667 if (strncmp(*ep, "SHELL=", 6) == 0)
668 SET(didvar, DID_SHELL);
671 if (strncmp(*ep, "TERM=", 5) == 0)
672 SET(didvar, DID_TERM);
675 if (strncmp(*ep, "USER=", 5) == 0)
676 SET(didvar, DID_USER);
677 if (strncmp(*ep, "USERNAME=", 5) == 0)
678 SET(didvar, DID_USERNAME);
681 sudo_putenv(*ep, FALSE, FALSE);
684 didvar |= didvar << 8; /* convert DID_* to KEPT_* */
687 * Add in defaults. In -i mode these come from the runas user,
688 * otherwise they may be from the user's environment (depends
689 * on sudoers options).
691 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
692 sudo_setenv("SHELL", runas_pw->pw_shell, ISSET(didvar, DID_SHELL));
693 sudo_setenv("LOGNAME", runas_pw->pw_name,
694 ISSET(didvar, DID_LOGNAME));
695 sudo_setenv("USER", runas_pw->pw_name, ISSET(didvar, DID_USER));
696 sudo_setenv("USERNAME", runas_pw->pw_name,
697 ISSET(didvar, DID_USERNAME));
699 if (!ISSET(didvar, DID_SHELL))
700 sudo_setenv("SHELL", sudo_user.pw->pw_shell, FALSE);
701 if (!ISSET(didvar, DID_LOGNAME))
702 sudo_setenv("LOGNAME", user_name, FALSE);
703 if (!ISSET(didvar, DID_USER))
704 sudo_setenv("USER", user_name, FALSE);
705 if (!ISSET(didvar, DID_USERNAME))
706 sudo_setenv("USERNAME", user_name, FALSE);
709 /* If we didn't keep HOME, reset it based on target user. */
710 if (!ISSET(didvar, KEPT_HOME))
714 * Set MAIL to target user in -i mode or if MAIL is not preserved
715 * from user's environment.
717 if (ISSET(sudo_mode, MODE_LOGIN_SHELL) || !ISSET(didvar, KEPT_MAIL)) {
719 if (cp[sizeof(_PATH_MAILDIR) - 2] == '/')
720 easprintf(&cp, "MAIL=%s%s", _PATH_MAILDIR, runas_pw->pw_name);
722 easprintf(&cp, "MAIL=%s/%s", _PATH_MAILDIR, runas_pw->pw_name);
723 sudo_putenv(cp, ISSET(didvar, DID_MAIL), TRUE);
727 * Copy environ entries as long as they don't match env_delete or
730 for (ep = old_envp; *ep; ep++) {
733 /* Skip variables with values beginning with () (bash functions) */
734 if ((cp = strchr(*ep, '=')) != NULL) {
735 if (strncmp(cp, "=() ", 3) == 0)
740 * First check variables against the blacklist in env_delete.
741 * If no match there check for '%' and '/' characters.
743 okvar = matches_env_delete(*ep) != TRUE;
745 okvar = matches_env_check(*ep) != FALSE;
748 if (strncmp(*ep, "SUDO_PS1=", 9) == 0)
750 else if (strncmp(*ep, "PATH=", 5) == 0)
751 SET(didvar, DID_PATH);
752 else if (strncmp(*ep, "TERM=", 5) == 0)
753 SET(didvar, DID_TERM);
754 sudo_putenv(*ep, FALSE, FALSE);
758 /* Replace the PATH envariable with a secure one? */
759 if (def_secure_path && !user_is_exempt()) {
760 sudo_setenv("PATH", def_secure_path, TRUE);
761 SET(didvar, DID_PATH);
764 /* Set $USER, $LOGNAME and $USERNAME to target if "set_logname" is true. */
765 if (def_set_logname && !ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
766 if (!ISSET(didvar, KEPT_LOGNAME))
767 sudo_setenv("LOGNAME", runas_pw->pw_name, TRUE);
768 if (!ISSET(didvar, KEPT_USER))
769 sudo_setenv("USER", runas_pw->pw_name, TRUE);
770 if (!ISSET(didvar, KEPT_USERNAME))
771 sudo_setenv("USERNAME", runas_pw->pw_name, TRUE);
774 /* Set $HOME to target user if not preserving user's value. */
776 sudo_setenv("HOME", runas_pw->pw_dir, TRUE);
778 /* Provide default values for $TERM and $PATH if they are not set. */
779 if (!ISSET(didvar, DID_TERM))
780 sudo_putenv("TERM=unknown", FALSE, FALSE);
781 if (!ISSET(didvar, DID_PATH))
782 sudo_setenv("PATH", _PATH_STDPATH, FALSE);
785 * Preload a noexec file? For a list of LD_PRELOAD-alikes, see
786 * http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html
787 * XXX - should prepend to original value, if any
789 if (noexec && def_noexec_file != NULL) {
790 #if defined(__darwin__) || defined(__APPLE__)
791 sudo_setenv("DYLD_INSERT_LIBRARIES", def_noexec_file, TRUE);
792 sudo_setenv("DYLD_FORCE_FLAT_NAMESPACE", "", TRUE);
794 # if defined(__osf__) || defined(__sgi)
795 easprintf(&cp, "%s:DEFAULT", def_noexec_file);
796 sudo_setenv("_RLD_LIST", cp, TRUE);
800 sudo_setenv("LDR_PRELOAD", def_noexec_file, TRUE);
802 sudo_setenv("LD_PRELOAD", def_noexec_file, TRUE);
804 # endif /* __osf__ || __sgi */
805 #endif /* __darwin__ || __APPLE__ */
808 /* Set PS1 if SUDO_PS1 is set. */
810 sudo_putenv(ps1, TRUE, TRUE);
812 /* Add the SUDO_COMMAND envariable (cmnd + args). */
814 easprintf(&cp, "%s %s", user_cmnd, user_args);
815 sudo_setenv("SUDO_COMMAND", cp, TRUE);
818 sudo_setenv("SUDO_COMMAND", user_cmnd, TRUE);
821 /* Add the SUDO_USER, SUDO_UID, SUDO_GID environment variables. */
822 sudo_setenv("SUDO_USER", user_name, TRUE);
823 snprintf(idbuf, sizeof(idbuf), "%u", (unsigned int) user_uid);
824 sudo_setenv("SUDO_UID", idbuf, TRUE);
825 snprintf(idbuf, sizeof(idbuf), "%u", (unsigned int) user_gid);
826 sudo_setenv("SUDO_GID", idbuf, TRUE);
828 /* Free old environment. */
833 insert_env_vars(env_vars)
834 struct list_member *env_vars;
836 struct list_member *cur;
838 /* Add user-specified environment variables. */
839 for (cur = env_vars; cur != NULL; cur = cur->next)
844 * Validate the list of environment variables passed in on the command
845 * line against env_delete, env_check, and env_keep.
846 * Calls log_error() if any specified variables are not allowed.
849 validate_env_vars(env_vars)
850 struct list_member *env_vars;
852 struct list_member *var;
853 char *eq, *bad = NULL;
854 size_t len, blen = 0, bsize = 0;
857 /* Add user-specified environment variables. */
858 for (var = env_vars; var != NULL; var = var->next) {
859 if (def_secure_path && !user_is_exempt() &&
860 strncmp(var->value, "PATH=", 5) == 0) {
862 } else if (def_env_reset) {
863 okvar = matches_env_check(var->value);
865 okvar = matches_env_keep(var->value);
867 okvar = matches_env_delete(var->value) == FALSE;
869 okvar = matches_env_check(var->value) != FALSE;
871 if (okvar == FALSE) {
872 /* Not allowed, add to error string, allocating as needed. */
873 if ((eq = strchr(var->value, '=')) != NULL)
875 len = strlen(var->value) + 2;
876 if (blen + len >= bsize) {
879 } while (blen + len >= bsize);
880 bad = erealloc(bad, bsize);
883 strlcat(bad, var->value, bsize);
884 strlcat(bad, ", ", bsize);
891 bad[blen - 2] = '\0'; /* remove trailing ", " */
893 "sorry, you are not allowed to set the following environment variables: %s", bad);
900 * Read in /etc/environment ala AIX and Linux.
901 * Lines may be in either of three formats:
905 * with an optional "export" prefix so the shell can source the file.
906 * Invalid lines, blank lines, or lines consisting solely of a comment
907 * character are skipped.
910 read_env_file(path, overwrite)
915 char *cp, *var, *val;
916 size_t var_len, val_len;
918 if ((fp = fopen(path, "r")) == NULL)
921 while ((var = sudo_parseln(fp)) != NULL) {
922 /* Skip blank or comment lines */
926 /* Skip optional "export " */
927 if (strncmp(var, "export", 6) == 0 && isspace((unsigned char) var[6])) {
929 while (isspace((unsigned char) *var)) {
934 /* Must be of the form name=["']value['"] */
935 for (val = var; *val != '\0' && *val != '='; val++)
937 if (var == val || *val != '=')
939 var_len = (size_t)(val - var);
940 val_len = strlen(++val);
942 /* Strip leading and trailing single/double quotes */
943 if ((val[0] == '\'' || val[0] == '\"') && val[0] == val[val_len - 1]) {
944 val[val_len - 1] = '\0';
949 cp = emalloc(var_len + 1 + val_len + 1);
950 memcpy(cp, var, var_len + 1); /* includes '=' */
951 memcpy(cp + var_len + 1, val, val_len + 1); /* includes NUL */
953 sudo_putenv(cp, TRUE, overwrite);
961 struct list_member *cur;
964 /* Fill in the "env_delete" list. */
965 for (p = initial_badenv_table; *p; p++) {
966 cur = emalloc(sizeof(struct list_member));
967 cur->value = estrdup(*p);
968 cur->next = def_env_delete;
969 def_env_delete = cur;
972 /* Fill in the "env_check" list. */
973 for (p = initial_checkenv_table; *p; p++) {
974 cur = emalloc(sizeof(struct list_member));
975 cur->value = estrdup(*p);
976 cur->next = def_env_check;
980 /* Fill in the "env_keep" list. */
981 for (p = initial_keepenv_table; *p; p++) {
982 cur = emalloc(sizeof(struct list_member));
983 cur->value = estrdup(*p);
984 cur->next = def_env_keep;