Imported Debian patch 1.6.8p12-6
[debian/sudo] / env.c
1 /*
2  * Copyright (c) 2000-2004 Todd C. Miller <Todd.Miller@courtesan.com>
3  *
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.
7  *
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.
15  *
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.
19  */
20
21 #include "config.h"
22
23 #include <sys/types.h>
24 #include <sys/param.h>
25 #include <sys/stat.h>
26 #include <stdio.h>
27 #ifdef STDC_HEADERS
28 # include <stdlib.h>
29 # include <stddef.h>
30 #else
31 # ifdef HAVE_STDLIB_H
32 #  include <stdlib.h>
33 # endif
34 #endif /* STDC_HEADERS */
35 #ifdef HAVE_STRING_H
36 # include <string.h>
37 #else
38 # ifdef HAVE_STRINGS_H
39 #  include <strings.h>
40 # endif
41 #endif /* HAVE_STRING_H */
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif /* HAVE_UNISTD_H */
45 #ifdef HAVE_ERR_H
46 # include <err.h>
47 #else
48 # include "emul/err.h"
49 #endif /* HAVE_ERR_H */
50 #include <pwd.h>
51
52 #include "sudo.h"
53
54 #ifndef lint
55 static const char rcsid[] = "$Sudo: env.c,v 1.42 2004/09/08 15:57:49 millert Exp $";
56 #endif /* lint */
57
58 /*
59  * Flags used in rebuild_env()
60  */
61 #undef DID_TERM
62 #define DID_TERM        0x01
63 #undef DID_PATH
64 #define DID_PATH        0x02
65 #undef DID_HOME
66 #define DID_HOME        0x04
67 #undef DID_SHELL
68 #define DID_SHELL       0x08
69 #undef DID_LOGNAME
70 #define DID_LOGNAME     0x10
71 #undef DID_USER
72 #define DID_USER        0x20
73
74 #undef VNULL
75 #define VNULL   (VOID *)NULL
76
77 /*
78  * Prototypes
79  */
80 char **rebuild_env              __P((char **, int, int));
81 char **zero_env                 __P((char **));
82 static void insert_env          __P((char *, int));
83 static char *format_env         __P((char *, ...));
84
85 /*
86  * Default table of "bad" variables to remove from the environment.
87  * XXX - how to omit TERMCAP if it starts with '/'?
88  */
89 static const char *initial_badenv_table[] = {
90     "IFS",
91     "CDPATH",
92     "SHELLOPTS",
93     "PS4",
94     "LOCALDOMAIN",
95     "RES_OPTIONS",
96     "HOSTALIASES",
97     "NLSPATH",
98     "PATH_LOCALE",
99     "LD_*",
100     "_RLD*",
101 #ifdef __hpux
102     "SHLIB_PATH",
103 #endif /* __hpux */
104 #ifdef _AIX
105     "LIBPATH",
106 #endif /* _AIX */
107 #ifdef __APPLE__
108     "DYLD_*",
109 #endif
110 #ifdef HAVE_KERB4
111     "KRB_CONF*",
112     "KRBCONFDIR",
113     "KRBTKFILE",
114 #endif /* HAVE_KERB4 */
115 #ifdef HAVE_KERB5
116     "KRB5_CONFIG*",
117 #endif /* HAVE_KERB5 */
118 #ifdef HAVE_SECURID
119     "VAR_ACE",
120     "USR_ACE",
121     "DLC_ACE",
122 #endif /* HAVE_SECURID */
123     "TERMINFO",
124     "TERMINFO_DIRS",
125     "TERMPATH",
126     "TERMCAP",                  /* XXX - only if it starts with '/' */
127     "ENV",
128     "BASH_ENV",
129     "PS4",
130     "SHELLOPTS",
131     "JAVA_TOOL_OPTIONS",
132     "PERLLIB",
133     "PERL5LIB",
134     "PERL5OPT",
135     NULL
136 };
137
138 /*
139  * Default table of variables to check for '%' and '/' characters.
140  */
141 static const char *initial_checkenv_table[] = {
142     "LC_*",
143     "LANG",
144     "LANGUAGE",
145     "TERM",
146     NULL
147 };
148
149 static char **new_environ;      /* Modified copy of the environment */
150 static size_t env_size;         /* size of new_environ in char **'s */
151 static size_t env_len;          /* number of slots used, not counting NULL */
152
153 /*
154  * Zero out environment and replace with a minimal set of KRB5CCNAME
155  * USER, LOGNAME, HOME, TZ, PATH (XXX - should just set path to default)
156  * May set user_path, user_shell, and/or user_prompt as side effects.
157  */
158 char **
159 zero_env(envp)
160     char **envp;
161 {
162     static char *newenv[9];
163     char **ep, **nep = newenv;
164     char **ne_last = &newenv[(sizeof(newenv) / sizeof(newenv[0])) - 1];
165     extern char *prev_user;
166
167     for (ep = envp; *ep; ep++) {
168         switch (**ep) {
169             case 'H':
170                 if (strncmp("HOME=", *ep, 5) == 0)
171                     break;
172                 continue;
173             case 'K':
174                 if (strncmp("KRB5CCNAME=", *ep, 11) == 0)
175                     break;
176                 continue;
177             case 'L':
178                 if (strncmp("LOGNAME=", *ep, 8) == 0)
179                     break;
180                 continue;
181             case 'P':
182                 if (strncmp("PATH=", *ep, 5) == 0) {
183                     user_path = *ep + 5;
184                     /* XXX - set to sane default instead of user's? */
185                     break;
186                 }
187                 continue;
188             case 'S':
189                 if (strncmp("SHELL=", *ep, 6) == 0)
190                     user_shell = *ep + 6;
191                 else if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
192                     user_prompt = *ep + 12;
193                 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
194                     prev_user = *ep + 10;
195                 continue;
196             case 'T':
197                 if (strncmp("TZ=", *ep, 3) == 0)
198                     break;
199                 continue;
200             case 'U':
201                 if (strncmp("USER=", *ep, 5) == 0)
202                     break;
203                 continue;
204             default:
205                 continue;
206         }
207
208         /* Deal with multiply defined variables (take first instance) */
209         for (nep = newenv; *nep; nep++) {
210             if (**nep == **ep)
211                 break;
212         }
213         if (*nep == NULL) {
214             if (nep < ne_last)
215                 *nep++ = *ep;
216             else
217                 errx(1, "internal error, attempt to write outside newenv");
218         }
219     }
220
221 #ifdef HAVE_LDAP
222     /*
223      * Prevent OpenLDAP from reading any user dotfiles
224      * or files in the current directory.
225      *
226      */      
227     if (nep < ne_last)
228         *nep++ = "LDAPNOINIT=1";
229     else
230         errx(1, "internal error, attempt to write outside newenv");
231 #endif
232
233     return(&newenv[0]);
234 }
235
236 /*
237  * Given a variable and value, allocate and format an environment string.
238  */
239 static char *
240 #ifdef __STDC__
241 format_env(char *var, ...)
242 #else
243 format_env(var, va_alist)
244     char *var;
245     va_dcl
246 #endif
247 {
248     char *estring;
249     char *val;
250     size_t esize;
251     va_list ap;
252
253 #ifdef __STDC__
254     va_start(ap, var);
255 #else
256     va_start(ap);
257 #endif
258     esize = strlen(var) + 2;
259     while ((val = va_arg(ap, char *)) != NULL)
260         esize += strlen(val);
261     va_end(ap);
262     estring = (char *) emalloc(esize);
263
264     /* Store variable name and the '=' separator.  */
265     if (strlcpy(estring, var, esize) >= esize ||
266         strlcat(estring, "=", esize) >= esize) {
267
268         errx(1, "internal error, format_env() overflow");
269     }
270
271     /* Now store the variable's value (if any) */
272 #ifdef __STDC__
273     va_start(ap, var);
274 #else
275     va_start(ap);
276 #endif
277     while ((val = va_arg(ap, char *)) != NULL) {
278         if (strlcat(estring, val, esize) >= esize)
279             errx(1, "internal error, format_env() overflow");
280     }
281     va_end(ap);
282
283     return(estring);
284 }
285
286 /*
287  * Insert str into new_environ, assumes str has an '=' in it.
288  * NOTE: no other routines may modify new_environ, env_size, or env_len.
289  */
290 static void
291 insert_env(str, dupcheck)
292     char *str;
293     int dupcheck;
294 {
295     char **nep;
296     size_t varlen;
297
298     /* Make sure there is room for the new entry plus a NULL. */
299     if (env_len + 2 > env_size) {
300         env_size += 128;
301         new_environ = erealloc3(new_environ, env_size, sizeof(char *));
302     }
303
304     if (dupcheck) {
305             varlen = (strchr(str, '=') - str) + 1;
306
307             for (nep = new_environ; *nep; nep++) {
308                 if (strncmp(str, *nep, varlen) == 0) {
309                     *nep = str;
310                     return;
311                 }
312             }
313     } else
314         nep = &new_environ[env_len];
315
316     env_len++;
317     *nep++ = str;
318     *nep = NULL;
319 }
320
321 /*
322  * Build a new environment and ether clear potentially dangerous
323  * variables from the old one or start with a clean slate.
324  * Also adds sudo-specific variables (SUDO_*).
325  */
326 char **
327 rebuild_env(envp, sudo_mode, noexec)
328     char **envp;
329     int sudo_mode;
330     int noexec;
331 {
332     char **ep, *cp, *ps1;
333     int okvar, iswild, didvar;
334     size_t len;
335     struct list_member *cur;
336
337     /*
338      * Either clean out the environment or reset to a safe default.
339      */
340     ps1 = NULL;
341     didvar = 0;
342     if (def_env_reset) {
343         int keepit;
344
345         /* Pull in vars we want to keep from the old environment. */
346         for (ep = envp; *ep; ep++) {
347             keepit = 0;
348
349             /* Skip variables with values beginning with () (bash functions) */
350             if ((cp = strchr(*ep, '=')) != NULL) {
351                 if (strncmp(cp, "=() ", 3) == 0)
352                     continue;
353             }
354
355             for (cur = def_env_keep; cur; cur = cur->next) {
356                 len = strlen(cur->value);
357                 /* Deal with '*' wildcard */
358                 if (cur->value[len - 1] == '*') {
359                     len--;
360                     iswild = 1;
361                 } else
362                     iswild = 0;
363                 if (strncmp(cur->value, *ep, len) == 0 &&
364                     (iswild || (*ep)[len] == '=')) {
365                     /* We always preserve TERM, no special treatment needed. */
366                     if (strncmp(*ep, "TERM=", 5) != 0)
367                         keepit = 1;
368                     break;
369                 }
370             }
371
372             if (!strncmp (*ep, "DISPLAY=",8)
373                 || !strncmp (*ep, "XAUTHORITY=", 11)
374                 || !strncmp (*ep, "XAUTHORIZATION=", 15)
375                 || !strncmp (*ep, "XAPPLRESDIR=", 12)
376                 || !strncmp (*ep, "XFILESEARCHPATH=", 16)
377                 || !strncmp (*ep, "XUSERFILESEARCHPATH=", 20)
378                 || !strncmp (*ep, "LANG=", 5)
379                 || !strncmp (*ep, "LANGUAGE=", 9)
380                 || !strncmp (*ep, "LC_", 3))
381               keepit = 1;
382
383             /* For SUDO_PS1 -> PS1 conversion. */
384             if (strncmp(*ep, "SUDO_PS1=", 8) == 0)
385                 ps1 = *ep + 5;
386
387             if (keepit) {
388                 /* Preserve variable. */
389                 switch (**ep) {
390                     case 'H':
391                         if (strncmp(*ep, "HOME=", 5) == 0)
392                             SET(didvar, DID_HOME);
393                         break;
394                     case 'S':
395                         if (strncmp(*ep, "SHELL=", 6) == 0)
396                             SET(didvar, DID_SHELL);
397                         break;
398                     case 'L':
399                         if (strncmp(*ep, "LOGNAME=", 8) == 0)
400                             SET(didvar, DID_LOGNAME);
401                         break;
402                     case 'U':
403                         if (strncmp(*ep, "USER=", 5) == 0)
404                             SET(didvar, DID_USER);
405                         break;
406                    case 'P':
407                       if (strncmp("PATH=", *ep, 5) == 0)
408                          SET(didvar,DID_PATH);
409                       break;
410                 }
411                 insert_env(*ep, 0);
412             } else {
413                 /* Preserve TERM and PATH, ignore anything else. */
414                 if (!ISSET(didvar, DID_TERM) && strncmp(*ep, "TERM=", 5) == 0) {
415                     insert_env(*ep, 0);
416                     SET(didvar, DID_TERM);
417                 } else if (!ISSET(didvar, DID_PATH) && strncmp(*ep, "PATH=", 5) == 0) {
418                     insert_env(*ep, 0);
419                     SET(didvar, DID_PATH);
420                 }
421             }
422         }
423
424         /*
425          * Add in defaults.  In -i mode these come from the runas user,
426          * otherwise they may be from the user's environment (depends
427          * on sudoers options).
428          */
429         if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
430             insert_env(format_env("HOME", runas_pw->pw_dir, VNULL), 0);
431             insert_env(format_env("SHELL", runas_pw->pw_shell, VNULL), 0);
432             insert_env(format_env("LOGNAME", runas_pw->pw_name, VNULL), 0);
433             insert_env(format_env("USER", runas_pw->pw_name, VNULL), 0);
434         } else {
435             if (!ISSET(didvar, DID_HOME))
436                 insert_env(format_env("HOME", user_dir, VNULL), 0);
437             if (!ISSET(didvar, DID_SHELL))
438                 insert_env(format_env("SHELL", sudo_user.pw->pw_shell, VNULL), 0);
439             if (!ISSET(didvar, DID_LOGNAME))
440                 insert_env(format_env("LOGNAME", user_name, VNULL), 0);
441             if (!ISSET(didvar, DID_USER))
442                 insert_env(format_env("USER", user_name, VNULL), 0);
443         }
444     } else {
445         /*
446          * Copy envp entries as long as they don't match env_delete or
447          * env_check.
448          */
449         for (ep = envp; *ep; ep++) {
450             okvar = 1;
451
452             /* Skip variables with values beginning with () (bash functions) */
453             if ((cp = strchr(*ep, '=')) != NULL) {
454                 if (strncmp(cp, "=() ", 3) == 0)
455                     continue;
456             }
457
458             /* Skip anything listed in env_delete. */
459             for (cur = def_env_delete; cur && okvar; cur = cur->next) {
460                 len = strlen(cur->value);
461                 /* Deal with '*' wildcard */
462                 if (cur->value[len - 1] == '*') {
463                     len--;
464                     iswild = 1;
465                 } else
466                     iswild = 0;
467                 if (strncmp(cur->value, *ep, len) == 0 &&
468                     (iswild || (*ep)[len] == '=')) {
469                     okvar = 0;
470                 }
471             }
472
473             /* Check certain variables for '%' and '/' characters. */
474             for (cur = def_env_check; cur && okvar; cur = cur->next) {
475                 len = strlen(cur->value);
476                 /* Deal with '*' wildcard */
477                 if (cur->value[len - 1] == '*') {
478                     len--;
479                     iswild = 1;
480                 } else
481                     iswild = 0;
482                 if (strncmp(cur->value, *ep, len) == 0 &&
483                     (iswild || (*ep)[len] == '=') &&
484                     strpbrk(*ep, "/%")) {
485                     okvar = 0;
486                 }
487             }
488
489             if (okvar) {
490                 if (strncmp(*ep, "SUDO_PS1=", 9) == 0)
491                     ps1 = *ep + 5;
492                 else if (strncmp(*ep, "PATH=", 5) == 0)
493                     SET(didvar, DID_PATH);
494                 else if (strncmp(*ep, "TERM=", 5) == 0)
495                     SET(didvar, DID_TERM);
496                 insert_env(*ep, 0);
497             }
498         }
499     }
500     /* Provide default values for $TERM and $PATH if they are not set. */
501     if (!ISSET(didvar, DID_TERM))
502         insert_env("TERM=unknown", 0);
503     if (!ISSET(didvar, DID_PATH))
504         insert_env(format_env("PATH", _PATH_DEFPATH, VNULL), 0);
505
506 #ifdef SECURE_PATH
507     /* Replace the PATH envariable with a secure one. */
508     insert_env(format_env("PATH", SECURE_PATH, VNULL), 1);
509 #endif
510
511     /* Set $USER and $LOGNAME to target if "set_logname" is true. */
512     if (def_set_logname && runas_pw->pw_name) {
513         insert_env(format_env("LOGNAME", runas_pw->pw_name, VNULL), 1);
514         insert_env(format_env("USER", runas_pw->pw_name, VNULL), 1);
515     }
516
517     /* Set $HOME for `sudo -H'.  Only valid at PERM_FULL_RUNAS. */
518     if (ISSET(sudo_mode, MODE_RESET_HOME) && runas_pw->pw_dir)
519         insert_env(format_env("HOME", runas_pw->pw_dir, VNULL), 1);
520
521     /*
522      * Preload a noexec file?  For a list of LD_PRELOAD-alikes, see
523      * http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html
524      * XXX - should prepend to original value, if any
525      */
526     if (noexec && def_noexec_file != NULL) {
527 #if defined(__darwin__) || defined(__APPLE__)
528         insert_env(format_env("DYLD_INSERT_LIBRARIES", def_noexec_file, VNULL), 1);
529         insert_env(format_env("DYLD_FORCE_FLAT_NAMESPACE", VNULL), 1);
530 #else
531 # if defined(__osf__) || defined(__sgi)
532         insert_env(format_env("_RLD_LIST", def_noexec_file, ":DEFAULT", VNULL), 1);
533 # else
534         insert_env(format_env("LD_PRELOAD", def_noexec_file, VNULL), 1);
535 # endif
536 #endif
537     }
538
539     /* Set PS1 if SUDO_PS1 is set. */
540     if (ps1)
541         insert_env(ps1, 1);
542
543     /* Add the SUDO_COMMAND envariable (cmnd + args). */
544     if (user_args)
545         insert_env(format_env("SUDO_COMMAND", user_cmnd, " ", user_args, VNULL), 1);
546     else
547         insert_env(format_env("SUDO_COMMAND", user_cmnd, VNULL), 1);
548
549     /* Add the SUDO_USER, SUDO_UID, SUDO_GID environment variables. */
550     insert_env(format_env("SUDO_USER", user_name, VNULL), 1);
551     easprintf(&cp, "SUDO_UID=%lu", (unsigned long) user_uid);
552     insert_env(cp, 1);
553     easprintf(&cp, "SUDO_GID=%lu", (unsigned long) user_gid);
554     insert_env(cp, 1);
555
556     return(new_environ);
557 }
558
559 void
560 init_envtables()
561 {
562     struct list_member *cur;
563     const char **p;
564
565     /* Fill in "env_delete" variable. */
566     for (p = initial_badenv_table; *p; p++) {
567         cur = emalloc(sizeof(struct list_member));
568         cur->value = estrdup(*p);
569         cur->next = def_env_delete;
570         def_env_delete = cur;
571     }
572
573     /* Fill in "env_check" variable. */
574     for (p = initial_checkenv_table; *p; p++) {
575         cur = emalloc(sizeof(struct list_member));
576         cur->value = estrdup(*p);
577         cur->next = def_env_check;
578         def_env_check = cur;
579     }
580 }