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