Imported Upstream version 1.8.6p8
[debian/sudo] / plugins / sudoers / visudo.c
1 /*
2  * Copyright (c) 1996, 1998-2005, 2007-2012
3  *      Todd C. Miller <Todd.Miller@courtesan.com>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  *
17  * Sponsored in part by the Defense Advanced Research Projects
18  * Agency (DARPA) and Air Force Research Laboratory, Air Force
19  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
20  */
21
22 /*
23  * Lock the sudoers file for safe editing (ala vipw) and check for parse errors.
24  */
25
26 #define _SUDO_MAIN
27
28 #ifdef __TANDEM
29 # include <floss.h>
30 #endif
31
32 #include <config.h>
33
34 #include <sys/types.h>
35 #include <sys/param.h>
36 #include <sys/stat.h>
37 #include <sys/socket.h>
38 #include <sys/time.h>
39 #ifndef __TANDEM
40 # include <sys/file.h>
41 #endif
42 #include <sys/wait.h>
43 #include <stdio.h>
44 #ifdef STDC_HEADERS
45 # include <stdlib.h>
46 # include <stddef.h>
47 #else
48 # ifdef HAVE_STDLIB_H
49 #  include <stdlib.h>
50 # endif
51 #endif /* STDC_HEADERS */
52 #ifdef HAVE_STRING_H
53 # include <string.h>
54 #endif /* HAVE_STRING_H */
55 #ifdef HAVE_STRINGS_H
56 # include <strings.h>
57 #endif /* HAVE_STRINGS_H */
58 #ifdef HAVE_UNISTD_H
59 #include <unistd.h>
60 #endif /* HAVE_UNISTD_H */
61 #include <stdarg.h>
62 #include <ctype.h>
63 #include <pwd.h>
64 #include <grp.h>
65 #include <signal.h>
66 #include <errno.h>
67 #include <fcntl.h>
68 #include <netinet/in.h>
69 #include <arpa/inet.h>
70 #include <netdb.h>
71 #if TIME_WITH_SYS_TIME
72 # include <time.h>
73 #endif
74 #ifdef HAVE_SETLOCALE
75 # include <locale.h>
76 #endif
77
78 #include "sudoers.h"
79 #include "interfaces.h"
80 #include "parse.h"
81 #include "redblack.h"
82 #include "gettext.h"
83 #include "sudoers_version.h"
84 #include "sudo_conf.h"
85 #include <gram.h>
86
87 struct sudoersfile {
88     struct sudoersfile *prev, *next;
89     char *path;
90     char *tpath;
91     int fd;
92     int modified;
93     int doedit;
94 };
95 TQ_DECLARE(sudoersfile)
96
97 sudo_conv_t sudo_conv;  /* NULL in non-plugin */
98
99 /*
100  * Function prototypes
101  */
102 static void quit(int);
103 static char *get_args(char *);
104 static char *get_editor(char **);
105 static void get_hostname(void);
106 static int whatnow(void);
107 static int check_aliases(bool, bool);
108 static bool check_syntax(char *, bool, bool, bool);
109 static bool edit_sudoers(struct sudoersfile *, char *, char *, int);
110 static bool install_sudoers(struct sudoersfile *, bool);
111 static int print_unused(void *, void *);
112 static void reparse_sudoers(char *, char *, bool, bool);
113 static int run_command(char *, char **);
114 static int visudo_printf(int msg_type, const char *fmt, ...);
115 static void setup_signals(void);
116 static void help(void) __attribute__((__noreturn__));
117 static void usage(int);
118
119 void cleanup(int);
120
121 extern void yyerror(const char *);
122 extern void yyrestart(FILE *);
123
124 /*
125  * External globals exported by the parser
126  */
127 extern struct rbtree *aliases;
128 extern FILE *yyin;
129 extern char *sudoers, *errorfile;
130 extern int errorlineno;
131 extern bool parse_error;
132 /* For getopt(3) */
133 extern char *optarg;
134 extern int optind;
135
136 /*
137  * Globals
138  */
139 struct interface *interfaces;
140 struct sudo_user sudo_user;
141 struct passwd *list_pw;
142 sudo_printf_t sudo_printf = visudo_printf;
143 static struct sudoersfile_list sudoerslist;
144 static struct rbtree *alias_freelist;
145 static bool checkonly;
146
147 int
148 main(int argc, char *argv[])
149 {
150     struct sudoersfile *sp;
151     char *args, *editor, *sudoers_path;
152     int ch, exitcode = 0;
153     bool quiet, strict, oldperms;
154     debug_decl(main, SUDO_DEBUG_MAIN)
155
156 #if defined(SUDO_DEVEL) && defined(__OpenBSD__)
157     {
158         extern char *malloc_options;
159         malloc_options = "AFGJPR";
160     }
161 #endif
162
163 #if !defined(HAVE_GETPROGNAME) && !defined(HAVE___PROGNAME)
164     setprogname(argc > 0 ? argv[0] : "visudo");
165 #endif
166
167 #ifdef HAVE_SETLOCALE 
168     setlocale(LC_ALL, "");
169 #endif
170     bindtextdomain("sudoers", LOCALEDIR); /* XXX - should have visudo domain */
171     textdomain("sudoers");
172
173     if (argc < 1)
174         usage(1);
175
176     /* Read sudo.conf. */
177     sudo_conf_read();
178
179     /*
180      * Arg handling.
181      */
182     checkonly = oldperms = quiet = strict = false;
183     sudoers_path = _PATH_SUDOERS;
184     while ((ch = getopt(argc, argv, "Vcf:sq")) != -1) {
185         switch (ch) {
186             case 'V':
187                 (void) printf(_("%s version %s\n"), getprogname(), PACKAGE_VERSION);
188                 (void) printf(_("%s grammar version %d\n"), getprogname(), SUDOERS_GRAMMAR_VERSION);
189                 goto done;
190             case 'c':
191                 checkonly = true;       /* check mode */
192                 break;
193             case 'f':
194                 sudoers_path = optarg;  /* sudoers file path */
195                 oldperms = true;
196                 break;
197             case 'h':
198                 help();
199                 break;
200             case 's':
201                 strict = true;          /* strict mode */
202                 break;
203             case 'q':
204                 quiet = false;          /* quiet mode */
205                 break;
206             default:
207                 usage(1);
208         }
209     }
210     /* There should be no other command line arguments. */
211     if (argc - optind != 0)
212         usage(1);
213
214     sudo_setpwent();
215     sudo_setgrent();
216
217     /* Mock up a fake sudo_user struct. */
218     user_cmnd = "";
219     if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL)
220         errorx(1, _("you do not exist in the %s database"), "passwd");
221     get_hostname();
222
223     /* Setup defaults data structures. */
224     init_defaults();
225
226     if (checkonly) {
227         exitcode = check_syntax(sudoers_path, quiet, strict, oldperms) ? 0 : 1;
228         goto done;
229     }
230
231     /*
232      * Parse the existing sudoers file(s) in quiet mode to highlight any
233      * existing errors and to pull in editor and env_editor conf values.
234      */
235     if ((yyin = open_sudoers(sudoers_path, true, NULL)) == NULL) {
236         error(1, "%s", sudoers_path);
237     }
238     init_parser(sudoers_path, false);
239     yyparse();
240     (void) update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER);
241
242     editor = get_editor(&args);
243
244     /* Install signal handlers to clean up temp files if we are killed. */
245     setup_signals();
246
247     /* Edit the sudoers file(s) */
248     tq_foreach_fwd(&sudoerslist, sp) {
249         if (!sp->doedit)
250             continue;
251         if (sp != tq_first(&sudoerslist)) {
252             printf(_("press return to edit %s: "), sp->path);
253             while ((ch = getchar()) != EOF && ch != '\n')
254                     continue;
255         }
256         edit_sudoers(sp, editor, args, -1);
257     }
258
259     /* Check edited files for a parse error and re-edit any that fail. */
260     reparse_sudoers(editor, args, strict, quiet);
261
262     /* Install the sudoers temp files as needed. */
263     tq_foreach_fwd(&sudoerslist, sp) {
264         (void) install_sudoers(sp, oldperms);
265     }
266
267 done:
268     sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, exitcode);                
269     exit(exitcode);
270 }
271
272 /*
273  * List of editors that support the "+lineno" command line syntax.
274  * If an entry starts with '*' the tail end of the string is matched.
275  * No other wild cards are supported.
276  */
277 static char *lineno_editors[] = {
278     "ex",
279     "nex",
280     "vi",
281     "nvi",
282     "vim",
283     "elvis",
284     "*macs",
285     "mg",
286     "vile",
287     "jove",
288     "pico",
289     "nano",
290     "ee",
291     "joe",
292     "zile",
293     NULL
294 };
295
296 /*
297  * Edit each sudoers file.
298  * Returns true on success, else false.
299  */
300 static bool
301 edit_sudoers(struct sudoersfile *sp, char *editor, char *args, int lineno)
302 {
303     int tfd;                            /* sudoers temp file descriptor */
304     bool modified;                      /* was the file modified? */
305     int ac;                             /* argument count */
306     char **av;                          /* argument vector for run_command */
307     char *cp;                           /* scratch char pointer */
308     char buf[PATH_MAX*2];               /* buffer used for copying files */
309     char linestr[64];                   /* string version of lineno */
310     struct timeval tv, tv1, tv2;        /* time before and after edit */
311     struct timeval orig_mtim;           /* starting mtime of sudoers file */
312     off_t orig_size;                    /* starting size of sudoers file */
313     ssize_t nread;                      /* number of bytes read */
314     struct stat sb;                     /* stat buffer */
315     bool rval = false;                  /* return value */
316     debug_decl(edit_sudoers, SUDO_DEBUG_UTIL)
317
318     if (fstat(sp->fd, &sb) == -1)
319         error(1, _("unable to stat %s"), sp->path);
320     orig_size = sb.st_size;
321     mtim_get(&sb, &orig_mtim);
322
323     /* Create the temp file if needed and set timestamp. */
324     if (sp->tpath == NULL) {
325         easprintf(&sp->tpath, "%s.tmp", sp->path);
326         tfd = open(sp->tpath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
327         if (tfd < 0)
328             error(1, "%s", sp->tpath);
329
330         /* Copy sp->path -> sp->tpath and reset the mtime. */
331         if (orig_size != 0) {
332             (void) lseek(sp->fd, (off_t)0, SEEK_SET);
333             while ((nread = read(sp->fd, buf, sizeof(buf))) > 0)
334                 if (write(tfd, buf, nread) != nread)
335                     error(1, _("write error"));
336
337             /* Add missing newline at EOF if needed. */
338             if (nread > 0 && buf[nread - 1] != '\n') {
339                 buf[0] = '\n';
340                 if (write(tfd, buf, 1) != 1)
341                     error(1, _("write error"));
342             }
343         }
344         (void) close(tfd);
345     }
346     (void) touch(-1, sp->tpath, &orig_mtim);
347
348     /* Does the editor support +lineno? */
349     if (lineno > 0)
350     {
351         char *editor_base = strrchr(editor, '/');
352         if (editor_base != NULL)
353             editor_base++;
354         else
355             editor_base = editor;
356         if (*editor_base == 'r')
357             editor_base++;
358
359         for (av = lineno_editors; (cp = *av) != NULL; av++) {
360             /* We only handle a leading '*' wildcard. */
361             if (*cp == '*') {
362                 size_t blen = strlen(editor_base);
363                 size_t clen = strlen(++cp);
364                 if (blen >= clen) {
365                     if (strcmp(cp, editor_base + blen - clen) == 0)
366                         break;
367                 }
368             } else if (strcmp(cp, editor_base) == 0)
369                 break;
370         }
371         /* Disable +lineno if editor doesn't support it. */
372         if (cp == NULL)
373             lineno = -1;
374     }
375
376     /* Find the length of the argument vector */
377     ac = 3 + (lineno > 0);
378     if (args) {
379         bool wasblank;
380
381         ac++;
382         for (wasblank = false, cp = args; *cp; cp++) {
383             if (isblank((unsigned char) *cp))
384                 wasblank = true;
385             else if (wasblank) {
386                 wasblank = false;
387                 ac++;
388             }
389         }
390     }
391
392     /* Build up argument vector for the command */
393     av = emalloc2(ac, sizeof(char *));
394     if ((av[0] = strrchr(editor, '/')) != NULL)
395         av[0]++;
396     else
397         av[0] = editor;
398     ac = 1;
399     if (lineno > 0) {
400         (void) snprintf(linestr, sizeof(linestr), "+%d", lineno);
401         av[ac++] = linestr;
402     }
403     if (args) {
404         for ((cp = strtok(args, " \t")); cp; (cp = strtok(NULL, " \t")))
405             av[ac++] = cp;
406     }
407     av[ac++] = sp->tpath;
408     av[ac++] = NULL;
409
410     /*
411      * Do the edit:
412      *  We cannot check the editor's exit value against 0 since
413      *  XPG4 specifies that vi's exit value is a function of the
414      *  number of errors during editing (?!?!).
415      */
416     gettimeofday(&tv1, NULL);
417     if (run_command(editor, av) != -1) {
418         gettimeofday(&tv2, NULL);
419         /*
420          * Sanity checks.
421          */
422         if (stat(sp->tpath, &sb) < 0) {
423             warningx(_("unable to stat temporary file (%s), %s unchanged"),
424                 sp->tpath, sp->path);
425             goto done;
426         }
427         if (sb.st_size == 0 && orig_size != 0) {
428             warningx(_("zero length temporary file (%s), %s unchanged"),
429                 sp->tpath, sp->path);
430             sp->modified = true;
431             goto done;
432         }
433     } else {
434         warningx(_("editor (%s) failed, %s unchanged"), editor, sp->path);
435         goto done;
436     }
437
438     /* Set modified bit if use changed the file. */
439     modified = true;
440     mtim_get(&sb, &tv);
441     if (orig_size == sb.st_size && timevalcmp(&orig_mtim, &tv, ==)) {
442         /*
443          * If mtime and size match but the user spent no measurable
444          * time in the editor we can't tell if the file was changed.
445          */
446         timevalsub(&tv1, &tv2);
447         if (timevalisset(&tv2))
448             modified = false;
449     }
450
451     /*
452      * If modified in this edit session, mark as modified.
453      */
454     if (modified)
455         sp->modified = modified;
456     else
457         warningx(_("%s unchanged"), sp->tpath);
458
459     rval = true;
460 done:
461     debug_return_bool(rval);
462 }
463
464 /*
465  * Parse sudoers after editing and re-edit any ones that caused a parse error.
466  */
467 static void
468 reparse_sudoers(char *editor, char *args, bool strict, bool quiet)
469 {
470     struct sudoersfile *sp, *last;
471     FILE *fp;
472     int ch;
473     debug_decl(reparse_sudoers, SUDO_DEBUG_UTIL)
474
475     if (tq_empty(&sudoerslist))
476         debug_return;
477
478     /*
479      * Parse the edited sudoers files and do sanity checking
480      */
481     do {
482         sp = tq_first(&sudoerslist);
483         last = tq_last(&sudoerslist);
484         fp = fopen(sp->tpath, "r+");
485         if (fp == NULL)
486             errorx(1, _("unable to re-open temporary file (%s), %s unchanged."),
487                 sp->tpath, sp->path);
488
489         /* Clean slate for each parse */
490         init_defaults();
491         init_parser(sp->path, quiet);
492
493         /* Parse the sudoers temp file */
494         yyrestart(fp);
495         if (yyparse() && !parse_error) {
496             warningx(_("unabled to parse temporary file (%s), unknown error"),
497                 sp->tpath);
498             parse_error = true;
499             errorfile = sp->path;
500         }
501         fclose(yyin);
502         if (!parse_error) {
503             if (!check_defaults(SETDEF_ALL, quiet) ||
504                 check_aliases(strict, quiet) != 0) {
505                 parse_error = true;
506                 errorfile = NULL;
507             }
508         }
509
510         /*
511          * Got an error, prompt the user for what to do now
512          */
513         if (parse_error) {
514             switch (whatnow()) {
515                 case 'Q' :      parse_error = false;    /* ignore parse error */
516                                 break;
517                 case 'x' :      /* XXX - should return instead of exiting */
518                                 cleanup(0);
519                                 sudo_debug_exit_int(__func__, __FILE__,
520                                     __LINE__, sudo_debug_subsys, 0);
521                                 exit(0);
522                                 break;
523             }
524         }
525         if (parse_error) {
526             /* Edit file with the parse error */
527             tq_foreach_fwd(&sudoerslist, sp) {
528                 if (errorfile == NULL || strcmp(sp->path, errorfile) == 0) {
529                     edit_sudoers(sp, editor, args, errorlineno);
530                     if (errorfile != NULL)
531                         break;
532                 }
533             }
534             if (errorfile != NULL && sp == NULL) {
535                 errorx(1, _("internal error, unable to find %s in list!"),
536                     sudoers);
537             }
538         }
539
540         /* If any new #include directives were added, edit them too. */
541         for (sp = last->next; sp != NULL; sp = sp->next) {
542             printf(_("press return to edit %s: "), sp->path);
543             while ((ch = getchar()) != EOF && ch != '\n')
544                     continue;
545             edit_sudoers(sp, editor, args, errorlineno);
546         }
547     } while (parse_error);
548
549     debug_return;
550 }
551
552 /*
553  * Set the owner and mode on a sudoers temp file and
554  * move it into place.  Returns true on success, else false.
555  */
556 static bool
557 install_sudoers(struct sudoersfile *sp, bool oldperms)
558 {
559     struct stat sb;
560     bool rval = false;
561     debug_decl(install_sudoers, SUDO_DEBUG_UTIL)
562
563     if (!sp->modified) {
564         /*
565          * No changes but fix owner/mode if needed.
566          */
567         (void) unlink(sp->tpath);
568         if (!oldperms && fstat(sp->fd, &sb) != -1) {
569             if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID)
570                 ignore_result(chown(sp->path, SUDOERS_UID, SUDOERS_GID));
571             if ((sb.st_mode & 0777) != SUDOERS_MODE)
572                 ignore_result(chmod(sp->path, SUDOERS_MODE));
573         }
574         rval = true;
575         goto done;
576     }
577
578     /*
579      * Change mode and ownership of temp file so when
580      * we move it to sp->path things are kosher.
581      */
582     if (oldperms) {
583         /* Use perms of the existing file.  */
584         if (fstat(sp->fd, &sb) == -1)
585             error(1, _("unable to stat %s"), sp->path);
586         if (chown(sp->tpath, sb.st_uid, sb.st_gid) != 0) {
587             warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
588                 sp->tpath, (unsigned int)sb.st_uid, (unsigned int)sb.st_gid);
589         }
590         if (chmod(sp->tpath, sb.st_mode & 0777) != 0) {
591             warning(_("unable to change mode of %s to 0%o"), sp->tpath,
592                 (unsigned int)(sb.st_mode & 0777));
593         }
594     } else {
595         if (chown(sp->tpath, SUDOERS_UID, SUDOERS_GID) != 0) {
596             warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
597                 sp->tpath, SUDOERS_UID, SUDOERS_GID);
598             goto done;
599         }
600         if (chmod(sp->tpath, SUDOERS_MODE) != 0) {
601             warning(_("unable to change mode of %s to 0%o"), sp->tpath,
602                 SUDOERS_MODE);
603             goto done;
604         }
605     }
606
607     /*
608      * Now that sp->tpath is sane (parses ok) it needs to be
609      * rename(2)'d to sp->path.  If the rename(2) fails we try using
610      * mv(1) in case sp->tpath and sp->path are on different file systems.
611      */
612     if (rename(sp->tpath, sp->path) == 0) {
613         efree(sp->tpath);
614         sp->tpath = NULL;
615     } else {
616         if (errno == EXDEV) {
617             char *av[4];
618             warningx(_("%s and %s not on the same file system, using mv to rename"),
619               sp->tpath, sp->path);
620
621             /* Build up argument vector for the command */
622             if ((av[0] = strrchr(_PATH_MV, '/')) != NULL)
623                 av[0]++;
624             else
625                 av[0] = _PATH_MV;
626             av[1] = sp->tpath;
627             av[2] = sp->path;
628             av[3] = NULL;
629
630             /* And run it... */
631             if (run_command(_PATH_MV, av)) {
632                 warningx(_("command failed: '%s %s %s', %s unchanged"),
633                     _PATH_MV, sp->tpath, sp->path, sp->path);
634                 (void) unlink(sp->tpath);
635                 efree(sp->tpath);
636                 sp->tpath = NULL;
637                 goto done;
638             }
639             efree(sp->tpath);
640             sp->tpath = NULL;
641         } else {
642             warning(_("error renaming %s, %s unchanged"), sp->tpath, sp->path);
643             (void) unlink(sp->tpath);
644             goto done;
645         }
646     }
647     rval = true;
648 done:
649     debug_return_bool(rval);
650 }
651
652 /* STUB */
653 void
654 set_fqdn(void)
655 {
656     return;
657 }
658
659 /* STUB */
660 void
661 init_envtables(void)
662 {
663     return;
664 }
665
666 /* STUB */
667 bool
668 user_is_exempt(void)
669 {
670     return false;
671 }
672
673 /* STUB */
674 void
675 sudo_setspent(void)
676 {
677     return;
678 }
679
680 /* STUB */
681 void
682 sudo_endspent(void)
683 {
684     return;
685 }
686
687 /* STUB */
688 int
689 group_plugin_query(const char *user, const char *group, const struct passwd *pw)
690 {
691     return false;
692 }
693
694 /*
695  * Assuming a parse error occurred, prompt the user for what they want
696  * to do now.  Returns the first letter of their choice.
697  */
698 static int
699 whatnow(void)
700 {
701     int choice, c;
702     debug_decl(whatnow, SUDO_DEBUG_UTIL)
703
704     for (;;) {
705         (void) fputs(_("What now? "), stdout);
706         choice = getchar();
707         for (c = choice; c != '\n' && c != EOF;)
708             c = getchar();
709
710         switch (choice) {
711             case EOF:
712                 choice = 'x';
713                 /* FALLTHROUGH */
714             case 'e':
715             case 'x':
716             case 'Q':
717                 debug_return_int(choice);
718             default:
719                 (void) puts(_("Options are:\n"
720                     "  (e)dit sudoers file again\n"
721                     "  e(x)it without saving changes to sudoers file\n"
722                     "  (Q)uit and save changes to sudoers file (DANGER!)\n"));
723         }
724     }
725 }
726
727 /*
728  * Install signal handlers for visudo.
729  */
730 static void
731 setup_signals(void)
732 {
733     sigaction_t sa;
734     debug_decl(setup_signals, SUDO_DEBUG_UTIL)
735
736     /*
737      * Setup signal handlers to cleanup nicely.
738      */
739     zero_bytes(&sa, sizeof(sa));
740     sigemptyset(&sa.sa_mask);
741     sa.sa_flags = SA_RESTART;
742     sa.sa_handler = quit;
743     (void) sigaction(SIGTERM, &sa, NULL);
744     (void) sigaction(SIGHUP, &sa, NULL);
745     (void) sigaction(SIGINT, &sa, NULL);
746     (void) sigaction(SIGQUIT, &sa, NULL);
747
748     debug_return;
749 }
750
751 static int
752 run_command(char *path, char **argv)
753 {
754     int status;
755     pid_t pid, rv;
756     debug_decl(run_command, SUDO_DEBUG_UTIL)
757
758     switch (pid = sudo_debug_fork()) {
759         case -1:
760             error(1, _("unable to execute %s"), path);
761             break;      /* NOTREACHED */
762         case 0:
763             sudo_endpwent();
764             sudo_endgrent();
765             closefrom(STDERR_FILENO + 1);
766             execv(path, argv);
767             warning(_("unable to run %s"), path);
768             _exit(127);
769             break;      /* NOTREACHED */
770     }
771
772     do {
773         rv = waitpid(pid, &status, 0);
774     } while (rv == -1 && errno == EINTR);
775
776     if (rv != -1)
777         rv = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
778     debug_return_int(rv);
779 }
780
781 static bool
782 check_owner(const char *path, bool quiet)
783 {
784     struct stat sb;
785     bool ok = true;
786     debug_decl(check_owner, SUDO_DEBUG_UTIL)
787
788     if (stat(path, &sb) == 0) {
789         if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID) {
790             ok = false;
791             if (!quiet) {
792                 fprintf(stderr,
793                     _("%s: wrong owner (uid, gid) should be (%u, %u)\n"),
794                     path, SUDOERS_UID, SUDOERS_GID);
795                 }
796         }
797         if ((sb.st_mode & 07777) != SUDOERS_MODE) {
798             ok = false;
799             if (!quiet) {
800                 fprintf(stderr, _("%s: bad permissions, should be mode 0%o\n"),
801                     path, SUDOERS_MODE);
802             }
803         }
804     }
805     debug_return_bool(ok);
806 }
807
808 static bool
809 check_syntax(char *sudoers_path, bool quiet, bool strict, bool oldperms)
810 {
811     bool ok = false;
812     debug_decl(check_syntax, SUDO_DEBUG_UTIL)
813
814     if (strcmp(sudoers_path, "-") == 0) {
815         yyin = stdin;
816         sudoers_path = "stdin";
817     } else if ((yyin = fopen(sudoers_path, "r")) == NULL) {
818         if (!quiet)
819             warning(_("unable to open %s"), sudoers_path);
820         goto done;
821     }
822     init_parser(sudoers_path, quiet);
823     if (yyparse() && !parse_error) {
824         if (!quiet)
825             warningx(_("failed to parse %s file, unknown error"), sudoers_path);
826         parse_error = true;
827         errorfile = sudoers_path;
828     }
829     if (!parse_error) {
830         if (!check_defaults(SETDEF_ALL, quiet) ||
831             check_aliases(strict, quiet) != 0) {
832             parse_error = true;
833             errorfile = NULL;
834         }
835     }
836     ok = !parse_error;
837
838     if (parse_error) {
839         if (!quiet) {
840             if (errorlineno != -1)
841                 (void) printf(_("parse error in %s near line %d\n"),
842                     errorfile, errorlineno);
843             else if (errorfile != NULL)
844                 (void) printf(_("parse error in %s\n"), errorfile);
845         }
846     } else {
847         struct sudoersfile *sp;
848
849         /* Parsed OK, check mode and owner. */
850         if (oldperms || check_owner(sudoers_path, quiet))
851             (void) printf(_("%s: parsed OK\n"), sudoers_path);
852         else
853             ok = false;
854         tq_foreach_fwd(&sudoerslist, sp) {
855             if (oldperms || check_owner(sp->path, quiet))
856                 (void) printf(_("%s: parsed OK\n"), sp->path);
857             else
858                 ok = false;
859         }
860     }
861
862 done:
863     debug_return_bool(ok);
864 }
865
866 /*
867  * Used to open (and lock) the initial sudoers file and to also open
868  * any subsequent files #included via a callback from the parser.
869  */
870 FILE *
871 open_sudoers(const char *path, bool doedit, bool *keepopen)
872 {
873     struct sudoersfile *entry;
874     FILE *fp;
875     int open_flags;
876     debug_decl(open_sudoers, SUDO_DEBUG_UTIL)
877
878     if (checkonly)
879         open_flags = O_RDONLY;
880     else
881         open_flags = O_RDWR | O_CREAT;
882
883     /* Check for existing entry */
884     tq_foreach_fwd(&sudoerslist, entry) {
885         if (strcmp(path, entry->path) == 0)
886             break;
887     }
888     if (entry == NULL) {
889         entry = ecalloc(1, sizeof(*entry));
890         entry->path = estrdup(path);
891         /* entry->modified = 0; */
892         entry->prev = entry;
893         /* entry->next = NULL; */
894         entry->fd = open(entry->path, open_flags, SUDOERS_MODE);
895         /* entry->tpath = NULL; */
896         entry->doedit = doedit;
897         if (entry->fd == -1) {
898             warning("%s", entry->path);
899             efree(entry);
900             debug_return_ptr(NULL);
901         }
902         if (!checkonly && !lock_file(entry->fd, SUDO_TLOCK))
903             errorx(1, _("%s busy, try again later"), entry->path);
904         if ((fp = fdopen(entry->fd, "r")) == NULL)
905             error(1, "%s", entry->path);
906         tq_append(&sudoerslist, entry);
907     } else {
908         /* Already exists, open .tmp version if there is one. */
909         if (entry->tpath != NULL) {
910             if ((fp = fopen(entry->tpath, "r")) == NULL)
911                 error(1, "%s", entry->tpath);
912         } else {
913             if ((fp = fdopen(entry->fd, "r")) == NULL)
914                 error(1, "%s", entry->path);
915             rewind(fp);
916         }
917     }
918     if (keepopen != NULL)
919         *keepopen = true;
920     debug_return_ptr(fp);
921 }
922
923 static char *
924 get_editor(char **args)
925 {
926     char *Editor, *EditorArgs, *EditorPath, *UserEditor, *UserEditorArgs;
927     debug_decl(get_editor, SUDO_DEBUG_UTIL)
928
929     /*
930      * Check VISUAL and EDITOR environment variables to see which editor
931      * the user wants to use (we may not end up using it though).
932      * If the path is not fully-qualified, make it so and check that
933      * the specified executable actually exists.
934      */
935     UserEditorArgs = NULL;
936     if ((UserEditor = getenv("VISUAL")) == NULL || *UserEditor == '\0')
937         UserEditor = getenv("EDITOR");
938     if (UserEditor && *UserEditor == '\0')
939         UserEditor = NULL;
940     else if (UserEditor) {
941         UserEditorArgs = get_args(UserEditor);
942         if (find_path(UserEditor, &Editor, NULL, getenv("PATH"), 0) == FOUND) {
943             UserEditor = Editor;
944         } else {
945             if (def_env_editor) {
946                 /* If we are honoring $EDITOR this is a fatal error. */
947                 errorx(1, _("specified editor (%s) doesn't exist"), UserEditor);
948             } else {
949                 /* Otherwise, just ignore $EDITOR. */
950                 UserEditor = NULL;
951             }
952         }
953     }
954
955     /*
956      * See if we can use the user's choice of editors either because
957      * we allow any $EDITOR or because $EDITOR is in the allowable list.
958      */
959     Editor = EditorArgs = EditorPath = NULL;
960     if (def_env_editor && UserEditor) {
961         Editor = UserEditor;
962         EditorArgs = UserEditorArgs;
963     } else if (UserEditor) {
964         struct stat editor_sb;
965         struct stat user_editor_sb;
966         char *base, *userbase;
967
968         if (stat(UserEditor, &user_editor_sb) != 0) {
969             /* Should never happen since we already checked above. */
970             error(1, _("unable to stat editor (%s)"), UserEditor);
971         }
972         EditorPath = estrdup(def_editor);
973         Editor = strtok(EditorPath, ":");
974         do {
975             EditorArgs = get_args(Editor);
976             /*
977              * Both Editor and UserEditor should be fully qualified but
978              * check anyway...
979              */
980             if ((base = strrchr(Editor, '/')) == NULL)
981                 continue;
982             if ((userbase = strrchr(UserEditor, '/')) == NULL) {
983                 Editor = NULL;
984                 break;
985             }
986             base++, userbase++;
987
988             /*
989              * We compare the basenames first and then use stat to match
990              * for sure.
991              */
992             if (strcmp(base, userbase) == 0) {
993                 if (stat(Editor, &editor_sb) == 0 && S_ISREG(editor_sb.st_mode)
994                     && (editor_sb.st_mode & 0000111) &&
995                     editor_sb.st_dev == user_editor_sb.st_dev &&
996                     editor_sb.st_ino == user_editor_sb.st_ino)
997                     break;
998             }
999         } while ((Editor = strtok(NULL, ":")));
1000     }
1001
1002     /*
1003      * Can't use $EDITOR, try each element of def_editor until we
1004      * find one that exists, is regular, and is executable.
1005      */
1006     if (Editor == NULL || *Editor == '\0') {
1007         efree(EditorPath);
1008         EditorPath = estrdup(def_editor);
1009         Editor = strtok(EditorPath, ":");
1010         do {
1011             EditorArgs = get_args(Editor);
1012             if (sudo_goodpath(Editor, NULL))
1013                 break;
1014         } while ((Editor = strtok(NULL, ":")));
1015
1016         /* Bleah, none of the editors existed! */
1017         if (Editor == NULL || *Editor == '\0')
1018             errorx(1, _("no editor found (editor path = %s)"), def_editor);
1019     }
1020     *args = EditorArgs;
1021     debug_return_str(Editor);
1022 }
1023
1024 /*
1025  * Split out any command line arguments and return them.
1026  */
1027 static char *
1028 get_args(char *cmnd)
1029 {
1030     char *args;
1031     debug_decl(get_args, SUDO_DEBUG_UTIL)
1032
1033     args = cmnd;
1034     while (*args && !isblank((unsigned char) *args))
1035         args++;
1036     if (*args) {
1037         *args++ = '\0';
1038         while (*args && isblank((unsigned char) *args))
1039             args++;
1040     }
1041     debug_return_str(*args ? args : NULL);
1042 }
1043
1044 /*
1045  * Look up the hostname and set user_host and user_shost.
1046  */
1047 static void
1048 get_hostname(void)
1049 {
1050     char *p, thost[MAXHOSTNAMELEN + 1];
1051     debug_decl(get_hostname, SUDO_DEBUG_UTIL)
1052
1053     if (gethostname(thost, sizeof(thost)) != -1) {
1054         thost[sizeof(thost) - 1] = '\0';
1055         user_host = estrdup(thost);
1056
1057         if ((p = strchr(user_host, '.'))) {
1058             *p = '\0';
1059             user_shost = estrdup(user_host);
1060             *p = '.';
1061         } else {
1062             user_shost = user_host;
1063         }
1064     } else {
1065         user_host = user_shost = "localhost";
1066     }
1067     debug_return;
1068 }
1069
1070 static bool
1071 alias_remove_recursive(char *name, int type)
1072 {
1073     struct member *m;
1074     struct alias *a;
1075     bool rval = true;
1076     debug_decl(alias_remove_recursive, SUDO_DEBUG_ALIAS)
1077
1078     if ((a = alias_remove(name, type)) != NULL) {
1079         tq_foreach_fwd(&a->members, m) {
1080             if (m->type == ALIAS) {
1081                 if (!alias_remove_recursive(m->name, type))
1082                     rval = false;
1083             }
1084         }
1085         rbinsert(alias_freelist, a);
1086     }
1087     alias_seqno++;
1088     debug_return_bool(rval);
1089 }
1090
1091 static int
1092 check_alias(char *name, int type, int strict, int quiet)
1093 {
1094     struct member *m;
1095     struct alias *a;
1096     int errors = 0;
1097     debug_decl(check_alias, SUDO_DEBUG_ALIAS)
1098
1099     if ((a = alias_find(name, type)) != NULL) {
1100         /* check alias contents */
1101         tq_foreach_fwd(&a->members, m) {
1102             if (m->type == ALIAS)
1103                 errors += check_alias(m->name, type, strict, quiet);
1104         }
1105     } else {
1106         if (!quiet) {
1107             char *fmt;
1108             if (errno == ELOOP) {
1109                 fmt = strict ?
1110                     _("Error: cycle in %s_Alias `%s'") :
1111                     _("Warning: cycle in %s_Alias `%s'");
1112             } else {
1113                 fmt = strict ?
1114                     _("Error: %s_Alias `%s' referenced but not defined") :
1115                     _("Warning: %s_Alias `%s' referenced but not defined");
1116             }
1117             warningx(fmt,
1118                 type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
1119                 type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
1120                 "Unknown", name);
1121         }
1122         errors++;
1123     }
1124
1125     debug_return_int(errors);
1126 }
1127
1128 /*
1129  * Iterate through the sudoers datastructures looking for undefined
1130  * aliases or unused aliases.
1131  */
1132 static int
1133 check_aliases(bool strict, bool quiet)
1134 {
1135     struct cmndspec *cs;
1136     struct member *m, *binding;
1137     struct privilege *priv;
1138     struct userspec *us;
1139     struct defaults *d;
1140     int atype, errors = 0;
1141     debug_decl(check_aliases, SUDO_DEBUG_ALIAS)
1142
1143     alias_freelist = rbcreate(alias_compare);
1144
1145     /* Forward check. */
1146     tq_foreach_fwd(&userspecs, us) {
1147         tq_foreach_fwd(&us->users, m) {
1148             if (m->type == ALIAS) {
1149                 alias_seqno++;
1150                 errors += check_alias(m->name, USERALIAS, strict, quiet);
1151             }
1152         }
1153         tq_foreach_fwd(&us->privileges, priv) {
1154             tq_foreach_fwd(&priv->hostlist, m) {
1155                 if (m->type == ALIAS) {
1156                     alias_seqno++;
1157                     errors += check_alias(m->name, HOSTALIAS, strict, quiet);
1158                 }
1159             }
1160             tq_foreach_fwd(&priv->cmndlist, cs) {
1161                 tq_foreach_fwd(&cs->runasuserlist, m) {
1162                     if (m->type == ALIAS) {
1163                         alias_seqno++;
1164                         errors += check_alias(m->name, RUNASALIAS, strict, quiet);
1165                     }
1166                 }
1167                 if ((m = cs->cmnd)->type == ALIAS) {
1168                     alias_seqno++;
1169                     errors += check_alias(m->name, CMNDALIAS, strict, quiet);
1170                 }
1171             }
1172         }
1173     }
1174
1175     /* Reverse check (destructive) */
1176     tq_foreach_fwd(&userspecs, us) {
1177         tq_foreach_fwd(&us->users, m) {
1178             if (m->type == ALIAS) {
1179                 alias_seqno++;
1180                 if (!alias_remove_recursive(m->name, USERALIAS))
1181                     errors++;
1182             }
1183         }
1184         tq_foreach_fwd(&us->privileges, priv) {
1185             tq_foreach_fwd(&priv->hostlist, m) {
1186                 if (m->type == ALIAS) {
1187                     alias_seqno++;
1188                     if (!alias_remove_recursive(m->name, HOSTALIAS))
1189                         errors++;
1190                 }
1191             }
1192             tq_foreach_fwd(&priv->cmndlist, cs) {
1193                 tq_foreach_fwd(&cs->runasuserlist, m) {
1194                     if (m->type == ALIAS) {
1195                         alias_seqno++;
1196                         if (!alias_remove_recursive(m->name, RUNASALIAS))
1197                             errors++;
1198                     }
1199                 }
1200                 if ((m = cs->cmnd)->type == ALIAS) {
1201                     alias_seqno++;
1202                     if (!alias_remove_recursive(m->name, CMNDALIAS))
1203                         errors++;
1204                 }
1205             }
1206         }
1207     }
1208     tq_foreach_fwd(&defaults, d) {
1209         switch (d->type) {
1210             case DEFAULTS_HOST:
1211                 atype = HOSTALIAS;
1212                 break;
1213             case DEFAULTS_USER:
1214                 atype = USERALIAS;
1215                 break;
1216             case DEFAULTS_RUNAS:
1217                 atype = RUNASALIAS;
1218                 break;
1219             case DEFAULTS_CMND:
1220                 atype = CMNDALIAS;
1221                 break;
1222             default:
1223                 continue; /* not an alias */
1224         }
1225         tq_foreach_fwd(&d->binding, binding) {
1226             for (m = binding; m != NULL; m = m->next) {
1227                 if (m->type == ALIAS) {
1228                     alias_seqno++;
1229                     if (!alias_remove_recursive(m->name, atype))
1230                         errors++;
1231                 }
1232             }
1233         }
1234     }
1235     rbdestroy(alias_freelist, alias_free);
1236
1237     /* If all aliases were referenced we will have an empty tree. */
1238     if (!no_aliases() && !quiet)
1239         alias_apply(print_unused, strict ? "Error" : "Warning");
1240
1241     debug_return_int(strict ? errors : 0);
1242 }
1243
1244 static int
1245 print_unused(void *v1, void *v2)
1246 {
1247     struct alias *a = (struct alias *)v1;
1248     char *prefix = (char *)v2;
1249
1250     warningx2(_("%s: unused %s_Alias %s"), prefix,
1251         a->type == HOSTALIAS ? "Host" : a->type == CMNDALIAS ? "Cmnd" :
1252         a->type == USERALIAS ? "User" : a->type == RUNASALIAS ? "Runas" :
1253         "Unknown", a->name);
1254     return 0;
1255 }
1256
1257 /*
1258  * Unlink any sudoers temp files that remain.
1259  */
1260 void
1261 cleanup(int gotsignal)
1262 {
1263     struct sudoersfile *sp;
1264
1265     tq_foreach_fwd(&sudoerslist, sp) {
1266         if (sp->tpath != NULL)
1267             (void) unlink(sp->tpath);
1268     }
1269     if (!gotsignal) {
1270         sudo_endpwent();
1271         sudo_endgrent();
1272     }
1273 }
1274
1275 /*
1276  * Unlink sudoers temp files (if any) and exit.
1277  */
1278 static void
1279 quit(int signo)
1280 {
1281     const char *signame, *myname;
1282
1283     cleanup(signo);
1284 #define emsg     " exiting due to signal: "
1285     myname = getprogname();
1286     signame = strsignal(signo);
1287     ignore_result(write(STDERR_FILENO, myname, strlen(myname)));
1288     ignore_result(write(STDERR_FILENO, emsg, sizeof(emsg) - 1));
1289     ignore_result(write(STDERR_FILENO, signame, strlen(signame)));
1290     ignore_result(write(STDERR_FILENO, "\n", 1));
1291     _exit(signo);
1292 }
1293
1294 static void
1295 usage(int fatal)
1296 {
1297     (void) fprintf(fatal ? stderr : stdout,
1298         "usage: %s [-chqsV] [-f sudoers]\n", getprogname());
1299     if (fatal)
1300         exit(1);
1301 }
1302
1303 static void
1304 help(void)
1305 {
1306     (void) printf(_("%s - safely edit the sudoers file\n\n"), getprogname());
1307     usage(0);
1308     (void) puts(_("\nOptions:\n"
1309         "  -c          check-only mode\n"
1310         "  -f sudoers  specify sudoers file location\n"
1311         "  -h          display help message and exit\n"
1312         "  -q          less verbose (quiet) syntax error messages\n"
1313         "  -s          strict syntax checking\n"
1314         "  -V          display version information and exit"));
1315     exit(0);
1316 }
1317
1318 static int
1319 visudo_printf(int msg_type, const char *fmt, ...)
1320 {
1321     va_list ap;
1322     FILE *fp;
1323             
1324     switch (msg_type) {
1325     case SUDO_CONV_INFO_MSG:
1326         fp = stdout;
1327         break;
1328     case SUDO_CONV_ERROR_MSG:
1329         fp = stderr;
1330         break;
1331     default:
1332         errno = EINVAL;
1333         return -1;
1334     }
1335    
1336     va_start(ap, fmt);
1337     vfprintf(fp, fmt, ap);
1338     va_end(ap);
1339    
1340     return 0;
1341 }