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 *));
612 /* Reset HOME based on target user if configured to. */
613 if (ISSET(sudo_mode, MODE_RUN)) {
614 if (def_always_set_home ||
615 ISSET(sudo_mode, MODE_RESET_HOME | MODE_LOGIN_SHELL) ||
616 (ISSET(sudo_mode, MODE_SHELL) && def_set_home))
620 if (def_env_reset || ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
621 /* Pull in vars we want to keep from the old environment. */
622 for (ep = old_envp; *ep; ep++) {
625 /* Skip variables with values beginning with () (bash functions) */
626 if ((cp = strchr(*ep, '=')) != NULL) {
627 if (strncmp(cp, "=() ", 3) == 0)
632 * First check certain variables for '%' and '/' characters.
633 * If no match there, check the keep list.
634 * If nothing matched, we remove it from the environment.
636 keepit = matches_env_check(*ep);
638 keepit = matches_env_keep(*ep);
640 /* For SUDO_PS1 -> PS1 conversion. */
641 if (strncmp(*ep, "SUDO_PS1=", 8) == 0)
645 /* Preserve variable. */
648 if (strncmp(*ep, "HOME=", 5) == 0)
649 SET(didvar, DID_HOME);
652 if (strncmp(*ep, "LOGNAME=", 8) == 0)
653 SET(didvar, DID_LOGNAME);
656 if (strncmp(*ep, "MAIL=", 5) == 0)
657 SET(didvar, DID_MAIL);
660 if (strncmp(*ep, "PATH=", 5) == 0)
661 SET(didvar, DID_PATH);
664 if (strncmp(*ep, "SHELL=", 6) == 0)
665 SET(didvar, DID_SHELL);
668 if (strncmp(*ep, "TERM=", 5) == 0)
669 SET(didvar, DID_TERM);
672 if (strncmp(*ep, "USER=", 5) == 0)
673 SET(didvar, DID_USER);
674 if (strncmp(*ep, "USERNAME=", 5) == 0)
675 SET(didvar, DID_USERNAME);
678 sudo_putenv(*ep, FALSE, FALSE);
681 didvar |= didvar << 8; /* convert DID_* to KEPT_* */
684 * Add in defaults. In -i mode these come from the runas user,
685 * otherwise they may be from the user's environment (depends
686 * on sudoers options).
688 if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
689 sudo_setenv("SHELL", runas_pw->pw_shell, ISSET(didvar, DID_SHELL));
690 sudo_setenv("LOGNAME", runas_pw->pw_name,
691 ISSET(didvar, DID_LOGNAME));
692 sudo_setenv("USER", runas_pw->pw_name, ISSET(didvar, DID_USER));
693 sudo_setenv("USERNAME", runas_pw->pw_name,
694 ISSET(didvar, DID_USERNAME));
696 if (!ISSET(didvar, DID_SHELL))
697 sudo_setenv("SHELL", sudo_user.pw->pw_shell, FALSE);
698 if (!ISSET(didvar, DID_LOGNAME))
699 sudo_setenv("LOGNAME", user_name, FALSE);
700 if (!ISSET(didvar, DID_USER))
701 sudo_setenv("USER", user_name, FALSE);
702 if (!ISSET(didvar, DID_USERNAME))
703 sudo_setenv("USERNAME", user_name, FALSE);
706 /* If we didn't keep HOME, reset it based on target user. */
707 if (!ISSET(didvar, KEPT_HOME))
711 * Set MAIL to target user in -i mode or if MAIL is not preserved
712 * from user's environment.
714 if (ISSET(sudo_mode, MODE_LOGIN_SHELL) || !ISSET(didvar, KEPT_MAIL)) {
716 if (cp[sizeof(_PATH_MAILDIR) - 2] == '/')
717 easprintf(&cp, "MAIL=%s%s", _PATH_MAILDIR, runas_pw->pw_name);
719 easprintf(&cp, "MAIL=%s/%s", _PATH_MAILDIR, runas_pw->pw_name);
720 sudo_putenv(cp, ISSET(didvar, DID_MAIL), TRUE);
724 * Copy environ entries as long as they don't match env_delete or
727 for (ep = old_envp; *ep; ep++) {
730 /* Skip variables with values beginning with () (bash functions) */
731 if ((cp = strchr(*ep, '=')) != NULL) {
732 if (strncmp(cp, "=() ", 3) == 0)
737 * First check variables against the blacklist in env_delete.
738 * If no match there check for '%' and '/' characters.
740 okvar = matches_env_delete(*ep) != TRUE;
742 okvar = matches_env_check(*ep) != FALSE;
745 if (strncmp(*ep, "SUDO_PS1=", 9) == 0)
747 else if (strncmp(*ep, "PATH=", 5) == 0)
748 SET(didvar, DID_PATH);
749 else if (strncmp(*ep, "TERM=", 5) == 0)
750 SET(didvar, DID_TERM);
751 sudo_putenv(*ep, FALSE, FALSE);
755 /* Replace the PATH envariable with a secure one? */
756 if (def_secure_path && !user_is_exempt()) {
757 sudo_setenv("PATH", def_secure_path, TRUE);
758 SET(didvar, DID_PATH);
761 /* Set $USER, $LOGNAME and $USERNAME to target if "set_logname" is true. */
762 if (def_set_logname && !ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
763 if (!ISSET(didvar, KEPT_LOGNAME))
764 sudo_setenv("LOGNAME", runas_pw->pw_name, TRUE);
765 if (!ISSET(didvar, KEPT_USER))
766 sudo_setenv("USER", runas_pw->pw_name, TRUE);
767 if (!ISSET(didvar, KEPT_USERNAME))
768 sudo_setenv("USERNAME", runas_pw->pw_name, TRUE);
771 /* Set $HOME to target user if not preserving user's value. */
773 sudo_setenv("HOME", runas_pw->pw_dir, TRUE);
775 /* Provide default values for $TERM and $PATH if they are not set. */
776 if (!ISSET(didvar, DID_TERM))
777 sudo_putenv("TERM=unknown", FALSE, FALSE);
778 if (!ISSET(didvar, DID_PATH))
779 sudo_setenv("PATH", _PATH_STDPATH, FALSE);
782 * Preload a noexec file? For a list of LD_PRELOAD-alikes, see
783 * http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html
784 * XXX - should prepend to original value, if any
786 if (noexec && def_noexec_file != NULL) {
787 #if defined(__darwin__) || defined(__APPLE__)
788 sudo_setenv("DYLD_INSERT_LIBRARIES", def_noexec_file, TRUE);
789 sudo_setenv("DYLD_FORCE_FLAT_NAMESPACE", "", TRUE);
791 # if defined(__osf__) || defined(__sgi)
792 easprintf(&cp, "%s:DEFAULT", def_noexec_file);
793 sudo_setenv("_RLD_LIST", cp, TRUE);
797 sudo_setenv("LDR_PRELOAD", def_noexec_file, TRUE);
799 sudo_setenv("LD_PRELOAD", def_noexec_file, TRUE);
801 # endif /* __osf__ || __sgi */
802 #endif /* __darwin__ || __APPLE__ */
805 /* Set PS1 if SUDO_PS1 is set. */
807 sudo_putenv(ps1, TRUE, TRUE);
809 /* Add the SUDO_COMMAND envariable (cmnd + args). */
811 easprintf(&cp, "%s %s", user_cmnd, user_args);
812 sudo_setenv("SUDO_COMMAND", cp, TRUE);
815 sudo_setenv("SUDO_COMMAND", user_cmnd, TRUE);
818 /* Add the SUDO_USER, SUDO_UID, SUDO_GID environment variables. */
819 sudo_setenv("SUDO_USER", user_name, TRUE);
820 snprintf(idbuf, sizeof(idbuf), "%lu", (unsigned long) user_uid);
821 sudo_setenv("SUDO_UID", idbuf, TRUE);
822 snprintf(idbuf, sizeof(idbuf), "%lu", (unsigned long) user_gid);
823 sudo_setenv("SUDO_GID", idbuf, TRUE);
825 /* Free old environment. */
830 insert_env_vars(env_vars)
831 struct list_member *env_vars;
833 struct list_member *cur;
835 /* Add user-specified environment variables. */
836 for (cur = env_vars; cur != NULL; cur = cur->next)
841 * Validate the list of environment variables passed in on the command
842 * line against env_delete, env_check, and env_keep.
843 * Calls log_error() if any specified variables are not allowed.
846 validate_env_vars(env_vars)
847 struct list_member *env_vars;
849 struct list_member *var;
850 char *eq, *bad = NULL;
851 size_t len, blen = 0, bsize = 0;
854 /* Add user-specified environment variables. */
855 for (var = env_vars; var != NULL; var = var->next) {
856 if (def_secure_path && !user_is_exempt() &&
857 strncmp(var->value, "PATH=", 5) == 0) {
859 } else if (def_env_reset) {
860 okvar = matches_env_check(var->value);
862 okvar = matches_env_keep(var->value);
864 okvar = matches_env_delete(var->value) == FALSE;
866 okvar = matches_env_check(var->value) != FALSE;
868 if (okvar == FALSE) {
869 /* Not allowed, add to error string, allocating as needed. */
870 if ((eq = strchr(var->value, '=')) != NULL)
872 len = strlen(var->value) + 2;
873 if (blen + len >= bsize) {
876 } while (blen + len >= bsize);
877 bad = erealloc(bad, bsize);
880 strlcat(bad, var->value, bsize);
881 strlcat(bad, ", ", bsize);
888 bad[blen - 2] = '\0'; /* remove trailing ", " */
890 "sorry, you are not allowed to set the following environment variables: %s", bad);
897 * Read in /etc/environment ala AIX and Linux.
898 * Lines may be in either of three formats:
902 * with an optional "export" prefix so the shell can source the file.
903 * Invalid lines, blank lines, or lines consisting solely of a comment
904 * character are skipped.
907 read_env_file(path, overwrite)
912 char *cp, *var, *val;
913 size_t var_len, val_len;
915 if ((fp = fopen(path, "r")) == NULL)
918 while ((var = sudo_parseln(fp)) != NULL) {
919 /* Skip blank or comment lines */
923 /* Skip optional "export " */
924 if (strncmp(var, "export", 6) == 0 && isspace((unsigned char) var[6])) {
926 while (isspace((unsigned char) *var)) {
931 /* Must be of the form name=["']value['"] */
932 for (val = var; *val != '\0' && *val != '='; val++)
934 if (var == val || *val != '=')
936 var_len = (size_t)(val - var);
937 val_len = strlen(++val);
939 /* Strip leading and trailing single/double quotes */
940 if ((val[0] == '\'' || val[0] == '\"') && val[0] == val[val_len - 1]) {
941 val[val_len - 1] = '\0';
946 cp = emalloc(var_len + 1 + val_len + 1);
947 memcpy(cp, var, var_len + 1); /* includes '=' */
948 memcpy(cp + var_len + 1, val, val_len + 1); /* includes NUL */
950 sudo_putenv(cp, TRUE, overwrite);
958 struct list_member *cur;
961 /* Fill in the "env_delete" list. */
962 for (p = initial_badenv_table; *p; p++) {
963 cur = emalloc(sizeof(struct list_member));
964 cur->value = estrdup(*p);
965 cur->next = def_env_delete;
966 def_env_delete = cur;
969 /* Fill in the "env_check" list. */
970 for (p = initial_checkenv_table; *p; p++) {
971 cur = emalloc(sizeof(struct list_member));
972 cur->value = estrdup(*p);
973 cur->next = def_env_check;
977 /* Fill in the "env_keep" list. */
978 for (p = initial_keepenv_table; *p; p++) {
979 cur = emalloc(sizeof(struct list_member));
980 cur->value = estrdup(*p);
981 cur->next = def_env_keep;