Imported Upstream version 1.8.3
[debian/sudo] / plugins / sudoers / sudoers.c
1 /*
2  * Copyright (c) 1993-1996, 1998-2011 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  * For a brief history of sudo, please see the HISTORY file included
21  * with this distribution.
22  */
23
24 #define _SUDO_MAIN
25
26 #ifdef __TANDEM
27 # include <floss.h>
28 #endif
29
30 #include <config.h>
31
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/param.h>
35 #include <sys/socket.h>
36 #include <stdio.h>
37 #ifdef STDC_HEADERS
38 # include <stdlib.h>
39 # include <stddef.h>
40 #else
41 # ifdef HAVE_STDLIB_H
42 #  include <stdlib.h>
43 # endif
44 #endif /* STDC_HEADERS */
45 #ifdef HAVE_STRING_H
46 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
47 #  include <memory.h>
48 # endif
49 # include <string.h>
50 #endif /* HAVE_STRING_H */
51 #ifdef HAVE_STRINGS_H
52 # include <strings.h>
53 #endif /* HAVE_STRINGS_H */
54 #ifdef HAVE_UNISTD_H
55 # include <unistd.h>
56 #endif /* HAVE_UNISTD_H */
57 #include <pwd.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <signal.h>
61 #include <grp.h>
62 #include <time.h>
63 #ifdef HAVE_SETLOCALE
64 # include <locale.h>
65 #endif
66 #include <netinet/in.h>
67 #include <netdb.h>
68 #ifdef HAVE_LOGIN_CAP_H
69 # include <login_cap.h>
70 # ifndef LOGIN_DEFROOTCLASS
71 #  define LOGIN_DEFROOTCLASS    "daemon"
72 # endif
73 #endif
74 #ifdef HAVE_SELINUX
75 # include <selinux/selinux.h>
76 #endif
77 #include <ctype.h>
78 #include <setjmp.h>
79
80 #include "sudoers.h"
81 #include "interfaces.h"
82 #include "sudoers_version.h"
83 #include "auth/sudo_auth.h"
84
85 /*
86  * Prototypes
87  */
88 static void init_vars(char * const *);
89 static int set_cmnd(void);
90 static void set_loginclass(struct passwd *);
91 static void set_runaspw(const char *);
92 static void set_runasgr(const char *);
93 static int cb_runas_default(const char *);
94 static int sudoers_policy_version(int verbose);
95 static int deserialize_info(char * const settings[], char * const user_info[]);
96 static char *find_editor(int nfiles, char **files, char ***argv_out);
97 static void create_admin_success_flag(void);
98
99 /*
100  * Globals
101  */
102 const char *sudoers_file = _PATH_SUDOERS;
103 mode_t sudoers_mode = SUDOERS_MODE;
104 uid_t sudoers_uid = SUDOERS_UID;
105 gid_t sudoers_gid = SUDOERS_GID;
106 struct sudo_user sudo_user;
107 struct passwd *list_pw;
108 struct interface *interfaces;
109 int long_list;
110 int debug_level;
111 uid_t timestamp_uid;
112 extern int errorlineno;
113 extern int parse_error;
114 extern char *errorfile;
115 #ifdef HAVE_LOGIN_CAP_H
116 login_cap_t *lc;
117 #endif /* HAVE_LOGIN_CAP_H */
118 #ifdef HAVE_BSD_AUTH_H
119 char *login_style;
120 #endif /* HAVE_BSD_AUTH_H */
121 sudo_conv_t sudo_conv;
122 sudo_printf_t sudo_printf;
123 int sudo_mode;
124
125 static char *prev_user;
126 static char *runas_user;
127 static char *runas_group;
128 static struct sudo_nss_list *snl;
129 static const char *interfaces_string;
130 static sigaction_t saved_sa_int, saved_sa_quit, saved_sa_tstp;
131
132 /* XXX - must be extern for audit bits of sudo_auth.c */
133 int NewArgc;
134 char **NewArgv;
135
136 /* plugin_error.c */
137 extern sigjmp_buf error_jmp;
138
139 static int
140 sudoers_policy_open(unsigned int version, sudo_conv_t conversation,
141     sudo_printf_t plugin_printf, char * const settings[],
142     char * const user_info[], char * const envp[])
143 {
144     volatile int sources = 0;
145     sigaction_t sa;
146     struct sudo_nss *nss;
147
148     if (!sudo_conv)
149         sudo_conv = conversation;
150     if (!sudo_printf)
151         sudo_printf = plugin_printf;
152
153     if (sigsetjmp(error_jmp, 1)) {
154         /* called via error(), errorx() or log_error() */
155         rewind_perms();
156         return -1;
157     }
158
159     bindtextdomain("sudoers", LOCALEDIR);
160
161     /*
162      * Signal setup:
163      *  Ignore keyboard-generated signals so the user cannot interrupt
164      *  us at some point and avoid the logging.
165      *  Install handler to wait for children when they exit.
166      */
167     zero_bytes(&sa, sizeof(sa));
168     sigemptyset(&sa.sa_mask);
169     sa.sa_flags = SA_RESTART;
170     sa.sa_handler = SIG_IGN;
171     (void) sigaction(SIGINT, &sa, &saved_sa_int);
172     (void) sigaction(SIGQUIT, &sa, &saved_sa_quit);
173     (void) sigaction(SIGTSTP, &sa, &saved_sa_tstp);
174
175     sudo_setpwent();
176     sudo_setgrent();
177
178     /* Initialize environment functions (including replacements). */
179     env_init(envp);
180
181     /* Setup defaults data structures. */
182     init_defaults();
183
184     /* Parse settings and user_info */
185     sudo_mode = deserialize_info(settings, user_info);
186
187     init_vars(envp);            /* XXX - move this later? */
188
189     /* Parse nsswitch.conf for sudoers order. */
190     snl = sudo_read_nss();
191
192     /* LDAP or NSS may modify the euid so we need to be root for the open. */
193     set_perms(PERM_INITIAL);
194     set_perms(PERM_ROOT);
195
196     /* Open and parse sudoers, set global defaults */
197     tq_foreach_fwd(snl, nss) {
198         if (nss->open(nss) == 0 && nss->parse(nss) == 0) {
199             sources++;
200             if (nss->setdefs(nss) != 0)
201                 log_error(NO_STDERR|NO_EXIT, _("problem with defaults entries"));
202         }
203     }
204     if (sources == 0) {
205         warningx(_("no valid sudoers sources found, quitting"));
206         return -1;
207     }
208
209     /* XXX - collect post-sudoers parse settings into a function */
210
211     /*
212      * Initialize external group plugin, if any.
213      */
214     if (def_group_plugin) {
215         if (group_plugin_load(def_group_plugin) != TRUE)
216             def_group_plugin = NULL;
217     }
218
219     /*
220      * Set runas passwd/group entries based on command line or sudoers.
221      * Note that if runas_group was specified without runas_user we
222      * defer setting runas_pw so the match routines know to ignore it.
223      */
224     if (runas_group != NULL) {
225         set_runasgr(runas_group);
226         if (runas_user != NULL)
227             set_runaspw(runas_user);
228     } else
229         set_runaspw(runas_user ? runas_user : def_runas_default);
230
231     if (!update_defaults(SETDEF_RUNAS))
232         log_error(NO_STDERR|NO_EXIT, _("problem with defaults entries"));
233
234     if (def_fqdn)
235         set_fqdn();     /* deferred until after sudoers is parsed */
236
237     /* Set login class if applicable. */
238     set_loginclass(sudo_user.pw);
239
240     restore_perms();
241
242     return TRUE;
243 }
244
245 static void
246 sudoers_policy_close(int exit_status, int error_code)
247 {
248     if (sigsetjmp(error_jmp, 1)) {
249         /* called via error(), errorx() or log_error() */
250         return;
251     }
252
253     /* We do not currently log the exit status. */
254     if (error_code)
255         warningx(_("unable to execute %s: %s"), safe_cmnd, strerror(error_code));
256
257     /* Close the session we opened in sudoers_policy_init_session(). */
258     if (ISSET(sudo_mode, MODE_RUN|MODE_EDIT))
259         (void)sudo_auth_end_session(runas_pw);
260
261     /* Free remaining references to password and group entries. */
262     pw_delref(sudo_user.pw);
263     pw_delref(runas_pw);
264     if (runas_gr != NULL)
265         gr_delref(runas_gr);
266     if (user_group_list != NULL)
267         grlist_delref(user_group_list);
268 }
269
270 /*
271  * The init_session function is called before executing the command
272  * and before uid/gid changes occur.
273  */
274 static int
275 sudoers_policy_init_session(struct passwd *pwd)
276 {
277     if (sigsetjmp(error_jmp, 1)) {
278         /* called via error(), errorx() or log_error() */
279         return -1;
280     }
281
282     return sudo_auth_begin_session(pwd);
283 }
284
285 static int
286 sudoers_policy_main(int argc, char * const argv[], int pwflag, char *env_add[],
287     char **command_infop[], char **argv_out[], char **user_env_out[])
288 {
289     static char *command_info[32]; /* XXX */
290     char **edit_argv = NULL;
291     struct sudo_nss *nss;
292     int cmnd_status = -1, validated;
293     volatile int info_len = 0;
294     volatile int rval = TRUE;
295
296     if (sigsetjmp(error_jmp, 1)) {
297         /* error recovery via error(), errorx() or log_error() */
298         rval = -1;
299         goto done;
300     }
301
302     /* Is root even allowed to run sudo? */
303     if (user_uid == 0 && !def_root_sudo) {
304         warningx(_("sudoers specifies that root is not allowed to sudo"));
305         goto bad;
306     }    
307
308     /* Check for -C overriding def_closefrom. */
309     if (user_closefrom >= 0 && user_closefrom != def_closefrom) {
310         if (!def_closefrom_override) {
311             warningx(_("you are not permitted to use the -C option"));
312             goto bad;
313         }
314         def_closefrom = user_closefrom;
315     }
316
317     set_perms(PERM_INITIAL);
318
319     /* Environment variables specified on the command line. */
320     if (env_add != NULL && env_add[0] != NULL)
321         sudo_user.env_vars = env_add;
322
323     /*
324      * Make a local copy of argc/argv, with special handling
325      * for pseudo-commands and the '-i' option.
326      */
327     if (argc == 0) {
328         NewArgc = 1;
329         NewArgv = emalloc2(NewArgc + 1, sizeof(char *));
330         NewArgv[0] = user_cmnd;
331         NewArgv[1] = NULL;
332     } else {
333         /* Must leave an extra slot before NewArgv for bash's --login */
334         NewArgc = argc;
335         NewArgv = emalloc2(NewArgc + 2, sizeof(char *));
336         memcpy(++NewArgv, argv, argc * sizeof(char *));
337         NewArgv[NewArgc] = NULL;
338         if (ISSET(sudo_mode, MODE_LOGIN_SHELL))
339             NewArgv[0] = estrdup(runas_pw->pw_shell);
340     }
341
342     /* If given the -P option, set the "preserve_groups" flag. */
343     if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS))
344         def_preserve_groups = TRUE;
345
346     /* Find command in path */
347     cmnd_status = set_cmnd();
348     if (cmnd_status == -1) {
349         rval = -1;
350         goto done;
351     }
352
353 #ifdef HAVE_SETLOCALE
354     if (!setlocale(LC_ALL, def_sudoers_locale)) {
355         warningx(_("unable to set locale to \"%s\", using \"C\""),
356             def_sudoers_locale);
357         setlocale(LC_ALL, "C");
358     }
359 #endif
360
361     /*
362      * Check sudoers sources.
363      */
364     validated = FLAG_NO_USER | FLAG_NO_HOST;
365     tq_foreach_fwd(snl, nss) {
366         validated = nss->lookup(nss, validated, pwflag);
367
368         if (ISSET(validated, VALIDATE_OK)) {
369             /* Handle "= auth" in netsvc.conf */
370             if (nss->ret_if_found)
371                 break;
372         } else {
373             /* Handle [NOTFOUND=return] */
374             if (nss->ret_if_notfound)
375                 break;
376         }
377     }
378
379     if (safe_cmnd == NULL)
380         safe_cmnd = estrdup(user_cmnd);
381
382 #ifdef HAVE_SETLOCALE
383     setlocale(LC_ALL, "");
384 #endif
385
386     /* If only a group was specified, set runas_pw based on invoking user. */
387     if (runas_pw == NULL)
388         set_runaspw(user_name);
389
390     /*
391      * Look up the timestamp dir owner if one is specified.
392      */
393     if (def_timestampowner) {
394         struct passwd *pw;
395
396         if (*def_timestampowner == '#')
397             pw = sudo_getpwuid(atoi(def_timestampowner + 1));
398         else
399             pw = sudo_getpwnam(def_timestampowner);
400         if (!pw)
401             log_error(0, _("timestamp owner (%s): No such user"),
402                 def_timestampowner);
403         timestamp_uid = pw->pw_uid;
404         pw_delref(pw);
405     }
406
407     /* If no command line args and "shell_noargs" is not set, error out. */
408     if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs) {
409         rval = -2; /* usage error */
410         goto done;
411     }
412
413     /* Bail if a tty is required and we don't have one.  */
414     if (def_requiretty) {
415         int fd = open(_PATH_TTY, O_RDWR|O_NOCTTY);
416         if (fd == -1) {
417             audit_failure(NewArgv, _("no tty"));
418             warningx(_("sorry, you must have a tty to run sudo"));
419             goto bad;
420         } else
421             (void) close(fd);
422     }
423
424     /*
425      * We don't reset the environment for sudoedit or if the user
426      * specified the -E command line flag and they have setenv privs.
427      */
428     if (ISSET(sudo_mode, MODE_EDIT) ||
429         (ISSET(sudo_mode, MODE_PRESERVE_ENV) && def_setenv))
430         def_env_reset = FALSE;
431
432     /* Build a new environment that avoids any nasty bits. */
433     rebuild_env();
434
435     /* Require a password if sudoers says so.  */
436     if (def_authenticate) {
437         int rc = check_user(validated, sudo_mode);
438         if (rc != TRUE) {
439             rval = rc;
440             goto done;
441         }
442     }
443
444     /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */
445     /* XXX - causes confusion when root is not listed in sudoers */
446     if (sudo_mode & (MODE_RUN | MODE_EDIT) && prev_user != NULL) {
447         if (user_uid == 0 && strcmp(prev_user, "root") != 0) {
448             struct passwd *pw;
449
450             if ((pw = sudo_getpwnam(prev_user)) != NULL) {
451                     if (sudo_user.pw != NULL)
452                         pw_delref(sudo_user.pw);
453                     sudo_user.pw = pw;
454             }
455         }
456     }
457
458     /* If the user was not allowed to run the command we are done. */
459     if (!ISSET(validated, VALIDATE_OK)) {
460         if (ISSET(validated, FLAG_NO_USER | FLAG_NO_HOST)) {
461             audit_failure(NewArgv, _("No user or host"));
462             log_denial(validated, 1);
463         } else {
464             if (def_path_info) {
465                 /*
466                  * We'd like to not leak path info at all here, but that can
467                  * *really* confuse the users.  To really close the leak we'd
468                  * have to say "not allowed to run foo" even when the problem
469                  * is just "no foo in path" since the user can trivially set
470                  * their path to just contain a single dir.
471                  */
472                 log_denial(validated,
473                     !(cmnd_status == NOT_FOUND_DOT || cmnd_status == NOT_FOUND));
474                 if (cmnd_status == NOT_FOUND)
475                     warningx(_("%s: command not found"), user_cmnd);
476                 else if (cmnd_status == NOT_FOUND_DOT)
477                     warningx(_("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run."), user_cmnd, user_cmnd, user_cmnd);
478             } else {
479                 /* Just tell the user they are not allowed to run foo. */
480                 log_denial(validated, 1);
481             }
482             audit_failure(NewArgv, _("validation failure"));
483         }
484         goto bad;
485     }
486
487     /* Create Ubuntu-style dot file to indicate sudo was successful. */
488     create_admin_success_flag();
489
490     /* Finally tell the user if the command did not exist. */
491     if (cmnd_status == NOT_FOUND_DOT) {
492         audit_failure(NewArgv, _("command in current directory"));
493         warningx(_("ignoring `%s' found in '.'\nUse `sudo ./%s' if this is the `%s' you wish to run."), user_cmnd, user_cmnd, user_cmnd);
494         goto bad;
495     } else if (cmnd_status == NOT_FOUND) {
496         audit_failure(NewArgv, _("%s: command not found"), user_cmnd);
497         warningx(_("%s: command not found"), user_cmnd);
498         goto bad;
499     }
500
501     /* If user specified env vars make sure sudoers allows it. */
502     if (ISSET(sudo_mode, MODE_RUN) && !def_setenv) {
503         if (ISSET(sudo_mode, MODE_PRESERVE_ENV)) {
504             warningx(_("sorry, you are not allowed to preserve the environment"));
505             goto bad;
506         } else
507             validate_env_vars(sudo_user.env_vars);
508     }
509
510     if (ISSET(sudo_mode, (MODE_RUN | MODE_EDIT)) && (def_log_input || def_log_output)) {
511         if (def_iolog_file && def_iolog_dir) {
512             command_info[info_len++] = expand_iolog_path("iolog_path=",
513                 def_iolog_dir, def_iolog_file, &sudo_user.iolog_file);
514             sudo_user.iolog_file++;
515         }
516         if (def_log_input) {
517             command_info[info_len++] = estrdup("iolog_stdin=true");
518             command_info[info_len++] = estrdup("iolog_ttyin=true");
519         }
520         if (def_log_output) {
521             command_info[info_len++] = estrdup("iolog_stdout=true");
522             command_info[info_len++] = estrdup("iolog_stderr=true");
523             command_info[info_len++] = estrdup("iolog_ttyout=true");
524         }
525         if (def_compress_io)
526             command_info[info_len++] = estrdup("iolog_compress=true");
527     }
528
529     log_allowed(validated);
530     if (ISSET(sudo_mode, MODE_CHECK))
531         rval = display_cmnd(snl, list_pw ? list_pw : sudo_user.pw);
532     else if (ISSET(sudo_mode, MODE_LIST))
533         display_privs(snl, list_pw ? list_pw : sudo_user.pw); /* XXX - return val */
534
535     /* Cleanup sudoers sources */
536     tq_foreach_fwd(snl, nss) {
537         nss->close(nss);
538     }
539     if (def_group_plugin)
540         group_plugin_unload();
541
542     if (ISSET(sudo_mode, (MODE_VALIDATE|MODE_CHECK|MODE_LIST))) {
543         /* rval already set appropriately */
544         goto done;
545     }
546
547     /*
548      * Set umask based on sudoers.
549      * If user's umask is more restrictive, OR in those bits too
550      * unless umask_override is set.
551      */
552     if (def_umask != 0777) {
553         mode_t mask = def_umask;
554         if (!def_umask_override) {
555             mode_t omask = umask(mask);
556             mask |= omask;
557             umask(omask);
558         }
559         easprintf(&command_info[info_len++], "umask=0%o", (unsigned int)mask);
560     }
561
562     if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) {
563         char *p;
564
565         /* Convert /bin/sh -> -sh so shell knows it is a login shell */
566         if ((p = strrchr(NewArgv[0], '/')) == NULL)
567             p = NewArgv[0];
568         *p = '-';
569         NewArgv[0] = p;
570
571         /* Set cwd to run user's homedir. */
572         command_info[info_len++] = fmt_string("cwd", runas_pw->pw_dir);
573
574         /*
575          * Newer versions of bash require the --login option to be used
576          * in conjunction with the -c option even if the shell name starts
577          * with a '-'.  Unfortunately, bash 1.x uses -login, not --login
578          * so this will cause an error for that.
579          */
580         if (NewArgc > 1 && strcmp(NewArgv[0], "-bash") == 0 &&
581             strcmp(NewArgv[1], "-c") == 0) {
582             /* Use the extra slot before NewArgv so we can store --login. */
583             NewArgv--;
584             NewArgc++;
585             NewArgv[0] = NewArgv[1];
586             NewArgv[1] = "--login";
587         }
588
589 #if defined(__linux__) || defined(_AIX)
590         /* Insert system-wide environment variables. */
591         read_env_file(_PATH_ENVIRONMENT, TRUE);
592 #endif
593     }
594
595     /* Insert system-wide environment variables. */
596     if (def_env_file)
597         read_env_file(def_env_file, FALSE);
598
599     /* Insert user-specified environment variables. */
600     insert_env_vars(sudo_user.env_vars);
601
602     /* Restore signal handlers before we exec. */
603     (void) sigaction(SIGINT, &saved_sa_int, NULL);
604     (void) sigaction(SIGQUIT, &saved_sa_quit, NULL);
605     (void) sigaction(SIGTSTP, &saved_sa_tstp, NULL);
606
607     if (ISSET(sudo_mode, MODE_EDIT)) {
608         char *editor = find_editor(NewArgc - 1, NewArgv + 1, &edit_argv);
609         if (editor == NULL)
610             goto bad;
611         command_info[info_len++] = fmt_string("command", editor);
612         command_info[info_len++] = estrdup("sudoedit=true");
613     } else {
614         command_info[info_len++] = fmt_string("command", safe_cmnd);
615     }
616     if (def_stay_setuid) {
617         easprintf(&command_info[info_len++], "runas_uid=%u",
618             (unsigned int)user_uid);
619         easprintf(&command_info[info_len++], "runas_gid=%u",
620             (unsigned int)user_gid);
621         easprintf(&command_info[info_len++], "runas_euid=%u",
622             (unsigned int)runas_pw->pw_uid);
623         easprintf(&command_info[info_len++], "runas_egid=%u",
624             runas_gr ? (unsigned int)runas_gr->gr_gid :
625             (unsigned int)runas_pw->pw_gid);
626     } else {
627         easprintf(&command_info[info_len++], "runas_uid=%u",
628             (unsigned int)runas_pw->pw_uid);
629         easprintf(&command_info[info_len++], "runas_gid=%u",
630             runas_gr ? (unsigned int)runas_gr->gr_gid :
631             (unsigned int)runas_pw->pw_gid);
632     }
633     if (def_preserve_groups) {
634         command_info[info_len++] = "preserve_groups=true";
635     } else {
636         int i, len;
637         size_t glsize;
638         char *cp, *gid_list;
639         struct group_list *grlist = get_group_list(runas_pw);
640
641         glsize = sizeof("runas_groups=") - 1 + (grlist->ngids * (MAX_UID_T_LEN + 1));
642         gid_list = emalloc(glsize);
643         memcpy(gid_list, "runas_groups=", sizeof("runas_groups=") - 1);
644         cp = gid_list + sizeof("runas_groups=") - 1;
645         for (i = 0; i < grlist->ngids; i++) {
646             /* XXX - check rval */
647             len = snprintf(cp, glsize - (cp - gid_list), "%s%u",
648                  i ? "," : "", (unsigned int) grlist->gids[i]);
649             cp += len;
650         }
651         command_info[info_len++] = gid_list;
652         grlist_delref(grlist);
653     }
654     if (def_closefrom >= 0)
655         easprintf(&command_info[info_len++], "closefrom=%d", def_closefrom);
656     if (def_noexec)
657         command_info[info_len++] = estrdup("noexec=true");
658     if (def_noexec_file)
659         command_info[info_len++] = fmt_string("noexec_file", def_noexec_file);
660     if (def_set_utmp)
661         command_info[info_len++] = estrdup("set_utmp=true");
662     if (def_use_pty)
663         command_info[info_len++] = estrdup("use_pty=true");
664     if (def_utmp_runas)
665         command_info[info_len++] = fmt_string("utmp_user", runas_pw->pw_name);
666 #ifdef HAVE_LOGIN_CAP_H
667     if (lc != NULL)
668         command_info[info_len++] = fmt_string("login_class", lc->lc_class);
669 #endif /* HAVE_LOGIN_CAP_H */
670 #ifdef HAVE_SELINUX
671     if (user_role != NULL)
672         command_info[info_len++] = fmt_string("selinux_role", user_role);
673     if (user_type != NULL)
674         command_info[info_len++] = fmt_string("selinux_type", user_type);
675 #endif /* HAVE_SELINUX */
676
677     /* Must audit before uid change. */
678     audit_success(NewArgv);
679
680     *command_infop = command_info;
681
682     *argv_out = edit_argv ? edit_argv : NewArgv;
683     *user_env_out = env_get(); /* our private copy */
684
685     goto done;
686
687 bad:
688     rval = FALSE;
689
690 done:
691     rewind_perms();
692
693     /* Close the password and group files and free up memory. */
694     sudo_endpwent();
695     sudo_endgrent();
696
697     return rval;
698 }
699
700 static int
701 sudoers_policy_check(int argc, char * const argv[], char *env_add[],
702     char **command_infop[], char **argv_out[], char **user_env_out[])
703 {
704     if (!ISSET(sudo_mode, MODE_EDIT))
705         SET(sudo_mode, MODE_RUN);
706
707     return sudoers_policy_main(argc, argv, 0, env_add, command_infop,
708         argv_out, user_env_out);
709 }
710
711 static int
712 sudoers_policy_validate(void)
713 {
714     user_cmnd = "validate";
715     SET(sudo_mode, MODE_VALIDATE);
716
717     return sudoers_policy_main(0, NULL, I_VERIFYPW, NULL, NULL, NULL, NULL);
718 }
719
720 static void
721 sudoers_policy_invalidate(int remove)
722 {
723     user_cmnd = "kill";
724     if (sigsetjmp(error_jmp, 1) == 0) {
725         remove_timestamp(remove);
726         plugin_cleanup(0);
727     }
728 }
729
730 static int
731 sudoers_policy_list(int argc, char * const argv[], int verbose,
732     const char *list_user)
733 {
734     int rval;
735
736     user_cmnd = "list";
737     if (argc)
738         SET(sudo_mode, MODE_CHECK);
739     else
740         SET(sudo_mode, MODE_LIST);
741     if (verbose)
742         long_list = 1;
743     if (list_user) {
744         list_pw = sudo_getpwnam(list_user);
745         if (list_pw == NULL) {
746             warningx(_("unknown user: %s"), list_user);
747             return -1;
748         }
749     }
750     rval = sudoers_policy_main(argc, argv, I_LISTPW, NULL, NULL, NULL, NULL);
751     if (list_user) {
752         pw_delref(list_pw);
753         list_pw = NULL;
754     }
755
756     return rval;
757 }
758
759 /*
760  * Initialize timezone, set umask, fill in ``sudo_user'' struct and
761  * load the ``interfaces'' array.
762  */
763 static void
764 init_vars(char * const envp[])
765 {
766     char * const * ep;
767
768 #ifdef HAVE_TZSET
769     (void) tzset();             /* set the timezone if applicable */
770 #endif /* HAVE_TZSET */
771
772     for (ep = envp; *ep; ep++) {
773         /* XXX - don't fill in if empty string */
774         switch (**ep) {
775             case 'K':
776                 if (strncmp("KRB5CCNAME=", *ep, 11) == 0)
777                     user_ccname = *ep + 11;
778                 break;
779             case 'P':
780                 if (strncmp("PATH=", *ep, 5) == 0)
781                     user_path = *ep + 5;
782                 break;
783             case 'S':
784                 if (!user_prompt && strncmp("SUDO_PROMPT=", *ep, 12) == 0)
785                     user_prompt = *ep + 12;
786                 else if (strncmp("SUDO_USER=", *ep, 10) == 0)
787                     prev_user = *ep + 10;
788                 break;
789             }
790     }
791
792     /*
793      * Get a local copy of the user's struct passwd with the shadow password
794      * if necessary.  It is assumed that euid is 0 at this point so we
795      * can read the shadow passwd file if necessary.
796      */
797     if ((sudo_user.pw = sudo_getpwuid(user_uid)) == NULL) {
798         /*
799          * It is not unusual for users to place "sudo -k" in a .logout
800          * file which can cause sudo to be run during reboot after the
801          * YP/NIS/NIS+/LDAP/etc daemon has died.
802          */
803         if (sudo_mode == MODE_KILL || sudo_mode == MODE_INVALIDATE)
804             errorx(1, _("unknown uid: %u"), (unsigned int) user_uid);
805
806         /* Need to make a fake struct passwd for the call to log_error(). */
807         sudo_user.pw = sudo_fakepwnamid(user_name, user_uid, user_gid);
808         log_error(0, _("unknown uid: %u"), (unsigned int) user_uid);
809         /* NOTREACHED */
810     }
811
812     /*
813      * Get group list.
814      */
815     if (user_group_list == NULL)
816         user_group_list = get_group_list(sudo_user.pw);
817
818     /* Set runas callback. */
819     sudo_defs_table[I_RUNAS_DEFAULT].callback = cb_runas_default;
820
821     /* It is now safe to use log_error() and set_perms() */
822 }
823
824 /*
825  * Fill in user_cmnd, user_args, user_base and user_stat variables
826  * and apply any command-specific defaults entries.
827  */
828 static int
829 set_cmnd(void)
830 {
831     int rval;
832     char *path = user_path;
833
834     /* Resolve the path and return. */
835     rval = FOUND;
836     user_stat = emalloc(sizeof(struct stat));
837
838     /* Default value for cmnd, overridden below. */
839     if (user_cmnd == NULL)
840         user_cmnd = NewArgv[0];
841
842     if (sudo_mode & (MODE_RUN | MODE_EDIT | MODE_CHECK)) {
843         if (ISSET(sudo_mode, MODE_RUN | MODE_CHECK)) {
844             if (def_secure_path && !user_is_exempt())
845                 path = def_secure_path;
846             set_perms(PERM_RUNAS);
847             rval = find_path(NewArgv[0], &user_cmnd, user_stat, path,
848                 def_ignore_dot);
849             restore_perms();
850             if (rval != FOUND) {
851                 /* Failed as root, try as invoking user. */
852                 set_perms(PERM_USER);
853                 rval = find_path(NewArgv[0], &user_cmnd, user_stat, path,
854                     def_ignore_dot);
855                 restore_perms();
856             }
857         }
858
859         /* set user_args */
860         if (NewArgc > 1) {
861             char *to, *from, **av;
862             size_t size, n;
863
864             /* Alloc and build up user_args. */
865             for (size = 0, av = NewArgv + 1; *av; av++)
866                 size += strlen(*av) + 1;
867             user_args = emalloc(size);
868             if (ISSET(sudo_mode, MODE_SHELL|MODE_LOGIN_SHELL)) {
869                 /*
870                  * When running a command via a shell, the sudo front-end
871                  * escapes potential meta chars.  We unescape non-spaces
872                  * for sudoers matching and logging purposes.
873                  */
874                 for (to = user_args, av = NewArgv + 1; (from = *av); av++) {
875                     while (*from) {
876                         if (from[0] == '\\' && !isspace((unsigned char)from[1]))
877                             from++;
878                         *to++ = *from++;
879                     }
880                     *to++ = ' ';
881                 }
882                 *--to = '\0';
883             } else {
884                 for (to = user_args, av = NewArgv + 1; *av; av++) {
885                     n = strlcpy(to, *av, size - (to - user_args));
886                     if (n >= size - (to - user_args))
887                         errorx(1, _("internal error, set_cmnd() overflow"));
888                     to += n;
889                     *to++ = ' ';
890                 }
891                 *--to = '\0';
892             }
893         }
894     }
895     if (strlen(user_cmnd) >= PATH_MAX)
896         errorx(1, _("%s: %s"), user_cmnd, strerror(ENAMETOOLONG));
897
898     if ((user_base = strrchr(user_cmnd, '/')) != NULL)
899         user_base++;
900     else
901         user_base = user_cmnd;
902
903     if (!update_defaults(SETDEF_CMND))
904         log_error(NO_STDERR|NO_EXIT, _("problem with defaults entries"));
905
906     return rval;
907 }
908
909 /*
910  * Open sudoers and sanity check mode/owner/type.
911  * Returns a handle to the sudoers file or NULL on error.
912  */
913 FILE *
914 open_sudoers(const char *sudoers, int doedit, int *keepopen)
915 {
916     struct stat statbuf;
917     FILE *fp = NULL;
918     int rootstat;
919
920     /*
921      * Fix the mode and group on sudoers file from old default.
922      * Only works if file system is readable/writable by root.
923      */
924     if ((rootstat = stat_sudoers(sudoers, &statbuf)) == 0 &&
925         sudoers_uid == statbuf.st_uid && sudoers_mode != 0400 &&
926         (statbuf.st_mode & 0007777) == 0400) {
927
928         if (chmod(sudoers, sudoers_mode) == 0) {
929             warningx(_("fixed mode on %s"), sudoers);
930             SET(statbuf.st_mode, sudoers_mode);
931             if (statbuf.st_gid != sudoers_gid) {
932                 if (chown(sudoers, (uid_t) -1, sudoers_gid) == 0) {
933                     warningx(_("set group on %s"), sudoers);
934                     statbuf.st_gid = sudoers_gid;
935                 } else
936                     warning(_("unable to set group on %s"), sudoers);
937             }
938         } else
939             warning(_("unable to fix mode on %s"), sudoers);
940     }
941
942     /*
943      * Sanity checks on sudoers file.  Must be done as sudoers
944      * file owner.  We already did a stat as root, so use that
945      * data if we can't stat as sudoers file owner.
946      */
947     set_perms(PERM_SUDOERS);
948
949     if (rootstat != 0 && stat_sudoers(sudoers, &statbuf) != 0)
950         log_error(USE_ERRNO|NO_EXIT, _("unable to stat %s"), sudoers);
951     else if (!S_ISREG(statbuf.st_mode))
952         log_error(NO_EXIT, _("%s is not a regular file"), sudoers);
953     else if ((statbuf.st_mode & 07577) != sudoers_mode)
954         log_error(NO_EXIT, _("%s is mode 0%o, should be 0%o"), sudoers,
955             (unsigned int) (statbuf.st_mode & 07777),
956             (unsigned int) sudoers_mode);
957     else if (statbuf.st_uid != sudoers_uid)
958         log_error(NO_EXIT, _("%s is owned by uid %u, should be %u"), sudoers,
959             (unsigned int) statbuf.st_uid, (unsigned int) sudoers_uid);
960     else if (statbuf.st_gid != sudoers_gid && ISSET(statbuf.st_mode, S_IRGRP|S_IWGRP))
961         log_error(NO_EXIT, _("%s is owned by gid %u, should be %u"), sudoers,
962             (unsigned int) statbuf.st_gid, (unsigned int) sudoers_gid);
963     else if ((fp = fopen(sudoers, "r")) == NULL)
964         log_error(USE_ERRNO|NO_EXIT, _("unable to open %s"), sudoers);
965     else {
966         /*
967          * Make sure we can actually read sudoers so we can present the
968          * user with a reasonable error message (unlike the lexer).
969          */
970         if (statbuf.st_size != 0 && fgetc(fp) == EOF) {
971             log_error(USE_ERRNO|NO_EXIT, _("unable to read %s"), sudoers);
972             fclose(fp);
973             fp = NULL;
974         }
975     }
976
977     if (fp != NULL) {
978         rewind(fp);
979         (void) fcntl(fileno(fp), F_SETFD, 1);
980     }
981
982     restore_perms();            /* change back to root */
983     return fp;
984 }
985
986 #ifdef HAVE_LOGIN_CAP_H
987 static void
988 set_loginclass(struct passwd *pw)
989 {
990     int errflags;
991
992     /*
993      * Don't make it a fatal error if the user didn't specify the login
994      * class themselves.  We do this because if login.conf gets
995      * corrupted we want the admin to be able to use sudo to fix it.
996      */
997     if (login_class)
998         errflags = NO_MAIL|MSG_ONLY;
999     else
1000         errflags = NO_MAIL|MSG_ONLY|NO_EXIT;
1001
1002     if (login_class && strcmp(login_class, "-") != 0) {
1003         if (user_uid != 0 &&
1004             strcmp(runas_user ? runas_user : def_runas_default, "root") != 0)
1005             errorx(1, _("only root can use `-c %s'"), login_class);
1006     } else {
1007         login_class = pw->pw_class;
1008         if (!login_class || !*login_class)
1009             login_class =
1010                 (pw->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS;
1011     }
1012
1013     lc = login_getclass(login_class);
1014     if (!lc || !lc->lc_class || strcmp(lc->lc_class, login_class) != 0) {
1015         log_error(errflags, _("unknown login class: %s"), login_class);
1016         if (!lc)
1017             lc = login_getclass(NULL);  /* needed for login_getstyle() later */
1018     }
1019 }
1020 #else
1021 static void
1022 set_loginclass(struct passwd *pw)
1023 {
1024 }
1025 #endif /* HAVE_LOGIN_CAP_H */
1026
1027 /*
1028  * Look up the fully qualified domain name and set user_host and user_shost.
1029  */
1030 void
1031 set_fqdn(void)
1032 {
1033 #ifdef HAVE_GETADDRINFO
1034     struct addrinfo *res0, hint;
1035 #else
1036     struct hostent *hp;
1037 #endif
1038     char *p;
1039
1040 #ifdef HAVE_GETADDRINFO
1041     zero_bytes(&hint, sizeof(hint));
1042     hint.ai_family = PF_UNSPEC;
1043     hint.ai_flags = AI_CANONNAME;
1044     if (getaddrinfo(user_host, NULL, &hint, &res0) != 0) {
1045 #else
1046     if (!(hp = gethostbyname(user_host))) {
1047 #endif
1048         log_error(MSG_ONLY|NO_EXIT,
1049             _("unable to resolve host %s"), user_host);
1050     } else {
1051         if (user_shost != user_host)
1052             efree(user_shost);
1053         efree(user_host);
1054 #ifdef HAVE_GETADDRINFO
1055         user_host = estrdup(res0->ai_canonname);
1056         freeaddrinfo(res0);
1057 #else
1058         user_host = estrdup(hp->h_name);
1059 #endif
1060     }
1061     if ((p = strchr(user_host, '.')) != NULL)
1062         user_shost = estrndup(user_host, (size_t)(p - user_host));
1063     else
1064         user_shost = user_host;
1065 }
1066
1067 /*
1068  * Get passwd entry for the user we are going to run commands as
1069  * and store it in runas_pw.  By default, commands run as "root".
1070  */
1071 void
1072 set_runaspw(const char *user)
1073 {
1074     if (runas_pw != NULL)
1075         pw_delref(runas_pw);
1076     if (*user == '#') {
1077         if ((runas_pw = sudo_getpwuid(atoi(user + 1))) == NULL)
1078             runas_pw = sudo_fakepwnam(user, runas_gr ? runas_gr->gr_gid : 0);
1079     } else {
1080         if ((runas_pw = sudo_getpwnam(user)) == NULL)
1081             log_error(NO_MAIL|MSG_ONLY, _("unknown user: %s"), user);
1082     }
1083 }
1084
1085 /*
1086  * Get group entry for the group we are going to run commands as
1087  * and store it in runas_gr.
1088  */
1089 static void
1090 set_runasgr(const char *group)
1091 {
1092     if (runas_gr != NULL)
1093         gr_delref(runas_gr);
1094     if (*group == '#') {
1095         if ((runas_gr = sudo_getgrgid(atoi(group + 1))) == NULL)
1096             runas_gr = sudo_fakegrnam(group);
1097     } else {
1098         if ((runas_gr = sudo_getgrnam(group)) == NULL)
1099             log_error(NO_MAIL|MSG_ONLY, _("unknown group: %s"), group);
1100     }
1101 }
1102
1103 /*
1104  * Callback for runas_default sudoers setting.
1105  */
1106 static int
1107 cb_runas_default(const char *user)
1108 {
1109     /* Only reset runaspw if user didn't specify one. */
1110     if (!runas_user && !runas_group)
1111         set_runaspw(user);
1112     return TRUE;
1113 }
1114
1115 /*
1116  * Cleanup hook for error()/errorx()
1117  */
1118 void
1119 plugin_cleanup(int gotsignal)
1120 {
1121     struct sudo_nss *nss;
1122
1123     if (!gotsignal) {
1124         if (snl != NULL) {
1125             tq_foreach_fwd(snl, nss)
1126                 nss->close(nss);
1127         }
1128         if (def_group_plugin)
1129             group_plugin_unload();
1130         sudo_endpwent();
1131         sudo_endgrent();
1132     }
1133 }
1134
1135 static int
1136 sudoers_policy_version(int verbose)
1137 {
1138     if (sigsetjmp(error_jmp, 1)) {
1139         /* error recovery via error(), errorx() or log_error() */
1140         return -1;
1141     }
1142
1143     sudo_printf(SUDO_CONV_INFO_MSG, _("Sudoers policy plugin version %s\n"),
1144         PACKAGE_VERSION);
1145     sudo_printf(SUDO_CONV_INFO_MSG, _("Sudoers file grammar version %d\n"),
1146         SUDOERS_GRAMMAR_VERSION);
1147
1148     if (verbose) {
1149         sudo_printf(SUDO_CONV_INFO_MSG, _("\nSudoers path: %s\n"), sudoers_file);
1150 #ifdef HAVE_LDAP
1151 # ifdef _PATH_NSSWITCH_CONF
1152         sudo_printf(SUDO_CONV_INFO_MSG, _("nsswitch path: %s\n"), _PATH_NSSWITCH_CONF);
1153 # endif
1154         sudo_printf(SUDO_CONV_INFO_MSG, _("ldap.conf path: %s\n"), _PATH_LDAP_CONF);
1155         sudo_printf(SUDO_CONV_INFO_MSG, _("ldap.secret path: %s\n"), _PATH_LDAP_SECRET);
1156 #endif
1157         dump_auth_methods();
1158         dump_defaults();
1159         sudo_printf(SUDO_CONV_INFO_MSG, "\n");
1160         dump_interfaces(interfaces_string);
1161         sudo_printf(SUDO_CONV_INFO_MSG, "\n");
1162     }
1163     return TRUE;
1164 }
1165
1166 static int
1167 deserialize_info(char * const settings[], char * const user_info[])
1168 {
1169     char * const *cur;
1170     const char *p, *groups = NULL;
1171     int flags = 0;
1172
1173 #define MATCHES(s, v) (strncmp(s, v, sizeof(v) - 1) == 0)
1174
1175     /* Parse command line settings. */
1176     user_closefrom = -1;
1177     for (cur = settings; *cur != NULL; cur++) {
1178         if (MATCHES(*cur, "closefrom=")) {
1179             user_closefrom = atoi(*cur + sizeof("closefrom=") - 1);
1180             continue;
1181         }
1182         if (MATCHES(*cur, "debug_level=")) {
1183             debug_level = atoi(*cur + sizeof("debug_level=") - 1);
1184             continue;
1185         }
1186         if (MATCHES(*cur, "runas_user=")) {
1187             runas_user = *cur + sizeof("runas_user=") - 1;
1188             continue;
1189         }
1190         if (MATCHES(*cur, "runas_group=")) {
1191             runas_group = *cur + sizeof("runas_group=") - 1;
1192             continue;
1193         }
1194         if (MATCHES(*cur, "prompt=")) {
1195             user_prompt = *cur + sizeof("prompt=") - 1;
1196             def_passprompt_override = TRUE;
1197             continue;
1198         }
1199         if (MATCHES(*cur, "set_home=")) {
1200             if (atobool(*cur + sizeof("set_home=") - 1) == TRUE)
1201                 SET(flags, MODE_RESET_HOME);
1202             continue;
1203         }
1204         if (MATCHES(*cur, "preserve_environment=")) {
1205             if (atobool(*cur + sizeof("preserve_environment=") - 1) == TRUE)
1206                 SET(flags, MODE_PRESERVE_ENV);
1207             continue;
1208         }
1209         if (MATCHES(*cur, "run_shell=")) {
1210             if (atobool(*cur + sizeof("run_shell=") - 1) == TRUE)
1211                 SET(flags, MODE_SHELL);
1212             continue;
1213         }
1214         if (MATCHES(*cur, "login_shell=")) {
1215             if (atobool(*cur + sizeof("login_shell=") - 1) == TRUE) {
1216                 SET(flags, MODE_LOGIN_SHELL);
1217                 def_env_reset = TRUE;
1218             }
1219             continue;
1220         }
1221         if (MATCHES(*cur, "implied_shell=")) {
1222             if (atobool(*cur + sizeof("implied_shell=") - 1) == TRUE)
1223                 SET(flags, MODE_IMPLIED_SHELL);
1224             continue;
1225         }
1226         if (MATCHES(*cur, "preserve_groups=")) {
1227             if (atobool(*cur + sizeof("preserve_groups=") - 1) == TRUE)
1228                 SET(flags, MODE_PRESERVE_GROUPS);
1229             continue;
1230         }
1231         if (MATCHES(*cur, "ignore_ticket=")) {
1232             if (atobool(*cur + sizeof("ignore_ticket=") - 1) == TRUE)
1233                 SET(flags, MODE_IGNORE_TICKET);
1234             continue;
1235         }
1236         if (MATCHES(*cur, "noninteractive=")) {
1237             if (atobool(*cur + sizeof("noninteractive=") - 1) == TRUE)
1238                 SET(flags, MODE_NONINTERACTIVE);
1239             continue;
1240         }
1241         if (MATCHES(*cur, "sudoedit=")) {
1242             if (atobool(*cur + sizeof("sudoedit=") - 1) == TRUE)
1243                 SET(flags, MODE_EDIT);
1244             continue;
1245         }
1246         if (MATCHES(*cur, "login_class=")) {
1247             login_class = *cur + sizeof("login_class=") - 1;
1248             def_use_loginclass = TRUE;
1249             continue;
1250         }
1251 #ifdef HAVE_SELINUX
1252         if (MATCHES(*cur, "selinux_role=")) {
1253             user_role = *cur + sizeof("selinux_role=") - 1;
1254             continue;
1255         }
1256         if (MATCHES(*cur, "selinux_type=")) {
1257             user_type = *cur + sizeof("selinux_type=") - 1;
1258             continue;
1259         }
1260 #endif /* HAVE_SELINUX */
1261 #ifdef HAVE_BSD_AUTH_H
1262         if (MATCHES(*cur, "bsdauth_type=")) {
1263             login_style = *cur + sizeof("bsdauth_type=") - 1;
1264             continue;
1265         }
1266 #endif /* HAVE_BSD_AUTH_H */
1267 #if !defined(HAVE_GETPROGNAME) && !defined(HAVE___PROGNAME)
1268         if (MATCHES(*cur, "progname=")) {
1269             setprogname(*cur + sizeof("progname=") - 1);
1270             continue;
1271         }
1272 #endif
1273         if (MATCHES(*cur, "network_addrs=")) {
1274             interfaces_string = *cur + sizeof("network_addrs=") - 1;
1275             set_interfaces(interfaces_string);
1276             continue;
1277         }
1278         if (MATCHES(*cur, "sudoers_file=")) {
1279             sudoers_file = *cur + sizeof("sudoers_file=") - 1;
1280             continue;
1281         }
1282         if (MATCHES(*cur, "sudoers_uid=")) {
1283             sudoers_uid = (uid_t) atoi(*cur + sizeof("sudoers_uid=") - 1);
1284             continue;
1285         }
1286         if (MATCHES(*cur, "sudoers_gid=")) {
1287             sudoers_gid = (gid_t) atoi(*cur + sizeof("sudoers_gid=") - 1);
1288             continue;
1289         }
1290         if (MATCHES(*cur, "sudoers_mode=")) {
1291             sudoers_mode = (mode_t) strtol(*cur + sizeof("sudoers_mode=") - 1,
1292                 NULL, 8);
1293             continue;
1294         }
1295     }
1296
1297     for (cur = user_info; *cur != NULL; cur++) {
1298         if (MATCHES(*cur, "user=")) {
1299             user_name = estrdup(*cur + sizeof("user=") - 1);
1300             continue;
1301         }
1302         if (MATCHES(*cur, "uid=")) {
1303             user_uid = (uid_t) atoi(*cur + sizeof("uid=") - 1);
1304             continue;
1305         }
1306         if (MATCHES(*cur, "gid=")) {
1307             p = *cur + sizeof("gid=") - 1;
1308             user_gid = (gid_t) atoi(p);
1309             continue;
1310         }
1311         if (MATCHES(*cur, "groups=")) {
1312             groups = *cur + sizeof("groups=") - 1;
1313             continue;
1314         }
1315         if (MATCHES(*cur, "cwd=")) {
1316             user_cwd = estrdup(*cur + sizeof("cwd=") - 1);
1317             continue;
1318         }
1319         if (MATCHES(*cur, "tty=")) {
1320             user_tty = user_ttypath = estrdup(*cur + sizeof("tty=") - 1);
1321             if (strncmp(user_tty, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
1322                 user_tty += sizeof(_PATH_DEV) - 1;
1323             continue;
1324         }
1325         if (MATCHES(*cur, "host=")) {
1326             user_host = user_shost = estrdup(*cur + sizeof("host=") - 1);
1327             if ((p = strchr(user_host, '.')))
1328                 user_shost = estrndup(user_host, (size_t)(p - user_host));
1329             continue;
1330         }
1331         if (MATCHES(*cur, "lines=")) {
1332             sudo_user.lines = atoi(*cur + sizeof("lines=") - 1);
1333             continue;
1334         }
1335         if (MATCHES(*cur, "cols=")) {
1336             sudo_user.cols = atoi(*cur + sizeof("cols=") - 1);
1337             continue;
1338         }
1339     }
1340     if (user_cwd == NULL)
1341         user_cwd = "unknown";
1342     if (user_tty == NULL)
1343         user_tty = "unknown"; /* user_ttypath remains NULL */
1344
1345     if (groups != NULL && groups[0] != '\0') {
1346         const char *cp;
1347         GETGROUPS_T *gids;
1348         int ngids;
1349
1350         /* Count number of groups, including passwd gid. */
1351         ngids = 2;
1352         for (cp = groups; *cp != '\0'; cp++) {
1353             if (*cp == ',')
1354                 ngids++;
1355         }
1356
1357         /* The first gid in the list is the passwd group gid. */
1358         gids = emalloc2(ngids, sizeof(GETGROUPS_T));
1359         gids[0] = user_gid;
1360         ngids = 1;
1361         cp = groups;
1362         for (;;) {
1363             gids[ngids] = atoi(cp);
1364             if (gids[0] != gids[ngids])
1365                 ngids++;
1366             cp = strchr(cp, ',');
1367             if (cp == NULL)
1368                 break;
1369             cp++; /* skip over comma */
1370         }
1371         set_group_list(user_name, gids, ngids);
1372         efree(gids);
1373     }
1374
1375 #undef MATCHES
1376     return flags;
1377 }
1378
1379 static char *
1380 resolve_editor(char *editor, int nfiles, char **files, char ***argv_out)
1381 {
1382     char *cp, **nargv, *editor_path = NULL;
1383     int ac, i, nargc, wasblank;
1384
1385     editor = estrdup(editor); /* becomes part of argv_out */
1386
1387     /*
1388      * Split editor into an argument vector; editor is reused (do not free).
1389      * The EDITOR and VISUAL environment variables may contain command
1390      * line args so look for those and alloc space for them too.
1391      */
1392     nargc = 1;
1393     for (wasblank = FALSE, cp = editor; *cp != '\0'; cp++) {
1394         if (isblank((unsigned char) *cp))
1395             wasblank = TRUE;
1396         else if (wasblank) {
1397             wasblank = FALSE;
1398             nargc++;
1399         }
1400     }
1401     /* If we can't find the editor in the user's PATH, give up. */
1402     cp = strtok(editor, " \t");
1403     if (cp == NULL ||
1404         find_path(cp, &editor_path, NULL, getenv("PATH"), 0) != FOUND) {
1405         efree(editor);
1406         return NULL;
1407     }
1408     nargv = (char **) emalloc2(nargc + 1 + nfiles + 1, sizeof(char *));
1409     for (ac = 0; cp != NULL && ac < nargc; ac++) {
1410         nargv[ac] = cp;
1411         cp = strtok(NULL, " \t");
1412     }
1413     nargv[ac++] = "--";
1414     for (i = 0; i < nfiles; )
1415         nargv[ac++] = files[i++];
1416     nargv[ac] = NULL;
1417
1418     *argv_out = nargv;
1419     return editor_path;
1420 }
1421
1422 /*
1423  * Determine which editor to use.  We don't need to worry about restricting
1424  * this to a "safe" editor since it runs with the uid of the invoking user,
1425  * not the runas (privileged) user.
1426  */
1427 static char *
1428 find_editor(int nfiles, char **files, char ***argv_out)
1429 {
1430     char *cp, *editor, *editor_path = NULL, **ev, *ev0[4];
1431
1432     /*
1433      * If any of SUDO_EDITOR, VISUAL or EDITOR are set, choose the first one.
1434      */
1435     ev0[0] = "SUDO_EDITOR";
1436     ev0[1] = "VISUAL";
1437     ev0[2] = "EDITOR";
1438     ev0[3] = NULL;
1439     for (ev = ev0; *ev != NULL; ev++) {
1440         if ((editor = getenv(*ev)) != NULL && *editor != '\0') {
1441             editor_path = resolve_editor(editor, nfiles, files, argv_out);
1442             if (editor_path != NULL)
1443                 break;
1444         }
1445     }
1446     if (editor_path == NULL) {
1447         /* def_editor could be a path, split it up */
1448         editor = estrdup(def_editor);
1449         cp = strtok(editor, ":");
1450         while (cp != NULL && editor_path == NULL) {
1451             editor_path = resolve_editor(cp, nfiles, files, argv_out);
1452             cp = strtok(NULL, ":");
1453         }
1454         if (editor_path)
1455             efree(editor);
1456     }
1457     if (!editor_path) {
1458         audit_failure(NewArgv, _("%s: command not found"), editor);
1459         warningx(_("%s: command not found"), editor);
1460     }
1461     return editor_path;
1462 }
1463
1464 #ifdef USE_ADMIN_FLAG
1465 static void
1466 create_admin_success_flag(void)
1467 {
1468     struct stat statbuf;
1469     char flagfile[PATH_MAX];
1470     int fd, n;
1471
1472     /* Check whether the user is in the admin group. */
1473     if (!user_in_group(sudo_user.pw, "admin"))
1474         return;
1475
1476     /* Build path to flag file. */
1477     n = snprintf(flagfile, sizeof(flagfile), "%s/.sudo_as_admin_successful",
1478         user_dir);
1479     if (n <= 0 || n >= sizeof(flagfile))
1480         return;
1481
1482     /* Create admin flag file if it doesn't already exist. */
1483     set_perms(PERM_USER);
1484     if (stat(flagfile, &statbuf) != 0) {
1485         fd = open(flagfile, O_CREAT|O_WRONLY|O_EXCL, 0644);
1486         close(fd);
1487     }
1488     restore_perms();
1489 }
1490 #else /* !USE_ADMIN_FLAG */
1491 static void
1492 create_admin_success_flag(void)
1493 {
1494     /* STUB */
1495 }
1496 #endif /* USE_ADMIN_FLAG */
1497
1498 struct policy_plugin sudoers_policy = {
1499     SUDO_POLICY_PLUGIN,
1500     SUDO_API_VERSION,
1501     sudoers_policy_open,
1502     sudoers_policy_close,
1503     sudoers_policy_version,
1504     sudoers_policy_check,
1505     sudoers_policy_list,
1506     sudoers_policy_validate,
1507     sudoers_policy_invalidate,
1508     sudoers_policy_init_session
1509 };