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