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[] = {
143
#endif /* HAVE_KERB4 */
147
#endif /* HAVE_KERB5 */
152
#endif /* HAVE_SECURID */
153
"TERMINFO", /* terminfo, exclusive path to terminfo files */
154
"TERMINFO_DIRS", /* terminfo, path(s) to terminfo files */
155
"TERMPATH", /* termcap, path(s) to termcap files */
156
"TERMCAP", /* XXX - only if it starts with '/' */
157
"ENV", /* ksh, file to source before script runs */
158
"BASH_ENV", /* bash, file to source before script runs */
159
"PS4", /* bash, prefix for lines in xtrace mode */
160
"GLOBIGNORE", /* bash, globbing patterns to ignore */
161
"SHELLOPTS", /* bash, extra command line options */
162
"JAVA_TOOL_OPTIONS", /* java, extra command line options */
163
"PERLIO_DEBUG ", /* perl, debugging output file */
164
"PERLLIB", /* perl, search path for modules/includes */
165
"PERL5LIB", /* perl 5, search path for modules/includes */
166
"PERL5OPT", /* perl 5, extra command line options */
167
"PERL5DB", /* perl 5, command used to load debugger */
168
"FPATH", /* ksh, search path for functions */
169
"NULLCMD", /* zsh, command for null file redirection */
170
"READNULLCMD", /* zsh, command for null file redirection */
171
"ZDOTDIR", /* zsh, search path for dot files */
172
"TMPPREFIX", /* zsh, prefix for temporary files */
173
"PYTHONHOME", /* python, module search path */
174
"PYTHONPATH", /* python, search path */
175
"PYTHONINSPECT", /* python, allow inspection */
176
"PYTHONUSERBASE", /* python, per user site-packages directory */
177
"RUBYLIB", /* ruby, library load path */
178
"RUBYOPT", /* ruby, extra command line options */
183
* Default table of variables to check for '%' and '/' characters.
185
static const char *initial_checkenv_table[] = {
196
* Default table of variables to preserve in the environment.
198
static const char *initial_keepenv_table[] = {
214
* Initialize env based on envp.
223
for (ep = environ; *ep != NULL; ep++)
225
len = (size_t)(ep - environ);
229
* If we are already initialized due to lazy init (usualy via getenv())
230
* we need to avoid calling malloc() as it may call getenv() itself.
235
} else if (!env.owned) {
237
env.env_size = len + 1 + 128;
238
env.envp = emalloc2(env.env_size, sizeof(char *));
240
memset(env.envp, 0, env.env_size * sizeof(char *));
242
memcpy(env.envp, environ, len * sizeof(char *));
243
env.envp[len] = '\0';
255
* Similar to setenv(3) but operates on sudo's private copy of the environment
256
* (not environ) and it always overwrites. The dupcheck param determines
257
* whether we need to verify that the variable is not already set.
260
sudo_setenv(var, val, dupcheck)
268
esize = strlen(var) + 1 + strlen(val) + 1;
269
estring = emalloc(esize);
271
/* Build environment string and insert it. */
272
if (strlcpy(estring, var, esize) >= esize ||
273
strlcat(estring, "=", esize) >= esize ||
274
strlcat(estring, val, esize) >= esize) {
276
errorx(1, "internal error, sudo_setenv() overflow");
278
sudo_putenv(estring, dupcheck, TRUE);
282
* Version of getenv(3) that uses our own environ pointer.
289
size_t vlen = strlen(var);
291
if (env.envp == NULL)
294
for (ev = env.envp; (cp = *ev) != NULL; ev++) {
295
if (strncmp(var, cp, vlen) == 0 && cp[vlen] == '=')
296
return cp + vlen + 1;
302
* Version of setenv(3) that uses our own environ pointer.
305
setenv(var, val, overwrite)
314
if (!var || *var == '\0') {
319
if (env.envp == NULL)
323
* POSIX says a var name with '=' is an error but BSD
324
* just ignores the '=' and anything after it.
326
for (cp = var; *cp && *cp != '='; cp++)
328
esize = (size_t)(cp - var) + 2;
330
esize += strlen(val); /* glibc treats a NULL val as "" */
333
/* Allocate and fill in estring. */
334
estring = ep = emalloc(esize);
335
for (cp = var; *cp && *cp != '='; cp++)
339
for (cp = val; *cp; cp++)
345
if (env.envp[env.env_len] != NULL)
346
errorx(1, "setenv: corrupted envp, len mismatch");
348
sudo_putenv(estring, TRUE, overwrite);
353
* Version of unsetenv(3) that uses our own environ pointer.
366
if (var == NULL || *var == '\0' || strchr(var, '=') != NULL) {
375
if (env.envp == NULL)
379
if (env.envp[env.env_len] != NULL)
380
errorx(1, "unsetenv: corrupted envp, len mismatch");
384
for (ep = env.envp; *ep != NULL;) {
385
if (strncmp(var, *ep, len) == 0 && (*ep)[len] == '=') {
386
/* Found it; shift remainder + NULL over by one. */
388
while ((*cur = *(cur + 1)) != NULL)
390
/* Keep going, could be multiple instances of the var. */
395
env.env_len = ep - env.envp;
396
#ifndef UNSETENV_VOID
402
* Version of putenv(3) that uses our own environ pointer.
406
putenv(const char *string)
412
if (env.envp == NULL)
415
if (strchr(string, '=') == NULL) {
420
if (env.envp[env.env_len] != NULL)
421
errorx(1, "putenv: corrupted envp, len mismatch");
423
sudo_putenv((char *)string, TRUE, TRUE);
428
* Similar to putenv(3) but operates on sudo's private copy of the
429
* environment (not environ) and it always overwrites. The dupcheck param
430
* determines whether we need to verify that the variable is not already set.
431
* Will only overwrite an existing variable if overwrite is set.
434
sudo_putenv(str, dupcheck, overwrite)
443
/* Make sure there is room for the new entry plus a NULL. */
444
if (env.env_len + 2 > env.env_size) {
447
env.envp = erealloc3(env.envp, env.env_size, sizeof(char *));
449
/* We don't own env.envp, allocate a new one. */
450
ep = emalloc2(env.env_size, sizeof(char *));
451
memcpy(ep, env.envp, env.env_size * sizeof(char *));
456
memset(env.envp + env.env_len, 0,
457
(env.env_size - env.env_len) * sizeof(char *));
462
if (env.envp[env.env_len] != NULL)
463
errorx(1, "sudo_putenv: corrupted envp, len mismatch");
467
len = (strchr(str, '=') - str) + 1;
468
for (ep = env.envp; !found && *ep != NULL; ep++) {
469
if (strncmp(str, *ep, len) == 0) {
475
/* Prune out duplicate variables. */
476
if (found && overwrite) {
477
while (*ep != NULL) {
478
if (strncmp(str, *ep, len) == 0) {
480
while ((*cur = *(cur + 1)) != NULL)
486
env.env_len = ep - env.envp;
491
ep = env.envp + env.env_len;
499
* Check the env_delete blacklist.
500
* Returns TRUE if the variable was found, else false.
503
matches_env_delete(var)
506
struct list_member *cur;
508
int iswild, match = FALSE;
510
/* Skip anything listed in env_delete. */
511
for (cur = def_env_delete; cur; cur = cur->next) {
512
len = strlen(cur->value);
513
/* Deal with '*' wildcard */
514
if (cur->value[len - 1] == '*') {
519
if (strncmp(cur->value, var, len) == 0 &&
520
(iswild || var[len] == '=')) {
529
* Apply the env_check list.
530
* Returns TRUE if the variable is allowed, FALSE if denied
534
matches_env_check(var)
537
struct list_member *cur;
539
int iswild, keepit = -1;
541
for (cur = def_env_check; cur; cur = cur->next) {
542
len = strlen(cur->value);
543
/* Deal with '*' wildcard */
544
if (cur->value[len - 1] == '*') {
549
if (strncmp(cur->value, var, len) == 0 &&
550
(iswild || var[len] == '=')) {
551
keepit = !strpbrk(var, "/%");
559
* Check the env_keep list.
560
* Returns TRUE if the variable is allowed else FALSE.
563
matches_env_keep(var)
566
struct list_member *cur;
568
int iswild, keepit = FALSE;
570
for (cur = def_env_keep; cur; cur = cur->next) {
571
len = strlen(cur->value);
572
/* Deal with '*' wildcard */
573
if (cur->value[len - 1] == '*') {
578
if (strncmp(cur->value, var, len) == 0 &&
579
(iswild || var[len] == '=')) {
588
* Build a new environment and ether clear potentially dangerous
589
* variables from the old one or start with a clean slate.
590
* Also adds sudo-specific variables (SUDO_*).
596
char **old_envp, **ep, *cp, *ps1;
597
char idbuf[MAX_UID_T_LEN];
599
int reset_home = FALSE;
602
* Either clean out the environment or reset to a safe default.
609
env.envp = emalloc2(env.env_size, sizeof(char *));
611
memset(env.envp, 0, env.env_size * sizeof(char *));
613
if (def_env_reset || ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
614
/* Reset HOME based on target user unless keeping old value. */
617
/* Pull in vars we want to keep from the old environment. */
618
for (ep = old_envp; *ep; ep++) {
621
/* Skip variables with values beginning with () (bash functions) */
622
if ((cp = strchr(*ep, '=')) != NULL) {
623
if (strncmp(cp, "=() ", 3) == 0)
628
* First check certain variables for '%' and '/' characters.
629
* If no match there, check the keep list.
630
* If nothing matched, we remove it from the environment.
632
keepit = matches_env_check(*ep);
634
keepit = matches_env_keep(*ep);
636
if (!strncmp (*ep, "DISPLAY=",8)
637
|| !strncmp (*ep, "XAUTHORITY=", 11)
638
|| !strncmp (*ep, "XAUTHORIZATION=", 15)
639
|| !strncmp (*ep, "XAPPLRESDIR=", 12)
640
|| !strncmp (*ep, "XFILESEARCHPATH=", 16)
641
|| !strncmp (*ep, "XUSERFILESEARCHPATH=", 20)
642
|| !strncmp (*ep, "LANG=", 5)
643
|| !strncmp (*ep, "LANGUAGE=", 9)
644
|| !strncmp (*ep, "LC_", 3))
647
/* For SUDO_PS1 -> PS1 conversion. */
648
if (strncmp(*ep, "SUDO_PS1=", 8) == 0)
652
/* Preserve variable. */
655
if (strncmp(*ep, "HOME=", 5) == 0)
656
SET(didvar, DID_HOME);
659
if (strncmp(*ep, "LOGNAME=", 8) == 0)
660
SET(didvar, DID_LOGNAME);
663
if (strncmp(*ep, "MAIL=", 5) == 0)
664
SET(didvar, DID_MAIL);
667
if (strncmp(*ep, "PATH=", 5) == 0)
668
SET(didvar, DID_PATH);
671
if (strncmp(*ep, "SHELL=", 6) == 0)
672
SET(didvar, DID_SHELL);
675
if (strncmp(*ep, "TERM=", 5) == 0)
676
SET(didvar, DID_TERM);
679
if (strncmp(*ep, "USER=", 5) == 0)
680
SET(didvar, DID_USER);
681
if (strncmp(*ep, "USERNAME=", 5) == 0)
682
SET(didvar, DID_USERNAME);
685
sudo_putenv(*ep, FALSE, FALSE);
688
didvar |= didvar << 8; /* convert DID_* to KEPT_* */
691
* Add in defaults. In -i mode these come from the runas user,
692
* otherwise they may be from the user's environment (depends
693
* on sudoers options).
695
if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
696
sudo_setenv("SHELL", runas_pw->pw_shell, ISSET(didvar, DID_SHELL));
697
sudo_setenv("LOGNAME", runas_pw->pw_name,
698
ISSET(didvar, DID_LOGNAME));
699
sudo_setenv("USER", runas_pw->pw_name, ISSET(didvar, DID_USER));
700
sudo_setenv("USERNAME", runas_pw->pw_name,
701
ISSET(didvar, DID_USERNAME));
703
if (!ISSET(didvar, DID_SHELL))
704
sudo_setenv("SHELL", sudo_user.pw->pw_shell, FALSE);
705
if (!ISSET(didvar, DID_LOGNAME))
706
sudo_setenv("LOGNAME", user_name, FALSE);
707
if (!ISSET(didvar, DID_USER))
708
sudo_setenv("USER", user_name, FALSE);
709
if (!ISSET(didvar, DID_USERNAME))
710
sudo_setenv("USERNAME", user_name, FALSE);
713
* Set MAIL to target user in -i mode or if MAIL is not preserved
714
* from user's environment.
716
if (ISSET(sudo_mode, MODE_LOGIN_SHELL) || !ISSET(didvar, KEPT_MAIL)) {
718
if (cp[sizeof(_PATH_MAILDIR) - 2] == '/')
719
easprintf(&cp, "MAIL=%s%s", _PATH_MAILDIR, runas_pw->pw_name);
721
easprintf(&cp, "MAIL=%s/%s", _PATH_MAILDIR, runas_pw->pw_name);
722
sudo_putenv(cp, ISSET(didvar, DID_MAIL), TRUE);
725
/* Reset HOME based on target user if configured to. */
726
if (ISSET(sudo_mode, MODE_RUN)) {
727
if (def_always_set_home || ISSET(sudo_mode, MODE_RESET_HOME) ||
728
(ISSET(sudo_mode, MODE_SHELL) && def_set_home))
733
* Copy environ entries as long as they don't match env_delete or
736
for (ep = old_envp; *ep; ep++) {
739
/* Skip variables with values beginning with () (bash functions) */
740
if ((cp = strchr(*ep, '=')) != NULL) {
741
if (strncmp(cp, "=() ", 3) == 0)
746
* First check variables against the blacklist in env_delete.
747
* If no match there check for '%' and '/' characters.
749
okvar = matches_env_delete(*ep) != TRUE;
751
okvar = matches_env_check(*ep) != FALSE;
754
if (strncmp(*ep, "SUDO_PS1=", 9) == 0)
756
else if (strncmp(*ep, "PATH=", 5) == 0)
757
SET(didvar, DID_PATH);
758
else if (strncmp(*ep, "TERM=", 5) == 0)
759
SET(didvar, DID_TERM);
760
sudo_putenv(*ep, FALSE, FALSE);
764
/* Replace the PATH envariable with a secure one? */
765
if (def_secure_path && !user_is_exempt()) {
766
sudo_setenv("PATH", def_secure_path, TRUE);
767
SET(didvar, DID_PATH);
770
/* Set $USER, $LOGNAME and $USERNAME to target if "set_logname" is true. */
771
if (def_set_logname && !ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
772
if (!ISSET(didvar, KEPT_LOGNAME))
773
sudo_setenv("LOGNAME", runas_pw->pw_name, TRUE);
774
if (!ISSET(didvar, KEPT_USER))
775
sudo_setenv("USER", runas_pw->pw_name, TRUE);
776
if (!ISSET(didvar, KEPT_USERNAME))
777
sudo_setenv("USERNAME", runas_pw->pw_name, TRUE);
780
/* Set $HOME to target user if not preserving user's value. */
781
if (reset_home && !ISSET(didvar, KEPT_HOME))
782
sudo_setenv("HOME", runas_pw->pw_dir, TRUE);
784
/* Provide default values for $TERM and $PATH if they are not set. */
785
if (!ISSET(didvar, DID_TERM))
786
sudo_putenv("TERM=unknown", FALSE, FALSE);
787
if (!ISSET(didvar, DID_PATH))
788
sudo_setenv("PATH", _PATH_STDPATH, FALSE);
791
* Preload a noexec file? For a list of LD_PRELOAD-alikes, see
792
* http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html
793
* XXX - should prepend to original value, if any
795
if (noexec && def_noexec_file != NULL) {
796
#if defined(__darwin__) || defined(__APPLE__)
797
sudo_setenv("DYLD_INSERT_LIBRARIES", def_noexec_file, TRUE);
798
sudo_setenv("DYLD_FORCE_FLAT_NAMESPACE", "", TRUE);
800
# if defined(__osf__) || defined(__sgi)
801
easprintf(&cp, "%s:DEFAULT", def_noexec_file);
802
sudo_setenv("_RLD_LIST", cp, TRUE);
806
sudo_setenv("LDR_PRELOAD", def_noexec_file, TRUE);
808
sudo_setenv("LD_PRELOAD", def_noexec_file, TRUE);
810
# endif /* __osf__ || __sgi */
811
#endif /* __darwin__ || __APPLE__ */
814
/* Set PS1 if SUDO_PS1 is set. */
816
sudo_putenv(ps1, TRUE, TRUE);
818
/* Add the SUDO_COMMAND envariable (cmnd + args). */
820
easprintf(&cp, "%s %s", user_cmnd, user_args);
821
sudo_setenv("SUDO_COMMAND", cp, TRUE);
824
sudo_setenv("SUDO_COMMAND", user_cmnd, TRUE);
827
/* Add the SUDO_USER, SUDO_UID, SUDO_GID environment variables. */
828
sudo_setenv("SUDO_USER", user_name, TRUE);
829
snprintf(idbuf, sizeof(idbuf), "%lu", (unsigned long) user_uid);
830
sudo_setenv("SUDO_UID", idbuf, TRUE);
831
snprintf(idbuf, sizeof(idbuf), "%lu", (unsigned long) user_gid);
832
sudo_setenv("SUDO_GID", idbuf, TRUE);
834
/* Free old environment. */
839
insert_env_vars(env_vars)
840
struct list_member *env_vars;
842
struct list_member *cur;
844
/* Add user-specified environment variables. */
845
for (cur = env_vars; cur != NULL; cur = cur->next)
850
* Validate the list of environment variables passed in on the command
851
* line against env_delete, env_check, and env_keep.
852
* Calls log_error() if any specified variables are not allowed.
855
validate_env_vars(env_vars)
856
struct list_member *env_vars;
858
struct list_member *var;
859
char *eq, *bad = NULL;
860
size_t len, blen = 0, bsize = 0;
863
/* Add user-specified environment variables. */
864
for (var = env_vars; var != NULL; var = var->next) {
865
if (def_secure_path && !user_is_exempt() &&
866
strncmp(var->value, "PATH=", 5) == 0) {
868
} else if (def_env_reset) {
869
okvar = matches_env_check(var->value);
871
okvar = matches_env_keep(var->value);
873
okvar = matches_env_delete(var->value) == FALSE;
875
okvar = matches_env_check(var->value) != FALSE;
877
if (okvar == FALSE) {
878
/* Not allowed, add to error string, allocating as needed. */
879
if ((eq = strchr(var->value, '=')) != NULL)
881
len = strlen(var->value) + 2;
882
if (blen + len >= bsize) {
885
} while (blen + len >= bsize);
886
bad = erealloc(bad, bsize);
889
strlcat(bad, var->value, bsize);
890
strlcat(bad, ", ", bsize);
897
bad[blen - 2] = '\0'; /* remove trailing ", " */
899
"sorry, you are not allowed to set the following environment variables: %s", bad);
906
* Read in /etc/environment ala AIX and Linux.
907
* Lines may be in either of three formats:
911
* with an optional "export" prefix so the shell can source the file.
912
* Invalid lines, blank lines, or lines consisting solely of a comment
913
* character are skipped.
916
read_env_file(path, overwrite)
921
char *cp, *var, *val;
922
size_t var_len, val_len;
924
if ((fp = fopen(path, "r")) == NULL)
927
while ((var = sudo_parseln(fp)) != NULL) {
928
/* Skip blank or comment lines */
932
/* Skip optional "export " */
933
if (strncmp(var, "export", 6) == 0 && isspace((unsigned char) var[6])) {
935
while (isspace((unsigned char) *var)) {
940
/* Must be of the form name=["']value['"] */
941
for (val = var; *val != '\0' && *val != '='; val++)
943
if (var == val || *val != '=')
945
var_len = (size_t)(val - var);
946
val_len = strlen(++val);
948
/* Strip leading and trailing single/double quotes */
949
if ((val[0] == '\'' || val[0] == '\"') && val[0] == val[val_len - 1]) {
950
val[val_len - 1] = '\0';
955
cp = emalloc(var_len + 1 + val_len + 1);
956
memcpy(cp, var, var_len + 1); /* includes '=' */
957
memcpy(cp + var_len + 1, val, val_len + 1); /* includes NUL */
959
sudo_putenv(cp, TRUE, overwrite);
967
struct list_member *cur;
970
/* Fill in the "env_delete" list. */
971
for (p = initial_badenv_table; *p; p++) {
972
cur = emalloc(sizeof(struct list_member));
973
cur->value = estrdup(*p);
974
cur->next = def_env_delete;
975
def_env_delete = cur;
978
/* Fill in the "env_check" list. */
979
for (p = initial_checkenv_table; *p; p++) {
980
cur = emalloc(sizeof(struct list_member));
981
cur->value = estrdup(*p);
982
cur->next = def_env_check;
986
/* Fill in the "env_keep" list. */
987
for (p = initial_keepenv_table; *p; p++) {
988
cur = emalloc(sizeof(struct list_member));
989
cur->value = estrdup(*p);
990
cur->next = def_env_keep;