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