2 * Copyright (c) 1996, 1998-2005, 2007-2008
3 * Todd C. Miller <Todd.Miller@courtesan.com>
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.
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.
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.
23 * Lock the sudoers file for safe editing (ala vipw) and check for parse errors.
34 #include <sys/types.h>
35 #include <sys/param.h>
37 #include <sys/socket.h>
40 # include <sys/file.h>
51 #endif /* STDC_HEADERS */
55 # ifdef HAVE_STRINGS_H
58 #endif /* HAVE_STRING_H */
61 #endif /* HAVE_UNISTD_H */
68 #include <netinet/in.h>
69 #include <arpa/inet.h>
71 #if TIME_WITH_SYS_TIME
80 # include <emul/timespec.h>
84 #include "interfaces.h"
90 __unused static const char rcsid[] = "$Sudo: visudo.c,v 1.223 2008/11/22 15:12:26 millert Exp $";
99 struct sudoersfile *next;
103 * Function prototypes
105 static RETSIGTYPE quit __P((int));
106 static char *get_args __P((char *));
107 static char *get_editor __P((char **));
108 static char whatnow __P((void));
109 static int check_aliases __P((int));
110 static int check_syntax __P((char *, int, int));
111 static int edit_sudoers __P((struct sudoersfile *, char *, char *, int));
112 static int install_sudoers __P((struct sudoersfile *, int));
113 static int print_unused __P((void *, void *));
114 static int reparse_sudoers __P((char *, char *, int, int));
115 static int run_command __P((char *, char **));
116 static void setup_signals __P((void));
117 static void usage __P((void)) __attribute__((__noreturn__));
119 extern void yyerror __P((const char *));
120 extern void yyrestart __P((FILE *));
123 * External globals exported by the parser
126 extern char *sudoers, *errorfile;
127 extern int errorlineno, parse_error;
138 struct interface *interfaces;
139 struct sudo_user sudo_user;
140 struct passwd *list_pw;
141 static struct sudoerslist {
142 struct sudoersfile *first, *last;
150 struct sudoersfile *sp;
151 char *args, *editor, *sudoers_path;
152 int ch, checkonly, quiet, strict, oldperms;
153 #if defined(SUDO_DEVEL) && defined(__OpenBSD__)
154 extern char *malloc_options;
155 malloc_options = "AFGJPR";
159 if ((Argc = argc) < 1)
165 checkonly = oldperms = quiet = strict = FALSE;
166 sudoers_path = _PATH_SUDOERS;
167 while ((ch = getopt(argc, argv, "Vcf:sq")) != -1) {
170 (void) printf("%s version %s\n", getprogname(), version);
173 checkonly++; /* check mode */
176 sudoers_path = optarg; /* sudoers file path */
180 strict++; /* strict mode */
183 quiet++; /* quiet mode */
197 /* Mock up a fake sudo_user struct. */
198 user_host = user_shost = user_cmnd = "";
199 if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL)
200 errorx(1, "you don't exist in the passwd database");
202 /* Setup defaults data structures. */
206 exit(check_syntax(sudoers_path, quiet, strict));
209 * Parse the existing sudoers file(s) in quiet mode to highlight any
210 * existing errors and to pull in editor and env_editor conf values.
212 if ((yyin = open_sudoers(sudoers_path, NULL)) == NULL)
213 error(1, "%s", sudoers_path);
214 init_parser(sudoers_path, 0);
216 (void) update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER);
218 editor = get_editor(&args);
220 /* Install signal handlers to clean up temp files if we are killed. */
223 /* Edit the sudoers file(s) */
224 tq_foreach_fwd(&sudoerslist, sp) {
225 if (sp != tq_first(&sudoerslist)) {
226 printf("press return to edit %s: ", sp->path);
227 while ((ch = getchar()) != EOF && ch != '\n')
230 edit_sudoers(sp, editor, args, -1);
233 /* Check edited files for a parse error and re-edit any that fail. */
234 reparse_sudoers(editor, args, strict, quiet);
236 /* Install the sudoers temp files. */
237 tq_foreach_fwd(&sudoerslist, sp) {
239 (void) unlink(sp->tpath);
241 (void) install_sudoers(sp, oldperms);
248 * Edit each sudoers file.
249 * Returns TRUE on success, else FALSE.
252 edit_sudoers(sp, editor, args, lineno)
253 struct sudoersfile *sp;
257 int tfd; /* sudoers temp file descriptor */
258 int modified; /* was the file modified? */
259 int ac; /* argument count */
260 char **av; /* argument vector for run_command */
261 char *cp; /* scratch char pointer */
262 char buf[PATH_MAX*2]; /* buffer used for copying files */
263 char linestr[64]; /* string version of lineno */
264 struct timespec ts1, ts2; /* time before and after edit */
265 struct timespec orig_mtim; /* starting mtime of sudoers file */
266 off_t orig_size; /* starting size of sudoers file */
267 ssize_t nread; /* number of bytes read */
268 struct stat sb; /* stat buffer */
271 if (fstat(sp->fd, &sb) == -1)
273 if (stat(sp->path, &sb) == -1)
275 error(1, "can't stat %s", sp->path);
276 orig_size = sb.st_size;
277 orig_mtim.tv_sec = mtim_getsec(sb);
278 orig_mtim.tv_nsec = mtim_getnsec(sb);
280 /* Create the temp file if needed and set timestamp. */
281 if (sp->tpath == NULL) {
282 easprintf(&sp->tpath, "%s.tmp", sp->path);
283 tfd = open(sp->tpath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
285 error(1, "%s", sp->tpath);
287 /* Copy sp->path -> sp->tpath and reset the mtime. */
288 if (orig_size != 0) {
289 (void) lseek(sp->fd, (off_t)0, SEEK_SET);
290 while ((nread = read(sp->fd, buf, sizeof(buf))) > 0)
291 if (write(tfd, buf, nread) != nread)
292 error(1, "write error");
294 /* Add missing newline at EOF if needed. */
295 if (nread > 0 && buf[nread - 1] != '\n') {
302 (void) touch(-1, sp->tpath, &orig_mtim);
304 /* Find the length of the argument vector */
305 ac = 3 + (lineno > 0);
310 for (wasblank = FALSE, cp = args; *cp; cp++) {
311 if (isblank((unsigned char) *cp))
320 /* Build up argument vector for the command */
321 av = emalloc2(ac, sizeof(char *));
322 if ((av[0] = strrchr(editor, '/')) != NULL)
328 (void) snprintf(linestr, sizeof(linestr), "+%d", lineno);
332 for ((cp = strtok(args, " \t")); cp; (cp = strtok(NULL, " \t")))
335 av[ac++] = sp->tpath;
340 * We cannot check the editor's exit value against 0 since
341 * XPG4 specifies that vi's exit value is a function of the
342 * number of errors during editing (?!?!).
345 if (run_command(editor, av) != -1) {
350 if (stat(sp->tpath, &sb) < 0) {
351 warningx("cannot stat temporary file (%s), %s unchanged",
352 sp->tpath, sp->path);
355 if (sb.st_size == 0 && orig_size != 0) {
356 warningx("zero length temporary file (%s), %s unchanged",
357 sp->tpath, sp->path);
362 warningx("editor (%s) failed, %s unchanged", editor, sp->path);
366 /* Set modified bit if use changed the file. */
368 if (orig_size == sb.st_size &&
369 orig_mtim.tv_sec == mtim_getsec(sb) &&
370 orig_mtim.tv_nsec == mtim_getnsec(sb)) {
372 * If mtime and size match but the user spent no measurable
373 * time in the editor we can't tell if the file was changed.
375 #ifdef HAVE_TIMESPECSUB2
376 timespecsub(&ts1, &ts2);
378 timespecsub(&ts1, &ts2, &ts2);
380 if (timespecisset(&ts2))
385 * If modified in this edit session, mark as modified.
388 sp->modified = modified;
390 warningx("%s unchanged", sp->tpath);
396 * Parse sudoers after editing and re-edit any ones that caused a parse error.
397 * Returns TRUE on success, else FALSE.
400 reparse_sudoers(editor, args, strict, quiet)
404 struct sudoersfile *sp, *last;
409 * Parse the edited sudoers files and do sanity checking
412 sp = tq_first(&sudoerslist);
413 last = tq_last(&sudoerslist);
414 fp = fopen(sp->tpath, "r+");
416 errorx(1, "can't re-open temporary file (%s), %s unchanged.",
417 sp->tpath, sp->path);
419 /* Clean slate for each parse */
421 init_parser(sp->path, quiet);
423 /* Parse the sudoers temp file */
425 if (yyparse() && parse_error != TRUE) {
426 warningx("unabled to parse temporary file (%s), unknown error",
431 if (check_aliases(strict) != 0)
435 * Got an error, prompt the user for what to do now
439 case 'Q' : parse_error = FALSE; /* ignore parse error */
441 case 'x' : cleanup(0);
447 /* Edit file with the parse error */
448 tq_foreach_fwd(&sudoerslist, sp) {
449 if (errorfile == NULL || strcmp(sp->path, errorfile) == 0) {
450 edit_sudoers(sp, editor, args, errorlineno);
455 errorx(1, "internal error, can't find %s in list!", sudoers);
458 /* If any new #include directives were added, edit them too. */
459 for (sp = last->next; sp != NULL; sp = sp->next) {
460 printf("press return to edit %s: ", sp->path);
461 while ((ch = getchar()) != EOF && ch != '\n')
463 edit_sudoers(sp, editor, args, errorlineno);
465 } while (parse_error);
471 * Set the owner and mode on a sudoers temp file and
472 * move it into place. Returns TRUE on success, else FALSE.
475 install_sudoers(sp, oldperms)
476 struct sudoersfile *sp;
482 * Change mode and ownership of temp file so when
483 * we move it to sp->path things are kosher.
486 /* Use perms of the existing file. */
488 if (fstat(sp->fd, &sb) == -1)
490 if (stat(sp->path, &sb) == -1)
492 error(1, "can't stat %s", sp->path);
493 (void) chown(sp->tpath, sb.st_uid, sb.st_gid);
494 (void) chmod(sp->tpath, sb.st_mode & 0777);
496 if (chown(sp->tpath, SUDOERS_UID, SUDOERS_GID) != 0) {
497 warning("unable to set (uid, gid) of %s to (%d, %d)",
498 sp->tpath, SUDOERS_UID, SUDOERS_GID);
501 if (chmod(sp->tpath, SUDOERS_MODE) != 0) {
502 warning("unable to change mode of %s to 0%o", sp->tpath,
509 * Now that sp->tpath is sane (parses ok) it needs to be
510 * rename(2)'d to sp->path. If the rename(2) fails we try using
511 * mv(1) in case sp->tpath and sp->path are on different file systems.
513 if (rename(sp->tpath, sp->path) == 0) {
517 if (errno == EXDEV) {
519 warningx("%s and %s not on the same file system, using mv to rename",
520 sp->tpath, sp->path);
522 /* Build up argument vector for the command */
523 if ((av[0] = strrchr(_PATH_MV, '/')) != NULL)
532 if (run_command(_PATH_MV, av)) {
533 warningx("command failed: '%s %s %s', %s unchanged",
534 _PATH_MV, sp->tpath, sp->path, sp->path);
535 (void) unlink(sp->tpath);
543 warning("error renaming %s, %s unchanged", sp->tpath, sp->path);
544 (void) unlink(sp->tpath);
588 const struct passwd *pw;
590 return (pw->pw_passwd);
594 * Assuming a parse error occurred, prompt the user for what they want
595 * to do now. Returns the first letter of their choice.
603 (void) fputs("What now? ", stdout);
605 for (c = choice; c != '\n' && c != EOF;)
617 (void) puts("Options are:");
618 (void) puts(" (e)dit sudoers file again");
619 (void) puts(" e(x)it without saving changes to sudoers file");
620 (void) puts(" (Q)uit and save changes to sudoers file (DANGER!)\n");
626 * Install signal handlers for visudo.
634 * Setup signal handlers to cleanup nicely.
636 zero_bytes(&sa, sizeof(sa));
637 sigemptyset(&sa.sa_mask);
638 sa.sa_flags = SA_RESTART;
639 sa.sa_handler = quit;
640 (void) sigaction(SIGTERM, &sa, NULL);
641 (void) sigaction(SIGHUP, &sa, NULL);
642 (void) sigaction(SIGINT, &sa, NULL);
643 (void) sigaction(SIGQUIT, &sa, NULL);
647 run_command(path, argv)
654 switch (pid = fork()) {
656 error(1, "unable to run %s", path);
657 break; /* NOTREACHED */
661 closefrom(STDERR_FILENO + 1);
663 warning("unable to run %s", path);
665 break; /* NOTREACHED */
670 rv = sudo_waitpid(pid, &status, 0);
674 } while (rv == -1 && errno == EINTR);
676 if (rv == -1 || !WIFEXITED(status))
678 return(WEXITSTATUS(status));
682 check_syntax(sudoers_path, quiet, strict)
690 if ((yyin = fopen(sudoers_path, "r")) == NULL) {
692 warning("unable to open %s", sudoers_path);
695 init_parser(sudoers_path, quiet);
696 if (yyparse() && parse_error != TRUE) {
698 warningx("failed to parse %s file, unknown error", sudoers_path);
704 (void) printf("parse error in %s near line %d\n", sudoers_path,
707 (void) printf("%s: parsed OK\n", sudoers_path);
709 /* Check mode and owner in strict mode. */
711 if (strict && fstat(fileno(yyin), &sb) == 0)
713 if (strict && stat(sudoers_path, &sb) == 0)
716 if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID) {
719 fprintf(stderr, "%s: wrong owner (uid, gid) should be (%d, %d)\n",
720 sudoers_path, SUDOERS_UID, SUDOERS_GID);
723 if ((sb.st_mode & 07777) != SUDOERS_MODE) {
726 fprintf(stderr, "%s: bad permissions, should be mode 0%o\n",
727 sudoers_path, SUDOERS_MODE);
736 * Used to open (and lock) the initial sudoers file and to also open
737 * any subsequent files #included via a callback from the parser.
740 open_sudoers(path, keepopen)
744 struct sudoersfile *entry;
747 /* Check for existing entry */
748 tq_foreach_fwd(&sudoerslist, entry) {
749 if (strcmp(path, entry->path) == 0)
753 entry = emalloc(sizeof(*entry));
754 entry->path = estrdup(path);
757 entry->fd = open(entry->path, O_RDWR | O_CREAT, SUDOERS_MODE);
759 if (entry->fd == -1) {
760 warning("%s", entry->path);
764 if (!lock_file(entry->fd, SUDO_TLOCK))
765 errorx(1, "%s busy, try again later", entry->path);
766 if ((fp = fdopen(entry->fd, "r")) == NULL)
767 error(1, "%s", entry->path);
768 /* XXX - macro here? */
769 if (sudoerslist.last == NULL)
770 sudoerslist.first = sudoerslist.last = entry;
772 sudoerslist.last->next = entry;
773 sudoerslist.last = entry;
775 if (keepopen != NULL)
778 /* Already exists, open .tmp version if there is one. */
779 if (entry->tpath != NULL) {
780 if ((fp = fopen(entry->tpath, "r")) == NULL)
781 error(1, "%s", entry->tpath);
783 if ((fp = fdopen(entry->fd, "r")) == NULL)
784 error(1, "%s", entry->path);
794 char *Editor, *EditorArgs, *EditorPath, *UserEditor, *UserEditorArgs;
797 * Check VISUAL and EDITOR environment variables to see which editor
798 * the user wants to use (we may not end up using it though).
799 * If the path is not fully-qualified, make it so and check that
800 * the specified executable actually exists.
802 UserEditorArgs = NULL;
803 if ((UserEditor = getenv("VISUAL")) == NULL || *UserEditor == '\0')
804 UserEditor = getenv("EDITOR");
805 if (UserEditor && *UserEditor == '\0')
807 else if (UserEditor) {
808 UserEditorArgs = get_args(UserEditor);
809 if (find_path(UserEditor, &Editor, NULL, getenv("PATH")) == FOUND) {
812 if (def_env_editor) {
813 /* If we are honoring $EDITOR this is a fatal error. */
814 errorx(1, "specified editor (%s) doesn't exist!", UserEditor);
816 /* Otherwise, just ignore $EDITOR. */
823 * See if we can use the user's choice of editors either because
824 * we allow any $EDITOR or because $EDITOR is in the allowable list.
826 Editor = EditorArgs = EditorPath = NULL;
827 if (def_env_editor && UserEditor) {
829 EditorArgs = UserEditorArgs;
830 } else if (UserEditor) {
831 struct stat editor_sb;
832 struct stat user_editor_sb;
833 char *base, *userbase;
835 if (stat(UserEditor, &user_editor_sb) != 0) {
836 /* Should never happen since we already checked above. */
837 error(1, "unable to stat editor (%s)", UserEditor);
839 EditorPath = estrdup(def_editor);
840 Editor = strtok(EditorPath, ":");
842 EditorArgs = get_args(Editor);
844 * Both Editor and UserEditor should be fully qualified but
847 if ((base = strrchr(Editor, '/')) == NULL)
849 if ((userbase = strrchr(UserEditor, '/')) == NULL) {
856 * We compare the basenames first and then use stat to match
859 if (strcmp(base, userbase) == 0) {
860 if (stat(Editor, &editor_sb) == 0 && S_ISREG(editor_sb.st_mode)
861 && (editor_sb.st_mode & 0000111) &&
862 editor_sb.st_dev == user_editor_sb.st_dev &&
863 editor_sb.st_ino == user_editor_sb.st_ino)
866 } while ((Editor = strtok(NULL, ":")));
870 * Can't use $EDITOR, try each element of def_editor until we
871 * find one that exists, is regular, and is executable.
873 if (Editor == NULL || *Editor == '\0') {
875 EditorPath = estrdup(def_editor);
876 Editor = strtok(EditorPath, ":");
878 EditorArgs = get_args(Editor);
879 if (sudo_goodpath(Editor, NULL))
881 } while ((Editor = strtok(NULL, ":")));
883 /* Bleah, none of the editors existed! */
884 if (Editor == NULL || *Editor == '\0')
885 errorx(1, "no editor found (editor path = %s)", def_editor);
892 * Split out any command line arguments and return them.
901 while (*args && !isblank((unsigned char) *args))
905 while (*args && isblank((unsigned char) *args))
908 return(*args ? args : NULL);
912 * Iterate through the sudoers datastructures looking for undefined
913 * aliases or unused aliases.
916 check_aliases(strict)
920 struct member *m, *binding;
921 struct privilege *priv;
924 int atype, error = 0;
927 tq_foreach_fwd(&userspecs, us) {
928 tq_foreach_fwd(&us->users, m) {
929 if (m->type == ALIAS) {
931 if (find_alias(m->name, USERALIAS) == NULL) {
932 warningx("%s: User_Alias `%s' referenced but not defined",
933 strict ? "Error" : "Warning", m->name);
938 tq_foreach_fwd(&us->privileges, priv) {
939 tq_foreach_fwd(&priv->hostlist, m) {
940 if (m->type == ALIAS) {
942 if (find_alias(m->name, HOSTALIAS) == NULL) {
943 warningx("%s: Host_Alias `%s' referenced but not defined",
944 strict ? "Error" : "Warning", m->name);
949 tq_foreach_fwd(&priv->cmndlist, cs) {
950 tq_foreach_fwd(&cs->runasuserlist, m) {
951 if (m->type == ALIAS) {
953 if (find_alias(m->name, RUNASALIAS) == NULL) {
954 warningx("%s: Runas_Alias `%s' referenced but not defined",
955 strict ? "Error" : "Warning", m->name);
960 if ((m = cs->cmnd)->type == ALIAS) {
962 if (find_alias(m->name, CMNDALIAS) == NULL) {
963 warningx("%s: Cmnd_Alias `%s' referenced but not defined",
964 strict ? "Error" : "Warning", m->name);
972 /* Reverse check (destructive) */
973 tq_foreach_fwd(&userspecs, us) {
974 tq_foreach_fwd(&us->users, m) {
975 if (m->type == ALIAS)
976 (void) alias_remove(m->name, USERALIAS);
978 tq_foreach_fwd(&us->privileges, priv) {
979 tq_foreach_fwd(&priv->hostlist, m) {
980 if (m->type == ALIAS)
981 (void) alias_remove(m->name, HOSTALIAS);
983 tq_foreach_fwd(&priv->cmndlist, cs) {
984 tq_foreach_fwd(&cs->runasuserlist, m) {
985 if (m->type == ALIAS)
986 (void) alias_remove(m->name, RUNASALIAS);
988 if ((m = cs->cmnd)->type == ALIAS)
989 (void) alias_remove(m->name, CMNDALIAS);
993 tq_foreach_fwd(&defaults, d) {
1001 case DEFAULTS_RUNAS:
1008 continue; /* not an alias */
1010 tq_foreach_fwd(&d->binding, binding) {
1011 for (m = binding; m != NULL; m = m->next) {
1012 if (m->type == ALIAS)
1013 (void) alias_remove(m->name, atype);
1018 /* If all aliases were referenced we will have an empty tree. */
1021 alias_apply(print_unused, strict ? "Error" : "Warning");
1022 return (strict ? 1 : 0);
1026 print_unused(v1, v2)
1030 struct alias *a = (struct alias *)v1;
1031 char *prefix = (char *)v2;
1033 warningx("%s: unused %s_Alias %s", prefix,
1034 a->type == HOSTALIAS ? "Host" : a->type == CMNDALIAS ? "Cmnd" :
1035 a->type == USERALIAS ? "User" : a->type == RUNASALIAS ? "Runas" :
1036 "Unknown", a->name);
1041 * Unlink any sudoers temp files that remain.
1047 struct sudoersfile *sp;
1049 tq_foreach_fwd(&sudoerslist, sp) {
1050 if (sp->tpath != NULL)
1051 (void) unlink(sp->tpath);
1060 * Unlink sudoers temp files (if any) and exit.
1067 #define emsg " exiting due to signal.\n"
1068 write(STDERR_FILENO, getprogname(), strlen(getprogname()));
1069 write(STDERR_FILENO, emsg, sizeof(emsg) - 1);
1076 (void) fprintf(stderr, "usage: %s [-c] [-q] [-s] [-V] [-f sudoers]\n",