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[] = {
212 * Initialize env based on envp.
221 for (ep = environ; *ep != NULL; ep++)
223 len = (size_t)(ep - environ);
227 * If we are already initialized due to lazy init (usualy via getenv())
228 * we need to avoid calling malloc() as it may call getenv() itself.
233 } else if (!env.owned) {
235 env.env_size = len + 1 + 128;
236 env.envp = emalloc2(env.env_size, sizeof(char *));
238 memset(env.envp, 0, env.env_size * sizeof(char *));
240 memcpy(env.envp, environ, len * sizeof(char *));
241 env.envp[len] = '\0';
253 * Similar to setenv(3) but operates on sudo's private copy of the environment
254 * (not environ) and it always overwrites. The dupcheck param determines
255 * whether we need to verify that the variable is not already set.
258 sudo_setenv(var, val, dupcheck)
266 esize = strlen(var) + 1 + strlen(val) + 1;
267 estring = emalloc(esize);
269 /* Build environment string and insert it. */
270 if (strlcpy(estring, var, esize) >= esize ||
271 strlcat(estring, "=", esize) >= esize ||
272 strlcat(estring, val, esize) >= esize) {
274 errorx(1, "internal error, sudo_setenv() overflow");
276 sudo_putenv(estring, dupcheck, TRUE);
280 * Version of getenv(3) that uses our own environ pointer.
287 size_t vlen = strlen(var);
289 if (env.envp == NULL)
292 for (ev = env.envp; (cp = *ev) != NULL; ev++) {
293 if (strncmp(var, cp, vlen) == 0 && cp[vlen] == '=')
294 return cp + vlen + 1;
300 * Version of setenv(3) that uses our own environ pointer.
303 setenv(var, val, overwrite)
312 if (!var || *var == '\0') {
317 if (env.envp == NULL)
321 * POSIX says a var name with '=' is an error but BSD
322 * just ignores the '=' and anything after it.
324 for (cp = var; *cp && *cp != '='; cp++)
326 esize = (size_t)(cp - var) + 2;
328 esize += strlen(val); /* glibc treats a NULL val as "" */
331 /* Allocate and fill in estring. */
332 estring = ep = emalloc(esize);
333 for (cp = var; *cp && *cp != '='; cp++)
337 for (cp = val; *cp; cp++)
343 if (env.envp[env.env_len] != NULL)
344 errorx(1, "setenv: corrupted envp, len mismatch");
346 sudo_putenv(estring, TRUE, overwrite);
351 * Version of unsetenv(3) that uses our own environ pointer.
364 if (var == NULL || *var == '\0' || strchr(var, '=') != NULL) {
373 if (env.envp == NULL)
377 if (env.envp[env.env_len] != NULL)
378 errorx(1, "unsetenv: corrupted envp, len mismatch");
382 for (ep = env.envp; *ep != NULL;) {
383 if (strncmp(var, *ep, len) == 0 && (*ep)[len] == '=') {
384 /* Found it; shift remainder + NULL over by one. */
386 while ((*cur = *(cur + 1)) != NULL)
388 /* Keep going, could be multiple instances of the var. */
393 env.env_len = ep - env.envp;
394 #ifndef UNSETENV_VOID
400 * Version of putenv(3) that uses our own environ pointer.
404 putenv(const char *string)
410 if (env.envp == NULL)
413 if (strchr(string, '=') == NULL) {
418 if (env.envp[env.env_len] != NULL)
419 errorx(1, "putenv: corrupted envp, len mismatch");
421 sudo_putenv((char *)string, TRUE, TRUE);
426 * Similar to putenv(3) but operates on sudo's private copy of the
427 * environment (not environ) and it always overwrites. The dupcheck param
428 * determines whether we need to verify that the variable is not already set.
429 * Will only overwrite an existing variable if overwrite is set.
432 sudo_putenv(str, dupcheck, overwrite)
441 /* Make sure there is room for the new entry plus a NULL. */
442 if (env.env_len + 2 > env.env_size) {
445 env.envp = erealloc3(env.envp, env.env_size, sizeof(char *));
447 /* We don't own env.envp, allocate a new one. */
448 ep = emalloc2(env.env_size, sizeof(char *));
449 memcpy(ep, env.envp, env.env_size * sizeof(char *));
454 memset(env.envp + env.env_len, 0,
455 (env.env_size - env.env_len) * sizeof(char *));
460 if (env.envp[env.env_len] != NULL)
461 errorx(1, "sudo_putenv: corrupted envp, len mismatch");
465 len = (strchr(str, '=') - str) + 1;
466 for (ep = env.envp; !found && *ep != NULL; ep++) {
467 if (strncmp(str, *ep, len) == 0) {
473 /* Prune out duplicate variables. */
474 if (found && overwrite) {
475 while (*ep != NULL) {
476 if (strncmp(str, *ep, len) == 0) {
478 while ((*cur = *(cur + 1)) != NULL)
484 env.env_len = ep - env.envp;
489 ep = env.envp + env.env_len;
497 * Check the env_delete blacklist.
498 * Returns TRUE if the variable was found, else false.
501 matches_env_delete(var)
504 struct list_member *cur;
506 int iswild, match = FALSE;
508 /* Skip anything listed in env_delete. */
509 for (cur = def_env_delete; cur; cur = cur->next) {
510 len = strlen(cur->value);
511 /* Deal with '*' wildcard */
512 if (cur->value[len - 1] == '*') {
517 if (strncmp(cur->value, var, len) == 0 &&
518 (iswild || var[len] == '=')) {
527 * Apply the env_check list.
528 * Returns TRUE if the variable is allowed, FALSE if denied
532 matches_env_check(var)
535 struct list_member *cur;
537 int iswild, keepit = -1;
539 for (cur = def_env_check; cur; cur = cur->next) {
540 len = strlen(cur->value);
541 /* Deal with '*' wildcard */
542 if (cur->value[len - 1] == '*') {
547 if (strncmp(cur->value, var, len) == 0 &&
548 (iswild || var[len] == '=')) {
549 keepit = !strpbrk(var, "/%");
557 * Check the env_keep list.
558 * Returns TRUE if the variable is allowed else FALSE.
561 matches_env_keep(var)
564 struct list_member *cur;
566 int iswild, keepit = FALSE;
568 for (cur = def_env_keep; cur; cur = cur->next) {
569 len = strlen(cur->value);
570 /* Deal with '*' wildcard */
571 if (cur->value[len - 1] == '*') {
576 if (strncmp(cur->value, var, len) == 0 &&
577 (iswild || var[len] == '=')) {
586 * Build a new environment and ether clear potentially dangerous
587 * variables from the old one or start with a clean slate.
588 * Also adds sudo-specific variables (SUDO_*).
594 char **old_envp, **ep, *cp, *ps1;
595 char idbuf[MAX_UID_T_LEN];
597 int reset_home = FALSE;
600 * Either clean out the environment or reset to a safe default.
607 env.envp = emalloc2(env.env_size, sizeof(char *));
609 memset(env.envp, 0, env.env_size * sizeof(char *));
611 if (def_env_reset || ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
612 /* Reset HOME based on target user unless keeping old value. */
615 /* Pull in vars we want to keep from the old environment. */
616 for (ep = old_envp; *ep; ep++) {
619 /* Skip variables with values beginning with () (bash functions) */
620 if ((cp = strchr(*ep, '=')) != NULL) {
621 if (strncmp(cp, "=() ", 3) == 0)
626 * First check certain variables for '%' and '/' characters.
627 * If no match there, check the keep list.
628 * If nothing matched, we remove it from the environment.
630 keepit = matches_env_check(*ep);
632 keepit = matches_env_keep(*ep);
634 /* For SUDO_PS1 -> PS1 conversion. */
635 if (strncmp(*ep, "SUDO_PS1=", 8) == 0)
639 /* Preserve variable. */
642 if (strncmp(*ep, "HOME=", 5) == 0)
643 SET(didvar, DID_HOME);
646 if (strncmp(*ep, "LOGNAME=", 8) == 0)
647 SET(didvar, DID_LOGNAME);
650 if (strncmp(*ep, "MAIL=", 5) == 0)
651 SET(didvar, DID_MAIL);
654 if (strncmp(*ep, "PATH=", 5) == 0)
655 SET(didvar, DID_PATH);
658 if (strncmp(*ep, "SHELL=", 6) == 0)
659 SET(didvar, DID_SHELL);
662 if (strncmp(*ep, "TERM=", 5) == 0)
663 SET(didvar, DID_TERM);
666 if (strncmp(*ep, "USER=", 5) == 0)
667 SET(didvar, DID_USER);
668 if (strncmp(*ep, "USERNAME=", 5) == 0)
669 SET(didvar, DID_USERNAME);
672 sudo_putenv(*ep, FALSE, FALSE);
675 didvar |= didvar << 8; /* convert DID_* to KEPT_* */
678 * Add in defaults. In -i mode these come from the runas user,
679 * otherwise they may be from the user's environment (depends
680 * on sudoers options).
682 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
683 sudo_setenv("SHELL", runas_pw->pw_shell, ISSET(didvar, DID_SHELL));
684 sudo_setenv("LOGNAME", runas_pw->pw_name,
685 ISSET(didvar, DID_LOGNAME));
686 sudo_setenv("USER", runas_pw->pw_name, ISSET(didvar, DID_USER));
687 sudo_setenv("USERNAME", runas_pw->pw_name,
688 ISSET(didvar, DID_USERNAME));
690 if (!ISSET(didvar, DID_SHELL))
691 sudo_setenv("SHELL", sudo_user.pw->pw_shell, FALSE);
692 if (!ISSET(didvar, DID_LOGNAME))
693 sudo_setenv("LOGNAME", user_name, FALSE);
694 if (!ISSET(didvar, DID_USER))
695 sudo_setenv("USER", user_name, FALSE);
696 if (!ISSET(didvar, DID_USERNAME))
697 sudo_setenv("USERNAME", user_name, FALSE);
700 * Set MAIL to target user in -i mode or if MAIL is not preserved
701 * from user's environment.
703 if (ISSET(sudo_mode, MODE_LOGIN_SHELL) || !ISSET(didvar, KEPT_MAIL)) {
705 if (cp[sizeof(_PATH_MAILDIR) - 2] == '/')
706 easprintf(&cp, "MAIL=%s%s", _PATH_MAILDIR, runas_pw->pw_name);
708 easprintf(&cp, "MAIL=%s/%s", _PATH_MAILDIR, runas_pw->pw_name);
709 sudo_putenv(cp, ISSET(didvar, DID_MAIL), TRUE);
712 /* Reset HOME based on target user if configured to. */
713 if (ISSET(sudo_mode, MODE_RUN)) {
714 if (def_always_set_home || ISSET(sudo_mode, MODE_RESET_HOME) ||
715 (ISSET(sudo_mode, MODE_SHELL) && def_set_home))
720 * Copy environ entries as long as they don't match env_delete or
723 for (ep = old_envp; *ep; ep++) {
726 /* Skip variables with values beginning with () (bash functions) */
727 if ((cp = strchr(*ep, '=')) != NULL) {
728 if (strncmp(cp, "=() ", 3) == 0)
733 * First check variables against the blacklist in env_delete.
734 * If no match there check for '%' and '/' characters.
736 okvar = matches_env_delete(*ep) != TRUE;
738 okvar = matches_env_check(*ep) != FALSE;
741 if (strncmp(*ep, "SUDO_PS1=", 9) == 0)
743 else if (strncmp(*ep, "PATH=", 5) == 0)
744 SET(didvar, DID_PATH);
745 else if (strncmp(*ep, "TERM=", 5) == 0)
746 SET(didvar, DID_TERM);
747 sudo_putenv(*ep, FALSE, FALSE);
751 /* Replace the PATH envariable with a secure one? */
752 if (def_secure_path && !user_is_exempt()) {
753 sudo_setenv("PATH", def_secure_path, TRUE);
754 SET(didvar, DID_PATH);
757 /* Set $USER, $LOGNAME and $USERNAME to target if "set_logname" is true. */
758 if (def_set_logname && !ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
759 if (!ISSET(didvar, KEPT_LOGNAME))
760 sudo_setenv("LOGNAME", runas_pw->pw_name, TRUE);
761 if (!ISSET(didvar, KEPT_USER))
762 sudo_setenv("USER", runas_pw->pw_name, TRUE);
763 if (!ISSET(didvar, KEPT_USERNAME))
764 sudo_setenv("USERNAME", runas_pw->pw_name, TRUE);
767 /* Set $HOME to target user if not preserving user's value. */
768 if (reset_home && !ISSET(didvar, KEPT_HOME))
769 sudo_setenv("HOME", runas_pw->pw_dir, TRUE);
771 /* Provide default values for $TERM and $PATH if they are not set. */
772 if (!ISSET(didvar, DID_TERM))
773 sudo_putenv("TERM=unknown", FALSE, FALSE);
774 if (!ISSET(didvar, DID_PATH))
775 sudo_setenv("PATH", _PATH_STDPATH, FALSE);
778 * Preload a noexec file? For a list of LD_PRELOAD-alikes, see
779 * http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html
780 * XXX - should prepend to original value, if any
782 if (noexec && def_noexec_file != NULL) {
783 #if defined(__darwin__) || defined(__APPLE__)
784 sudo_setenv("DYLD_INSERT_LIBRARIES", def_noexec_file, TRUE);
785 sudo_setenv("DYLD_FORCE_FLAT_NAMESPACE", "", TRUE);
787 # if defined(__osf__) || defined(__sgi)
788 easprintf(&cp, "%s:DEFAULT", def_noexec_file);
789 sudo_setenv("_RLD_LIST", cp, TRUE);
793 sudo_setenv("LDR_PRELOAD", def_noexec_file, TRUE);
795 sudo_setenv("LD_PRELOAD", def_noexec_file, TRUE);
797 # endif /* __osf__ || __sgi */
798 #endif /* __darwin__ || __APPLE__ */
801 /* Set PS1 if SUDO_PS1 is set. */
803 sudo_putenv(ps1, TRUE, TRUE);
805 /* Add the SUDO_COMMAND envariable (cmnd + args). */
807 easprintf(&cp, "%s %s", user_cmnd, user_args);
808 sudo_setenv("SUDO_COMMAND", cp, TRUE);
811 sudo_setenv("SUDO_COMMAND", user_cmnd, TRUE);
814 /* Add the SUDO_USER, SUDO_UID, SUDO_GID environment variables. */
815 sudo_setenv("SUDO_USER", user_name, TRUE);
816 snprintf(idbuf, sizeof(idbuf), "%lu", (unsigned long) user_uid);
817 sudo_setenv("SUDO_UID", idbuf, TRUE);
818 snprintf(idbuf, sizeof(idbuf), "%lu", (unsigned long) user_gid);
819 sudo_setenv("SUDO_GID", idbuf, TRUE);
821 /* Free old environment. */
826 insert_env_vars(env_vars)
827 struct list_member *env_vars;
829 struct list_member *cur;
831 /* Add user-specified environment variables. */
832 for (cur = env_vars; cur != NULL; cur = cur->next)
837 * Validate the list of environment variables passed in on the command
838 * line against env_delete, env_check, and env_keep.
839 * Calls log_error() if any specified variables are not allowed.
842 validate_env_vars(env_vars)
843 struct list_member *env_vars;
845 struct list_member *var;
846 char *eq, *bad = NULL;
847 size_t len, blen = 0, bsize = 0;
850 /* Add user-specified environment variables. */
851 for (var = env_vars; var != NULL; var = var->next) {
852 if (def_secure_path && !user_is_exempt() &&
853 strncmp(var->value, "PATH=", 5) == 0) {
855 } else if (def_env_reset) {
856 okvar = matches_env_check(var->value);
858 okvar = matches_env_keep(var->value);
860 okvar = matches_env_delete(var->value) == FALSE;
862 okvar = matches_env_check(var->value) != FALSE;
864 if (okvar == FALSE) {
865 /* Not allowed, add to error string, allocating as needed. */
866 if ((eq = strchr(var->value, '=')) != NULL)
868 len = strlen(var->value) + 2;
869 if (blen + len >= bsize) {
872 } while (blen + len >= bsize);
873 bad = erealloc(bad, bsize);
876 strlcat(bad, var->value, bsize);
877 strlcat(bad, ", ", bsize);
884 bad[blen - 2] = '\0'; /* remove trailing ", " */
886 "sorry, you are not allowed to set the following environment variables: %s", bad);
893 * Read in /etc/environment ala AIX and Linux.
894 * Lines may be in either of three formats:
898 * with an optional "export" prefix so the shell can source the file.
899 * Invalid lines, blank lines, or lines consisting solely of a comment
900 * character are skipped.
903 read_env_file(path, overwrite)
908 char *cp, *var, *val;
909 size_t var_len, val_len;
911 if ((fp = fopen(path, "r")) == NULL)
914 while ((var = sudo_parseln(fp)) != NULL) {
915 /* Skip blank or comment lines */
919 /* Skip optional "export " */
920 if (strncmp(var, "export", 6) == 0 && isspace((unsigned char) var[6])) {
922 while (isspace((unsigned char) *var)) {
927 /* Must be of the form name=["']value['"] */
928 for (val = var; *val != '\0' && *val != '='; val++)
930 if (var == val || *val != '=')
932 var_len = (size_t)(val - var);
933 val_len = strlen(++val);
935 /* Strip leading and trailing single/double quotes */
936 if ((val[0] == '\'' || val[0] == '\"') && val[0] == val[val_len - 1]) {
937 val[val_len - 1] = '\0';
942 cp = emalloc(var_len + 1 + val_len + 1);
943 memcpy(cp, var, var_len + 1); /* includes '=' */
944 memcpy(cp + var_len + 1, val, val_len + 1); /* includes NUL */
946 sudo_putenv(cp, TRUE, overwrite);
954 struct list_member *cur;
957 /* Fill in the "env_delete" list. */
958 for (p = initial_badenv_table; *p; p++) {
959 cur = emalloc(sizeof(struct list_member));
960 cur->value = estrdup(*p);
961 cur->next = def_env_delete;
962 def_env_delete = cur;
965 /* Fill in the "env_check" list. */
966 for (p = initial_checkenv_table; *p; p++) {
967 cur = emalloc(sizeof(struct list_member));
968 cur->value = estrdup(*p);
969 cur->next = def_env_check;
973 /* Fill in the "env_keep" list. */
974 for (p = initial_keepenv_table; *p; p++) {
975 cur = emalloc(sizeof(struct list_member));
976 cur->value = estrdup(*p);
977 cur->next = def_env_keep;