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