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