switch from rcS.d to rc[0-6].d
[debian/sudo] / env.c
1 /*
2  * Copyright (c) 2000-2005, 2007-2009
3  *      Todd C. Miller <Todd.Miller@courtesan.com>
4  *
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.
8  *
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.
16  *
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.
20  */
21
22 #include <config.h>
23
24 #include <sys/types.h>
25 #include <sys/param.h>
26 #include <sys/stat.h>
27 #include <stdio.h>
28 #ifdef STDC_HEADERS
29 # include <stdlib.h>
30 # include <stddef.h>
31 #else
32 # ifdef HAVE_STDLIB_H
33 #  include <stdlib.h>
34 # endif
35 #endif /* STDC_HEADERS */
36 #ifdef HAVE_STRING_H
37 # include <string.h>
38 #else
39 # ifdef HAVE_STRINGS_H
40 #  include <strings.h>
41 # endif
42 #endif /* HAVE_STRING_H */
43 #ifdef HAVE_UNISTD_H
44 # include <unistd.h>
45 #endif /* HAVE_UNISTD_H */
46 #include <ctype.h>
47 #include <errno.h>
48 #include <pwd.h>
49
50 #include "sudo.h"
51
52 #ifndef lint
53 __unused static const char rcsid[] = "$Sudo: env.c,v 1.106 2009/06/23 18:24:42 millert Exp $";
54 #endif /* lint */
55
56 /*
57  * Flags used in rebuild_env()
58  */
59 #undef DID_TERM
60 #define DID_TERM        0x0001
61 #undef DID_PATH
62 #define DID_PATH        0x0002
63 #undef DID_HOME
64 #define DID_HOME        0x0004
65 #undef DID_SHELL
66 #define DID_SHELL       0x0008
67 #undef DID_LOGNAME
68 #define DID_LOGNAME     0x0010
69 #undef DID_USER
70 #define DID_USER        0x0020
71 #undef DID_USERNAME
72 #define DID_USERNAME    0x0040
73 #undef DID_MAX
74 #define DID_MAX         0x00ff
75
76 #undef KEPT_TERM
77 #define KEPT_TERM       0x0100
78 #undef KEPT_PATH
79 #define KEPT_PATH       0x0200
80 #undef KEPT_HOME
81 #define KEPT_HOME       0x0400
82 #undef KEPT_SHELL
83 #define KEPT_SHELL      0x0800
84 #undef KEPT_LOGNAME
85 #define KEPT_LOGNAME    0x1000
86 #undef KEPT_USER
87 #define KEPT_USER       0x2000
88 #undef KEPT_USERNAME
89 #define KEPT_USERNAME   0x4000
90 #undef KEPT_MAX
91 #define KEPT_MAX        0xff00
92
93 #undef VNULL
94 #define VNULL   (void *)NULL
95
96 struct environment {
97     char **envp;                /* pointer to the new environment */
98     size_t env_size;            /* size of new_environ in char **'s */
99     size_t env_len;             /* number of slots used, not counting NULL */
100 };
101
102 /*
103  * Prototypes
104  */
105 void rebuild_env                __P((int, int));
106 static void sudo_setenv         __P((const char *, const char *, int));
107 static void sudo_putenv         __P((char *, int, int));
108
109 extern char **environ;          /* global environment */
110
111 /*
112  * Copy of the sudo-managed environment.
113  */
114 static struct environment env;
115
116 /*
117  * Default table of "bad" variables to remove from the environment.
118  * XXX - how to omit TERMCAP if it starts with '/'?
119  */
120 static const char *initial_badenv_table[] = {
121     "IFS",
122     "CDPATH",
123     "SHELLOPTS",
124     "PS4",
125     "LOCALDOMAIN",
126     "RES_OPTIONS",
127     "HOSTALIASES",
128     "NLSPATH",
129     "PATH_LOCALE",
130     "LD_*",
131     "_RLD*",
132 #ifdef __hpux
133     "SHLIB_PATH",
134 #endif /* __hpux */
135 #ifdef _AIX
136     "LDR_*",
137     "LIBPATH",
138     "AUTHSTATE",
139 #endif
140 #ifdef __APPLE__
141     "DYLD_*",
142 #endif
143 #ifdef HAVE_KERB4
144     "KRB_CONF*",
145     "KRBCONFDIR",
146     "KRBTKFILE",
147 #endif /* HAVE_KERB4 */
148 #ifdef HAVE_KERB5
149     "KRB5_CONFIG*",
150     "KRB5_KTNAME",
151 #endif /* HAVE_KERB5 */
152 #ifdef HAVE_SECURID
153     "VAR_ACE",
154     "USR_ACE",
155     "DLC_ACE",
156 #endif /* HAVE_SECURID */
157     "TERMINFO",                 /* terminfo, exclusive path to terminfo files */
158     "TERMINFO_DIRS",            /* terminfo, path(s) to terminfo files */
159     "TERMPATH",                 /* termcap, path(s) to termcap files */
160     "TERMCAP",                  /* XXX - only if it starts with '/' */
161     "ENV",                      /* ksh, file to source before script runs */
162     "BASH_ENV",                 /* bash, file to source before script runs */
163     "PS4",                      /* bash, prefix for lines in xtrace mode */
164     "GLOBIGNORE",               /* bash, globbing patterns to ignore */
165     "SHELLOPTS",                /* bash, extra command line options */
166     "JAVA_TOOL_OPTIONS",        /* java, extra command line options */
167     "PERLIO_DEBUG ",            /* perl, debugging output file */
168     "PERLLIB",                  /* perl, search path for modules/includes */
169     "PERL5LIB",                 /* perl 5, search path for modules/includes */
170     "PERL5OPT",                 /* perl 5, extra command line options */
171     "PERL5DB",                  /* perl 5, command used to load debugger */
172     "FPATH",                    /* ksh, search path for functions */
173     "NULLCMD",                  /* zsh, command for null file redirection */
174     "READNULLCMD",              /* zsh, command for null file redirection */
175     "ZDOTDIR",                  /* zsh, search path for dot files */
176     "TMPPREFIX",                /* zsh, prefix for temporary files */
177     "PYTHONHOME",               /* python, module search path */
178     "PYTHONPATH",               /* python, search path */
179     "PYTHONINSPECT",            /* python, allow inspection */
180     "RUBYLIB",                  /* ruby, library load path */
181     "RUBYOPT",                  /* ruby, extra command line options */
182     NULL
183 };
184
185 /*
186  * Default table of variables to check for '%' and '/' characters.
187  */
188 static const char *initial_checkenv_table[] = {
189     "COLORTERM",
190     "LANG",
191     "LANGUAGE",
192     "LC_*",
193     "LINGUAS",
194     "TERM",
195     NULL
196 };
197
198 /*
199  * Default table of variables to preserve in the environment.
200  */
201 static const char *initial_keepenv_table[] = {
202     "COLORS",
203     "DISPLAY",
204     "HOME",
205     "HOSTNAME",
206     "KRB5CCNAME",
207     "LS_COLORS",
208     "MAIL",
209     "PATH",
210     "PS1",
211     "PS2",
212     "TZ",
213     "XAUTHORITY",
214     "XAUTHORIZATION",
215     NULL
216 };
217
218 /*
219  * Similar to setenv(3) but operates on sudo's private copy of the environment
220  * (not environ) and it always overwrites.  The dupcheck param determines
221  * whether we need to verify that the variable is not already set.
222  */
223 static void
224 sudo_setenv(var, val, dupcheck)
225     const char *var;
226     const char *val;
227     int dupcheck;
228 {
229     char *estring;
230     size_t esize;
231
232     esize = strlen(var) + 1 + strlen(val) + 1;
233     estring = emalloc(esize);
234
235     /* Build environment string and insert it. */
236     if (strlcpy(estring, var, esize) >= esize ||
237         strlcat(estring, "=", esize) >= esize ||
238         strlcat(estring, val, esize) >= esize) {
239
240         errorx(1, "internal error, sudo_setenv() overflow");
241     }
242     sudo_putenv(estring, dupcheck, TRUE);
243 }
244
245 /*
246  * Version of setenv(3) that uses our own environ pointer.
247  * Will sync with environ as needed.
248  */
249 int
250 setenv(var, val, overwrite)
251     const char *var;
252     const char *val;
253     int overwrite;
254 {
255     char *estring, *ep;
256     const char *cp;
257     size_t esize;
258
259     if (!var || *var == '\0')
260         return(EINVAL);
261
262     /*
263      * POSIX says a var name with '=' is an error but BSD
264      * just ignores the '=' and anything after it.
265      */
266     for (cp = var; *cp && *cp != '='; cp++)
267         ;
268     esize = (size_t)(cp - var) + 2;
269     if (val) {
270         esize += strlen(val);   /* glibc treats a NULL val as "" */
271     }
272
273     /* Allocate and fill in estring. */
274     estring = ep = emalloc(esize);
275     for (cp = var; *cp && *cp != '='; cp++)
276         *ep++ = *cp;
277     *ep++ = '=';
278     if (val) {
279         for (cp = val; *cp; cp++)
280             *ep++ = *cp;
281     }
282     *ep = '\0';
283
284     /* Sync env.envp with environ as needed. */
285     if (env.envp != environ) {
286         char **ep;
287         size_t len;
288
289         for (ep = environ; *ep != NULL; ep++)
290             continue;
291         len = ep - environ;
292         if (len + 2 > env.env_size) {
293             efree(env.envp);
294             env.env_size = len + 2 + 128;
295             env.envp = emalloc2(env.env_size, sizeof(char *));
296 #ifdef ENV_DEBUG
297             memset(env.envp, 0, env.env_size * sizeof(char *));
298 #endif
299         }
300         memcpy(env.envp, environ, len * sizeof(char *));
301         env.envp[len] = NULL;
302         env.env_len = len;
303         environ = env.envp;
304 #ifdef ENV_DEBUG
305     } else {
306         if (env.envp[env.env_len] != NULL)
307             errorx(1, "setenv: corrupted envp, len mismatch");
308 #endif
309     }
310     sudo_putenv(estring, TRUE, overwrite);
311     return(0);
312 }
313
314 /*
315  * Version of unsetenv(3) that uses our own environ pointer.
316  * Will sync with environ as needed.
317  */
318 #ifdef UNSETENV_VOID
319 void
320 #else
321 int
322 #endif
323 unsetenv(var)
324     const char *var;
325 {
326     char **ep;
327     size_t len;
328
329     if (strchr(var, '=') != NULL) {
330         errno = EINVAL;
331 #ifdef UNSETENV_VOID
332         return;
333 #else
334         return(-1);
335 #endif
336     }
337
338     /* Make sure we are operating on the current environment. */
339     /* XXX - this could be optimized to include the search */
340     if (env.envp != environ) {
341         for (ep = environ; *ep != NULL; ep++)
342             continue;
343         len = ep - environ;
344         if (len + 1 > env.env_size) {
345             efree(env.envp);
346             env.env_size = len + 1 + 128;
347             env.envp = emalloc2(env.env_size, sizeof(char *));
348 #ifdef ENV_DEBUG
349             memset(env.envp, 0, env.env_size * sizeof(char *));
350 #endif
351         }
352         memcpy(env.envp, environ, len * sizeof(char *));
353         env.envp[len] = NULL;
354         env.env_len = len;
355         environ = env.envp;
356 #ifdef ENV_DEBUG
357     } else {
358         if (env.envp[env.env_len] != NULL)
359             errorx(1, "unsetenv: corrupted envp, len mismatch");
360 #endif
361     }
362
363     len = strlen(var);
364     for (ep = env.envp; *ep; ep++) {
365         if (strncmp(var, *ep, len) == 0 && (*ep)[len] == '=') {
366             /* Found it; shift remainder + NULL over by one and update len. */
367             memmove(ep, ep + 1,
368                 (env.env_len - (ep - env.envp)) * sizeof(char *));
369             env.env_len--;
370             break;
371         }
372     }
373 #ifndef UNSETENV_VOID
374     return(0);
375 #endif
376 }
377
378 /*
379  * Version of putenv(3) that uses our own environ pointer.
380  * Will sync with environ as needed.
381  */
382 int
383 #ifdef PUTENV_CONST
384 putenv(const char *string)
385 #else
386 putenv(string)
387     char *string;
388 #endif
389 {
390     if (strchr(string, '=') == NULL) {
391         errno = EINVAL;
392         return(-1);
393     }
394     /* Sync env.envp with environ as needed. */
395     if (env.envp != environ) {
396         char **ep;
397         size_t len;
398
399         for (ep = environ; *ep != NULL; ep++)
400             continue;
401         len = ep - environ;
402         if (len + 2 > env.env_size) {
403             efree(env.envp);
404             env.env_size = len + 2 + 128;
405             env.envp = emalloc2(env.env_size, sizeof(char *));
406 #ifdef ENV_DEBUG
407             memset(env.envp, 0, env.env_size * sizeof(char *));
408 #endif
409         }
410         memcpy(env.envp, environ, len * sizeof(char *));
411         env.envp[len] = NULL;
412         env.env_len = len;
413         environ = env.envp;
414 #ifdef ENV_DEBUG
415     } else {
416         if (env.envp[env.env_len] != NULL)
417             errorx(1, "putenv: corrupted envp, len mismatch");
418 #endif
419     }
420     sudo_putenv((char *)string, TRUE, TRUE);
421     return(0);
422 }
423
424 /*
425  * Similar to putenv(3) but operates on sudo's private copy of the
426  * environment (not environ) and it always overwrites.  The dupcheck param
427  * determines whether we need to verify that the variable is not already set.
428  * Will only overwrite an existing variable if overwrite is set.
429  */
430 static void
431 sudo_putenv(str, dupcheck, overwrite)
432     char *str;
433     int dupcheck;
434     int overwrite;
435 {
436     char **ep;
437     size_t len;
438
439     /* Make sure there is room for the new entry plus a NULL. */
440     if (env.env_len + 2 > env.env_size) {
441         env.env_size += 128;
442         env.envp = erealloc3(env.envp, env.env_size, sizeof(char *));
443 #ifdef ENV_DEBUG
444         memset(env.envp + env.env_len, 0,
445             (env.env_size - env.env_len) * sizeof(char *));
446 #endif
447         environ = env.envp;
448     }
449
450 #ifdef ENV_DEBUG
451     if (env.envp[env.env_len] != NULL)
452         errorx(1, "sudo_putenv: corrupted envp, len mismatch");
453 #endif
454
455     if (dupcheck) {
456             len = (strchr(str, '=') - str) + 1;
457             for (ep = env.envp; *ep; ep++) {
458                 if (strncmp(str, *ep, len) == 0) {
459                     if (overwrite)
460                         *ep = str;
461                     return;
462                 }
463             }
464     } else
465         ep = env.envp + env.env_len;
466
467     env.env_len++;
468     *ep++ = str;
469     *ep = NULL;
470 }
471
472 /*
473  * Check the env_delete blacklist.
474  * Returns TRUE if the variable was found, else false.
475  */
476 static int
477 matches_env_delete(var)
478     const char *var;
479 {
480     struct list_member *cur;
481     size_t len;
482     int iswild, match = FALSE;
483
484     /* Skip anything listed in env_delete. */
485     for (cur = def_env_delete; cur; cur = cur->next) {
486         len = strlen(cur->value);
487         /* Deal with '*' wildcard */
488         if (cur->value[len - 1] == '*') {
489             len--;
490             iswild = TRUE;
491         } else
492             iswild = FALSE;
493         if (strncmp(cur->value, var, len) == 0 &&
494             (iswild || var[len] == '=')) {
495             match = TRUE;
496             break;
497         }
498     }
499     return(match);
500 }
501
502 /*
503  * Apply the env_check list.
504  * Returns TRUE if the variable is allowed, FALSE if denied
505  * or -1 if no match.
506  */
507 static int
508 matches_env_check(var)
509     const char *var;
510 {
511     struct list_member *cur;
512     size_t len;
513     int iswild, keepit = -1;
514
515     for (cur = def_env_check; cur; cur = cur->next) {
516         len = strlen(cur->value);
517         /* Deal with '*' wildcard */
518         if (cur->value[len - 1] == '*') {
519             len--;
520             iswild = TRUE;
521         } else
522             iswild = FALSE;
523         if (strncmp(cur->value, var, len) == 0 &&
524             (iswild || var[len] == '=')) {
525             keepit = !strpbrk(var, "/%");
526             break;
527         }
528     }
529     return(keepit);
530 }
531
532 /*
533  * Check the env_keep list.
534  * Returns TRUE if the variable is allowed else FALSE.
535  */
536 static int
537 matches_env_keep(var)
538     const char *var;
539 {
540     struct list_member *cur;
541     size_t len;
542     int iswild, keepit = FALSE;
543
544     for (cur = def_env_keep; cur; cur = cur->next) {
545         len = strlen(cur->value);
546         /* Deal with '*' wildcard */
547         if (cur->value[len - 1] == '*') {
548             len--;
549             iswild = TRUE;
550         } else
551             iswild = FALSE;
552         if (strncmp(cur->value, var, len) == 0 &&
553             (iswild || var[len] == '=')) {
554             keepit = TRUE;
555             break;
556         }
557     }
558     return(keepit);
559 }
560
561 /*
562  * Build a new environment and ether clear potentially dangerous
563  * variables from the old one or start with a clean slate.
564  * Also adds sudo-specific variables (SUDO_*).
565  */
566 void
567 rebuild_env(sudo_mode, noexec)
568     int sudo_mode;
569     int noexec;
570 {
571     char **old_envp, **ep, *cp, *ps1;
572     char idbuf[MAX_UID_T_LEN];
573     unsigned int didvar;
574
575     /*
576      * Either clean out the environment or reset to a safe default.
577      */
578     ps1 = NULL;
579     didvar = 0;
580     env.env_len = 0;
581     env.env_size = 128;
582     old_envp = env.envp;
583     env.envp = emalloc2(env.env_size, sizeof(char *));
584 #ifdef ENV_DEBUG
585     memset(env.envp, 0, env.env_size * sizeof(char *));
586 #endif
587     if (def_env_reset || ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
588         /* Pull in vars we want to keep from the old environment. */
589         for (ep = environ; *ep; ep++) {
590             int keepit;
591
592             /* Skip variables with values beginning with () (bash functions) */
593             if ((cp = strchr(*ep, '=')) != NULL) {
594                 if (strncmp(cp, "=() ", 3) == 0)
595                     continue;
596             }
597
598             /*
599              * First check certain variables for '%' and '/' characters.
600              * If no match there, check the keep list.
601              * If nothing matched, we remove it from the environment.
602              */
603             keepit = matches_env_check(*ep);
604             if (keepit == -1)
605                 keepit = matches_env_keep(*ep);
606
607             if (!strncmp (*ep, "DISPLAY=",8)
608                 || !strncmp (*ep, "XAUTHORITY=", 11)
609                 || !strncmp (*ep, "XAUTHORIZATION=", 15)
610                 || !strncmp (*ep, "XAPPLRESDIR=", 12)
611                 || !strncmp (*ep, "XFILESEARCHPATH=", 16)
612                 || !strncmp (*ep, "XUSERFILESEARCHPATH=", 20)
613                 || !strncmp (*ep, "LANG=", 5)
614                 || !strncmp (*ep, "LANGUAGE=", 9)
615                 || !strncmp (*ep, "LC_", 3))
616               keepit = 1;
617
618             /* For SUDO_PS1 -> PS1 conversion. */
619             if (strncmp(*ep, "SUDO_PS1=", 8) == 0)
620                 ps1 = *ep + 5;
621
622             if (keepit) {
623                 /* Preserve variable. */
624                 switch (**ep) {
625                     case 'H':
626                         if (strncmp(*ep, "HOME=", 5) == 0)
627                             SET(didvar, DID_HOME);
628                         break;
629                     case 'L':
630                         if (strncmp(*ep, "LOGNAME=", 8) == 0)
631                             SET(didvar, DID_LOGNAME);
632                         break;
633                     case 'P':
634                         if (strncmp(*ep, "PATH=", 5) == 0)
635                             SET(didvar, DID_PATH);
636                         break;
637                     case 'S':
638                         if (strncmp(*ep, "SHELL=", 6) == 0)
639                             SET(didvar, DID_SHELL);
640                         break;
641                     case 'T':
642                         if (strncmp(*ep, "TERM=", 5) == 0)
643                             SET(didvar, DID_TERM);
644                         break;
645                     case 'U':
646                         if (strncmp(*ep, "USER=", 5) == 0)
647                             SET(didvar, DID_USER);
648                         if (strncmp(*ep, "USERNAME=", 5) == 0)
649                             SET(didvar, DID_USERNAME);
650                         break;
651                 }
652                 sudo_putenv(*ep, FALSE, FALSE);
653             }
654         }
655         didvar |= didvar << 8;          /* convert DID_* to KEPT_* */
656
657         /*
658          * Add in defaults.  In -i mode these come from the runas user,
659          * otherwise they may be from the user's environment (depends
660          * on sudoers options).
661          */
662         if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
663             sudo_setenv("HOME", runas_pw->pw_dir, ISSET(didvar, DID_HOME));
664             sudo_setenv("SHELL", runas_pw->pw_shell, ISSET(didvar, DID_SHELL));
665             sudo_setenv("LOGNAME", runas_pw->pw_name,
666                 ISSET(didvar, DID_LOGNAME));
667             sudo_setenv("USER", runas_pw->pw_name, ISSET(didvar, DID_USER));
668             sudo_setenv("USERNAME", runas_pw->pw_name,
669                 ISSET(didvar, DID_USERNAME));
670         } else {
671             if (!ISSET(didvar, DID_HOME))
672                 sudo_setenv("HOME", user_dir, FALSE);
673             if (!ISSET(didvar, DID_SHELL))
674                 sudo_setenv("SHELL", sudo_user.pw->pw_shell, FALSE);
675             if (!ISSET(didvar, DID_LOGNAME))
676                 sudo_setenv("LOGNAME", user_name, FALSE);
677             if (!ISSET(didvar, DID_USER))
678                 sudo_setenv("USER", user_name, FALSE);
679             if (!ISSET(didvar, DID_USERNAME))
680                 sudo_setenv("USERNAME", user_name, FALSE);
681         }
682     } else {
683         /*
684          * Copy environ entries as long as they don't match env_delete or
685          * env_check.
686          */
687         for (ep = environ; *ep; ep++) {
688             int okvar;
689
690             /* Skip variables with values beginning with () (bash functions) */
691             if ((cp = strchr(*ep, '=')) != NULL) {
692                 if (strncmp(cp, "=() ", 3) == 0)
693                     continue;
694             }
695
696             /*
697              * First check variables against the blacklist in env_delete.
698              * If no match there check for '%' and '/' characters.
699              */
700             okvar = matches_env_delete(*ep) != TRUE;
701             if (okvar)
702                 okvar = matches_env_check(*ep) != FALSE;
703
704             if (okvar) {
705                 if (strncmp(*ep, "SUDO_PS1=", 9) == 0)
706                     ps1 = *ep + 5;
707                 else if (strncmp(*ep, "PATH=", 5) == 0)
708                     SET(didvar, DID_PATH);
709                 else if (strncmp(*ep, "TERM=", 5) == 0)
710                     SET(didvar, DID_TERM);
711                 sudo_putenv(*ep, FALSE, FALSE);
712             }
713         }
714     }
715     /* Replace the PATH envariable with a secure one? */
716     if (def_secure_path && !user_is_exempt()) {
717         sudo_setenv("PATH", def_secure_path, TRUE);
718         SET(didvar, DID_PATH);
719     }
720
721     /* Set $USER, $LOGNAME and $USERNAME to target if "set_logname" is true. */
722     /* XXX - not needed for MODE_LOGIN_SHELL */
723     if (def_set_logname && runas_pw->pw_name) {
724         if (!ISSET(didvar, KEPT_LOGNAME))
725             sudo_setenv("LOGNAME", runas_pw->pw_name, TRUE);
726         if (!ISSET(didvar, KEPT_USER))
727             sudo_setenv("USER", runas_pw->pw_name, TRUE);
728         if (!ISSET(didvar, KEPT_USERNAME))
729             sudo_setenv("USERNAME", runas_pw->pw_name, TRUE);
730     }
731
732     /* Set $HOME for `sudo -H'.  Only valid at PERM_FULL_RUNAS. */
733     /* XXX - not needed for MODE_LOGIN_SHELL */
734     if (runas_pw->pw_dir) {
735         if (ISSET(sudo_mode, MODE_RESET_HOME) ||
736             (ISSET(sudo_mode, MODE_RUN) && (def_always_set_home ||
737             (ISSET(sudo_mode, MODE_SHELL) && def_set_home))))
738             sudo_setenv("HOME", runas_pw->pw_dir, TRUE);
739     }
740
741     /* Provide default values for $TERM and $PATH if they are not set. */
742     if (!ISSET(didvar, DID_TERM))
743         sudo_putenv("TERM=unknown", FALSE, FALSE);
744     if (!ISSET(didvar, DID_PATH))
745         sudo_setenv("PATH", _PATH_DEFPATH, FALSE);
746
747     /*
748      * Preload a noexec file?  For a list of LD_PRELOAD-alikes, see
749      * http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html
750      * XXX - should prepend to original value, if any
751      */
752     if (noexec && def_noexec_file != NULL) {
753 #if defined(__darwin__) || defined(__APPLE__)
754         sudo_setenv("DYLD_INSERT_LIBRARIES", def_noexec_file, TRUE);
755         sudo_setenv("DYLD_FORCE_FLAT_NAMESPACE", "", TRUE);
756 #else
757 # if defined(__osf__) || defined(__sgi)
758         easprintf(&cp, "%s:DEFAULT", def_noexec_file);
759         sudo_setenv("_RLD_LIST", cp, TRUE);
760         efree(cp);
761 # else
762 #  ifdef _AIX
763         sudo_setenv("LDR_PRELOAD", def_noexec_file, TRUE);
764 #  else
765         sudo_setenv("LD_PRELOAD", def_noexec_file, TRUE);
766 #  endif /* _AIX */
767 # endif /* __osf__ || __sgi */
768 #endif /* __darwin__ || __APPLE__ */
769     }
770
771     /* Set PS1 if SUDO_PS1 is set. */
772     if (ps1 != NULL)
773         sudo_putenv(ps1, TRUE, TRUE);
774
775     /* Add the SUDO_COMMAND envariable (cmnd + args). */
776     if (user_args) {
777         easprintf(&cp, "%s %s", user_cmnd, user_args);
778         sudo_setenv("SUDO_COMMAND", cp, TRUE);
779         efree(cp);
780     } else
781         sudo_setenv("SUDO_COMMAND", user_cmnd, TRUE);
782
783     /* Add the SUDO_USER, SUDO_UID, SUDO_GID environment variables. */
784     sudo_setenv("SUDO_USER", user_name, TRUE);
785     snprintf(idbuf, sizeof(idbuf), "%lu", (unsigned long) user_uid);
786     sudo_setenv("SUDO_UID", idbuf, TRUE);
787     snprintf(idbuf, sizeof(idbuf), "%lu", (unsigned long) user_gid);
788     sudo_setenv("SUDO_GID", idbuf, TRUE);
789
790     /* Install new environment. */
791     environ = env.envp;
792     efree(old_envp);
793 }
794
795 void
796 insert_env_vars(env_vars)
797     struct list_member *env_vars;
798 {
799     struct list_member *cur;
800
801     if (env_vars == NULL)
802         return;
803
804     /* Add user-specified environment variables. */
805     for (cur = env_vars; cur != NULL; cur = cur->next)
806         putenv(cur->value);
807 }
808
809 /*
810  * Validate the list of environment variables passed in on the command
811  * line against env_delete, env_check, and env_keep.
812  * Calls log_error() if any specified variables are not allowed.
813  */
814 void
815 validate_env_vars(env_vars)
816     struct list_member *env_vars;
817 {
818     struct list_member *var;
819     char *eq, *bad = NULL;
820     size_t len, blen = 0, bsize = 0;
821     int okvar;
822
823     for (var = env_vars; var != NULL; var = var->next) {
824         if (def_secure_path && !user_is_exempt() &&
825             strncmp(var->value, "PATH=", 5) == 0) {
826             okvar = FALSE;
827         } else if (def_env_reset) {
828             okvar = matches_env_check(var->value);
829             if (okvar == -1)
830                 okvar = matches_env_keep(var->value);
831         } else {
832             okvar = matches_env_delete(var->value) == FALSE;
833             if (okvar == FALSE)
834                 okvar = matches_env_check(var->value) != FALSE;
835         }
836         if (okvar == FALSE) {
837             /* Not allowed, add to error string, allocating as needed. */
838             if ((eq = strchr(var->value, '=')) != NULL)
839                 *eq = '\0';
840             len = strlen(var->value) + 2;
841             if (blen + len >= bsize) {
842                 do {
843                     bsize += 1024;
844                 } while (blen + len >= bsize);
845                 bad = erealloc(bad, bsize);
846                 bad[blen] = '\0';
847             }
848             strlcat(bad, var->value, bsize);
849             strlcat(bad, ", ", bsize);
850             blen += len;
851             if (eq != NULL)
852                 *eq = '=';
853         }
854     }
855     if (bad != NULL) {
856         bad[blen - 2] = '\0';           /* remove trailing ", " */
857         log_error(NO_MAIL,
858             "sorry, you are not allowed to set the following environment variables: %s", bad);
859         /* NOTREACHED */
860         efree(bad);
861     }
862 }
863
864 /*
865  * Read in /etc/environment ala AIX and Linux.
866  * Lines may be in either of three formats:
867  *  NAME=VALUE
868  *  NAME="VALUE"
869  *  NAME='VALUE'
870  * with an optional "export" prefix so the shell can source the file.
871  * Invalid lines, blank lines, or lines consisting solely of a comment
872  * character are skipped.
873  */
874 void
875 read_env_file(path, overwrite)
876     const char *path;
877     int overwrite;
878 {
879     FILE *fp;
880     char *cp, *var, *val;
881     size_t var_len, val_len;
882
883     if ((fp = fopen(path, "r")) == NULL)
884         return;
885
886     while ((var = sudo_parseln(fp)) != NULL) {
887         /* Skip blank or comment lines */
888         if (*var == '\0')
889             continue;
890
891         /* Skip optional "export " */
892         if (strncmp(var, "export", 6) == 0 && isspace((unsigned char) var[6])) {
893             var += 7;
894             while (isspace((unsigned char) *var)) {
895                 var++;
896             }
897         }
898
899         /* Must be of the form name=["']value['"] */
900         for (val = var; *val != '\0' && *val != '='; val++)
901             ;
902         if (var == val || *val != '=')
903             continue;
904         var_len = (size_t)(val - var);
905         val_len = strlen(++val);
906
907         /* Strip leading and trailing single/double quotes */
908         if ((val[0] == '\'' || val[0] == '\"') && val[0] == val[val_len - 1]) {
909             val[val_len - 1] = '\0';
910             val++;
911             val_len -= 2;
912         }
913
914         cp = emalloc(var_len + 1 + val_len + 1);
915         memcpy(cp, var, var_len + 1); /* includes '=' */
916         memcpy(cp + var_len + 1, val, val_len + 1); /* includes NUL */
917
918         sudo_putenv(cp, TRUE, overwrite);
919     }
920     fclose(fp);
921 }
922
923 void
924 init_envtables()
925 {
926     struct list_member *cur;
927     const char **p;
928
929     /* Fill in the "env_delete" list. */
930     for (p = initial_badenv_table; *p; p++) {
931         cur = emalloc(sizeof(struct list_member));
932         cur->value = estrdup(*p);
933         cur->next = def_env_delete;
934         def_env_delete = cur;
935     }
936
937     /* Fill in the "env_check" list. */
938     for (p = initial_checkenv_table; *p; p++) {
939         cur = emalloc(sizeof(struct list_member));
940         cur->value = estrdup(*p);
941         cur->next = def_env_check;
942         def_env_check = cur;
943     }
944
945     /* Fill in the "env_keep" list. */
946     for (p = initial_keepenv_table; *p; p++) {
947         cur = emalloc(sizeof(struct list_member));
948         cur->value = estrdup(*p);
949         cur->next = def_env_keep;
950         def_env_keep = cur;
951     }
952 }