2 * Copyright (c) 1996, 1998-2005, 2007-2012
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 */
54 #endif /* HAVE_STRING_H */
57 #endif /* HAVE_STRINGS_H */
60 #endif /* HAVE_UNISTD_H */
68 #include <netinet/in.h>
69 #include <arpa/inet.h>
71 #if TIME_WITH_SYS_TIME
79 #include "interfaces.h"
83 #include "sudoers_version.h"
84 #include "sudo_conf.h"
88 struct sudoersfile *prev, *next;
95 TQ_DECLARE(sudoersfile)
97 sudo_conv_t sudo_conv; /* NULL in non-plugin */
100 * Function prototypes
102 static void quit(int);
103 static char *get_args(char *);
104 static char *get_editor(char **);
105 static void get_hostname(void);
106 static int whatnow(void);
107 static int check_aliases(bool, bool);
108 static bool check_syntax(char *, bool, bool, bool);
109 static bool edit_sudoers(struct sudoersfile *, char *, char *, int);
110 static bool install_sudoers(struct sudoersfile *, bool);
111 static int print_unused(void *, void *);
112 static void reparse_sudoers(char *, char *, bool, bool);
113 static int run_command(char *, char **);
114 static int visudo_printf(int msg_type, const char *fmt, ...);
115 static void setup_signals(void);
116 static void help(void) __attribute__((__noreturn__));
117 static void usage(int);
121 extern void yyerror(const char *);
122 extern void yyrestart(FILE *);
125 * External globals exported by the parser
127 extern struct rbtree *aliases;
129 extern char *sudoers, *errorfile;
130 extern int errorlineno;
131 extern bool parse_error;
139 struct interface *interfaces;
140 struct sudo_user sudo_user;
141 struct passwd *list_pw;
142 sudo_printf_t sudo_printf = visudo_printf;
143 static struct sudoersfile_list sudoerslist;
144 static struct rbtree *alias_freelist;
145 static bool checkonly;
148 main(int argc, char *argv[])
150 struct sudoersfile *sp;
151 char *args, *editor, *sudoers_path;
152 int ch, exitcode = 0;
153 bool quiet, strict, oldperms;
154 debug_decl(main, SUDO_DEBUG_MAIN)
156 #if defined(SUDO_DEVEL) && defined(__OpenBSD__)
158 extern char *malloc_options;
159 malloc_options = "AFGJPR";
163 #if !defined(HAVE_GETPROGNAME) && !defined(HAVE___PROGNAME)
164 setprogname(argc > 0 ? argv[0] : "visudo");
167 #ifdef HAVE_SETLOCALE
168 setlocale(LC_ALL, "");
170 bindtextdomain("sudoers", LOCALEDIR); /* XXX - should have visudo domain */
171 textdomain("sudoers");
176 /* Read sudo.conf. */
182 checkonly = oldperms = quiet = strict = false;
183 sudoers_path = _PATH_SUDOERS;
184 while ((ch = getopt(argc, argv, "Vcf:sq")) != -1) {
187 (void) printf(_("%s version %s\n"), getprogname(), PACKAGE_VERSION);
188 (void) printf(_("%s grammar version %d\n"), getprogname(), SUDOERS_GRAMMAR_VERSION);
191 checkonly++; /* check mode */
194 sudoers_path = optarg; /* sudoers file path */
201 strict++; /* strict mode */
204 quiet++; /* quiet mode */
218 /* Mock up a fake sudo_user struct. */
220 if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL)
221 errorx(1, _("you do not exist in the %s database"), "passwd");
224 /* Setup defaults data structures. */
228 exitcode = check_syntax(sudoers_path, quiet, strict, oldperms) ? 0 : 1;
233 * Parse the existing sudoers file(s) in quiet mode to highlight any
234 * existing errors and to pull in editor and env_editor conf values.
236 if ((yyin = open_sudoers(sudoers_path, true, NULL)) == NULL) {
237 error(1, "%s", sudoers_path);
239 init_parser(sudoers_path, 0);
241 (void) update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER);
243 editor = get_editor(&args);
245 /* Install signal handlers to clean up temp files if we are killed. */
248 /* Edit the sudoers file(s) */
249 tq_foreach_fwd(&sudoerslist, sp) {
252 if (sp != tq_first(&sudoerslist)) {
253 printf(_("press return to edit %s: "), sp->path);
254 while ((ch = getchar()) != EOF && ch != '\n')
257 edit_sudoers(sp, editor, args, -1);
260 /* Check edited files for a parse error and re-edit any that fail. */
261 reparse_sudoers(editor, args, strict, quiet);
263 /* Install the sudoers temp files as needed. */
264 tq_foreach_fwd(&sudoerslist, sp) {
265 (void) install_sudoers(sp, oldperms);
269 sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, exitcode);
274 * List of editors that support the "+lineno" command line syntax.
275 * If an entry starts with '*' the tail end of the string is matched.
276 * No other wild cards are supported.
278 static char *lineno_editors[] = {
298 * Edit each sudoers file.
299 * Returns true on success, else false.
302 edit_sudoers(struct sudoersfile *sp, char *editor, char *args, int lineno)
304 int tfd; /* sudoers temp file descriptor */
305 bool modified; /* was the file modified? */
306 int ac; /* argument count */
307 char **av; /* argument vector for run_command */
308 char *cp; /* scratch char pointer */
309 char buf[PATH_MAX*2]; /* buffer used for copying files */
310 char linestr[64]; /* string version of lineno */
311 struct timeval tv, tv1, tv2; /* time before and after edit */
312 struct timeval orig_mtim; /* starting mtime of sudoers file */
313 off_t orig_size; /* starting size of sudoers file */
314 ssize_t nread; /* number of bytes read */
315 struct stat sb; /* stat buffer */
316 bool rval = false; /* return value */
317 debug_decl(edit_sudoers, SUDO_DEBUG_UTIL)
319 if (fstat(sp->fd, &sb) == -1)
320 error(1, _("unable to stat %s"), sp->path);
321 orig_size = sb.st_size;
322 mtim_get(&sb, &orig_mtim);
324 /* Create the temp file if needed and set timestamp. */
325 if (sp->tpath == NULL) {
326 easprintf(&sp->tpath, "%s.tmp", sp->path);
327 tfd = open(sp->tpath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
329 error(1, "%s", sp->tpath);
331 /* Copy sp->path -> sp->tpath and reset the mtime. */
332 if (orig_size != 0) {
333 (void) lseek(sp->fd, (off_t)0, SEEK_SET);
334 while ((nread = read(sp->fd, buf, sizeof(buf))) > 0)
335 if (write(tfd, buf, nread) != nread)
336 error(1, _("write error"));
338 /* Add missing newline at EOF if needed. */
339 if (nread > 0 && buf[nread - 1] != '\n') {
341 if (write(tfd, buf, 1) != 1)
342 error(1, _("write error"));
347 (void) touch(-1, sp->tpath, &orig_mtim);
349 /* Does the editor support +lineno? */
352 char *editor_base = strrchr(editor, '/');
353 if (editor_base != NULL)
356 editor_base = editor;
357 if (*editor_base == 'r')
360 for (av = lineno_editors; (cp = *av) != NULL; av++) {
361 /* We only handle a leading '*' wildcard. */
363 size_t blen = strlen(editor_base);
364 size_t clen = strlen(++cp);
366 if (strcmp(cp, editor_base + blen - clen) == 0)
369 } else if (strcmp(cp, editor_base) == 0)
372 /* Disable +lineno if editor doesn't support it. */
377 /* Find the length of the argument vector */
378 ac = 3 + (lineno > 0);
383 for (wasblank = false, cp = args; *cp; cp++) {
384 if (isblank((unsigned char) *cp))
393 /* Build up argument vector for the command */
394 av = emalloc2(ac, sizeof(char *));
395 if ((av[0] = strrchr(editor, '/')) != NULL)
401 (void) snprintf(linestr, sizeof(linestr), "+%d", lineno);
405 for ((cp = strtok(args, " \t")); cp; (cp = strtok(NULL, " \t")))
408 av[ac++] = sp->tpath;
413 * We cannot check the editor's exit value against 0 since
414 * XPG4 specifies that vi's exit value is a function of the
415 * number of errors during editing (?!?!).
417 gettimeofday(&tv1, NULL);
418 if (run_command(editor, av) != -1) {
419 gettimeofday(&tv2, NULL);
423 if (stat(sp->tpath, &sb) < 0) {
424 warningx(_("unable to stat temporary file (%s), %s unchanged"),
425 sp->tpath, sp->path);
428 if (sb.st_size == 0 && orig_size != 0) {
429 warningx(_("zero length temporary file (%s), %s unchanged"),
430 sp->tpath, sp->path);
435 warningx(_("editor (%s) failed, %s unchanged"), editor, sp->path);
439 /* Set modified bit if use changed the file. */
442 if (orig_size == sb.st_size && timevalcmp(&orig_mtim, &tv, ==)) {
444 * If mtime and size match but the user spent no measurable
445 * time in the editor we can't tell if the file was changed.
447 timevalsub(&tv1, &tv2);
448 if (timevalisset(&tv2))
453 * If modified in this edit session, mark as modified.
456 sp->modified = modified;
458 warningx(_("%s unchanged"), sp->tpath);
462 debug_return_bool(rval);
466 * Parse sudoers after editing and re-edit any ones that caused a parse error.
469 reparse_sudoers(char *editor, char *args, bool strict, bool quiet)
471 struct sudoersfile *sp, *last;
474 debug_decl(reparse_sudoers, SUDO_DEBUG_UTIL)
477 * Parse the edited sudoers files and do sanity checking
480 sp = tq_first(&sudoerslist);
481 last = tq_last(&sudoerslist);
482 fp = fopen(sp->tpath, "r+");
484 errorx(1, _("unable to re-open temporary file (%s), %s unchanged."),
485 sp->tpath, sp->path);
487 /* Clean slate for each parse */
489 init_parser(sp->path, quiet);
491 /* Parse the sudoers temp file */
493 if (yyparse() && !parse_error) {
494 warningx(_("unabled to parse temporary file (%s), unknown error"),
497 errorfile = sp->path;
501 if (!update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER) ||
502 check_aliases(strict, quiet) != 0) {
504 errorfile = sp->path;
509 * Got an error, prompt the user for what to do now
513 case 'Q' : parse_error = false; /* ignore parse error */
515 case 'x' : /* XXX - should return instead of exiting */
517 sudo_debug_exit_int(__func__, __FILE__,
518 __LINE__, sudo_debug_subsys, 0);
524 /* Edit file with the parse error */
525 tq_foreach_fwd(&sudoerslist, sp) {
526 if (errorfile == NULL || strcmp(sp->path, errorfile) == 0) {
527 edit_sudoers(sp, editor, args, errorlineno);
532 errorx(1, _("internal error, unable to find %s in list!"),
537 /* If any new #include directives were added, edit them too. */
538 for (sp = last->next; sp != NULL; sp = sp->next) {
539 printf(_("press return to edit %s: "), sp->path);
540 while ((ch = getchar()) != EOF && ch != '\n')
542 edit_sudoers(sp, editor, args, errorlineno);
544 } while (parse_error);
550 * Set the owner and mode on a sudoers temp file and
551 * move it into place. Returns true on success, else false.
554 install_sudoers(struct sudoersfile *sp, bool oldperms)
558 debug_decl(install_sudoers, SUDO_DEBUG_UTIL)
562 * No changes but fix owner/mode if needed.
564 (void) unlink(sp->tpath);
565 if (!oldperms && fstat(sp->fd, &sb) != -1) {
566 if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID)
567 (void) chown(sp->path, SUDOERS_UID, SUDOERS_GID);
568 if ((sb.st_mode & 0777) != SUDOERS_MODE)
569 (void) chmod(sp->path, SUDOERS_MODE);
576 * Change mode and ownership of temp file so when
577 * we move it to sp->path things are kosher.
580 /* Use perms of the existing file. */
581 if (fstat(sp->fd, &sb) == -1)
582 error(1, _("unable to stat %s"), sp->path);
583 if (chown(sp->tpath, sb.st_uid, sb.st_gid) != 0) {
584 warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
585 sp->tpath, (unsigned int)sb.st_uid, (unsigned int)sb.st_gid);
587 if (chmod(sp->tpath, sb.st_mode & 0777) != 0) {
588 warning(_("unable to change mode of %s to 0%o"), sp->tpath,
589 (unsigned int)(sb.st_mode & 0777));
592 if (chown(sp->tpath, SUDOERS_UID, SUDOERS_GID) != 0) {
593 warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
594 sp->tpath, SUDOERS_UID, SUDOERS_GID);
597 if (chmod(sp->tpath, SUDOERS_MODE) != 0) {
598 warning(_("unable to change mode of %s to 0%o"), sp->tpath,
605 * Now that sp->tpath is sane (parses ok) it needs to be
606 * rename(2)'d to sp->path. If the rename(2) fails we try using
607 * mv(1) in case sp->tpath and sp->path are on different file systems.
609 if (rename(sp->tpath, sp->path) == 0) {
613 if (errno == EXDEV) {
615 warningx(_("%s and %s not on the same file system, using mv to rename"),
616 sp->tpath, sp->path);
618 /* Build up argument vector for the command */
619 if ((av[0] = strrchr(_PATH_MV, '/')) != NULL)
628 if (run_command(_PATH_MV, av)) {
629 warningx(_("command failed: '%s %s %s', %s unchanged"),
630 _PATH_MV, sp->tpath, sp->path, sp->path);
631 (void) unlink(sp->tpath);
639 warning(_("error renaming %s, %s unchanged"), sp->tpath, sp->path);
640 (void) unlink(sp->tpath);
646 debug_return_bool(rval);
686 group_plugin_query(const char *user, const char *group, const struct passwd *pw)
692 * Assuming a parse error occurred, prompt the user for what they want
693 * to do now. Returns the first letter of their choice.
699 debug_decl(whatnow, SUDO_DEBUG_UTIL)
702 (void) fputs(_("What now? "), stdout);
704 for (c = choice; c != '\n' && c != EOF;)
714 debug_return_int(choice);
716 (void) puts(_("Options are:\n"
717 " (e)dit sudoers file again\n"
718 " e(x)it without saving changes to sudoers file\n"
719 " (Q)uit and save changes to sudoers file (DANGER!)\n"));
725 * Install signal handlers for visudo.
731 debug_decl(setup_signals, SUDO_DEBUG_UTIL)
734 * Setup signal handlers to cleanup nicely.
736 zero_bytes(&sa, sizeof(sa));
737 sigemptyset(&sa.sa_mask);
738 sa.sa_flags = SA_RESTART;
739 sa.sa_handler = quit;
740 (void) sigaction(SIGTERM, &sa, NULL);
741 (void) sigaction(SIGHUP, &sa, NULL);
742 (void) sigaction(SIGINT, &sa, NULL);
743 (void) sigaction(SIGQUIT, &sa, NULL);
749 run_command(char *path, char **argv)
753 debug_decl(run_command, SUDO_DEBUG_UTIL)
755 switch (pid = fork()) {
757 error(1, _("unable to execute %s"), path);
758 break; /* NOTREACHED */
762 closefrom(STDERR_FILENO + 1);
764 warning(_("unable to run %s"), path);
766 break; /* NOTREACHED */
770 rv = waitpid(pid, &status, 0);
771 } while (rv == -1 && errno == EINTR);
774 rv = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
775 debug_return_int(rv);
779 check_owner(const char *path, bool quiet)
783 debug_decl(check_owner, SUDO_DEBUG_UTIL)
785 if (stat(path, &sb) == 0) {
786 if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID) {
790 _("%s: wrong owner (uid, gid) should be (%u, %u)\n"),
791 path, SUDOERS_UID, SUDOERS_GID);
794 if ((sb.st_mode & 07777) != SUDOERS_MODE) {
797 fprintf(stderr, _("%s: bad permissions, should be mode 0%o\n"),
802 debug_return_bool(ok);
806 check_syntax(char *sudoers_path, bool quiet, bool strict, bool oldperms)
809 debug_decl(check_syntax, SUDO_DEBUG_UTIL)
811 if (strcmp(sudoers_path, "-") == 0) {
813 sudoers_path = "stdin";
814 } else if ((yyin = fopen(sudoers_path, "r")) == NULL) {
816 warning(_("unable to open %s"), sudoers_path);
819 init_parser(sudoers_path, quiet);
820 if (yyparse() && !parse_error) {
822 warningx(_("failed to parse %s file, unknown error"), sudoers_path);
824 errorfile = sudoers_path;
826 if (!parse_error && check_aliases(strict, quiet) != 0) {
828 errorfile = sudoers_path;
834 if (errorlineno != -1)
835 (void) printf(_("parse error in %s near line %d\n"),
836 errorfile, errorlineno);
838 (void) printf(_("parse error in %s\n"), errorfile);
841 struct sudoersfile *sp;
843 /* Parsed OK, check mode and owner. */
844 if (oldperms || check_owner(sudoers_path, quiet))
845 (void) printf(_("%s: parsed OK\n"), sudoers_path);
848 tq_foreach_fwd(&sudoerslist, sp) {
849 if (oldperms || check_owner(sp->path, quiet))
850 (void) printf(_("%s: parsed OK\n"), sp->path);
857 debug_return_bool(ok);
861 * Used to open (and lock) the initial sudoers file and to also open
862 * any subsequent files #included via a callback from the parser.
865 open_sudoers(const char *path, bool doedit, bool *keepopen)
867 struct sudoersfile *entry;
870 debug_decl(open_sudoers, SUDO_DEBUG_UTIL)
873 open_flags = O_RDONLY;
875 open_flags = O_RDWR | O_CREAT;
877 /* Check for existing entry */
878 tq_foreach_fwd(&sudoerslist, entry) {
879 if (strcmp(path, entry->path) == 0)
883 entry = emalloc(sizeof(*entry));
884 entry->path = estrdup(path);
888 entry->fd = open(entry->path, open_flags, SUDOERS_MODE);
890 entry->doedit = doedit;
891 if (entry->fd == -1) {
892 warning("%s", entry->path);
894 debug_return_ptr(NULL);
896 if (!checkonly && !lock_file(entry->fd, SUDO_TLOCK))
897 errorx(1, _("%s busy, try again later"), entry->path);
898 if ((fp = fdopen(entry->fd, "r")) == NULL)
899 error(1, "%s", entry->path);
900 tq_append(&sudoerslist, entry);
902 /* Already exists, open .tmp version if there is one. */
903 if (entry->tpath != NULL) {
904 if ((fp = fopen(entry->tpath, "r")) == NULL)
905 error(1, "%s", entry->tpath);
907 if ((fp = fdopen(entry->fd, "r")) == NULL)
908 error(1, "%s", entry->path);
912 if (keepopen != NULL)
914 debug_return_ptr(fp);
918 get_editor(char **args)
920 char *Editor, *EditorArgs, *EditorPath, *UserEditor, *UserEditorArgs;
921 debug_decl(get_editor, SUDO_DEBUG_UTIL)
924 * Check VISUAL and EDITOR environment variables to see which editor
925 * the user wants to use (we may not end up using it though).
926 * If the path is not fully-qualified, make it so and check that
927 * the specified executable actually exists.
929 UserEditorArgs = NULL;
930 if ((UserEditor = getenv("VISUAL")) == NULL || *UserEditor == '\0')
931 UserEditor = getenv("EDITOR");
932 if (UserEditor && *UserEditor == '\0')
934 else if (UserEditor) {
935 UserEditorArgs = get_args(UserEditor);
936 if (find_path(UserEditor, &Editor, NULL, getenv("PATH"), 0) == FOUND) {
939 if (def_env_editor) {
940 /* If we are honoring $EDITOR this is a fatal error. */
941 errorx(1, _("specified editor (%s) doesn't exist"), UserEditor);
943 /* Otherwise, just ignore $EDITOR. */
950 * See if we can use the user's choice of editors either because
951 * we allow any $EDITOR or because $EDITOR is in the allowable list.
953 Editor = EditorArgs = EditorPath = NULL;
954 if (def_env_editor && UserEditor) {
956 EditorArgs = UserEditorArgs;
957 } else if (UserEditor) {
958 struct stat editor_sb;
959 struct stat user_editor_sb;
960 char *base, *userbase;
962 if (stat(UserEditor, &user_editor_sb) != 0) {
963 /* Should never happen since we already checked above. */
964 error(1, _("unable to stat editor (%s)"), UserEditor);
966 EditorPath = estrdup(def_editor);
967 Editor = strtok(EditorPath, ":");
969 EditorArgs = get_args(Editor);
971 * Both Editor and UserEditor should be fully qualified but
974 if ((base = strrchr(Editor, '/')) == NULL)
976 if ((userbase = strrchr(UserEditor, '/')) == NULL) {
983 * We compare the basenames first and then use stat to match
986 if (strcmp(base, userbase) == 0) {
987 if (stat(Editor, &editor_sb) == 0 && S_ISREG(editor_sb.st_mode)
988 && (editor_sb.st_mode & 0000111) &&
989 editor_sb.st_dev == user_editor_sb.st_dev &&
990 editor_sb.st_ino == user_editor_sb.st_ino)
993 } while ((Editor = strtok(NULL, ":")));
997 * Can't use $EDITOR, try each element of def_editor until we
998 * find one that exists, is regular, and is executable.
1000 if (Editor == NULL || *Editor == '\0') {
1002 EditorPath = estrdup(def_editor);
1003 Editor = strtok(EditorPath, ":");
1005 EditorArgs = get_args(Editor);
1006 if (sudo_goodpath(Editor, NULL))
1008 } while ((Editor = strtok(NULL, ":")));
1010 /* Bleah, none of the editors existed! */
1011 if (Editor == NULL || *Editor == '\0')
1012 errorx(1, _("no editor found (editor path = %s)"), def_editor);
1015 debug_return_str(Editor);
1019 * Split out any command line arguments and return them.
1022 get_args(char *cmnd)
1025 debug_decl(get_args, SUDO_DEBUG_UTIL)
1028 while (*args && !isblank((unsigned char) *args))
1032 while (*args && isblank((unsigned char) *args))
1035 debug_return_str(*args ? args : NULL);
1039 * Look up the hostname and set user_host and user_shost.
1044 char *p, thost[MAXHOSTNAMELEN + 1];
1045 debug_decl(get_hostname, SUDO_DEBUG_UTIL)
1047 if (gethostname(thost, sizeof(thost)) != -1) {
1048 thost[sizeof(thost) - 1] = '\0';
1049 user_host = estrdup(thost);
1051 if ((p = strchr(user_host, '.'))) {
1053 user_shost = estrdup(user_host);
1056 user_shost = user_host;
1059 user_host = user_shost = "localhost";
1065 alias_remove_recursive(char *name, int type)
1070 debug_decl(alias_remove_recursive, SUDO_DEBUG_ALIAS)
1072 if ((a = alias_find(name, type)) != NULL) {
1073 tq_foreach_fwd(&a->members, m) {
1074 if (m->type == ALIAS) {
1075 if (!alias_remove_recursive(m->name, type))
1081 a = alias_remove(name, type);
1083 rbinsert(alias_freelist, a);
1084 debug_return_bool(rval);
1088 check_alias(char *name, int type, int strict, int quiet)
1093 debug_decl(check_alias, SUDO_DEBUG_ALIAS)
1095 if ((a = alias_find(name, type)) != NULL) {
1096 /* check alias contents */
1097 tq_foreach_fwd(&a->members, m) {
1098 if (m->type == ALIAS)
1099 errors += check_alias(m->name, type, strict, quiet);
1104 if (errno == ELOOP) {
1106 _("Error: cycle in %s_Alias `%s'") :
1107 _("Warning: cycle in %s_Alias `%s'");
1110 _("Error: %s_Alias `%s' referenced but not defined") :
1111 _("Warning: %s_Alias `%s' referenced but not defined");
1114 type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
1115 type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
1121 debug_return_int(errors);
1125 * Iterate through the sudoers datastructures looking for undefined
1126 * aliases or unused aliases.
1129 check_aliases(bool strict, bool quiet)
1131 struct cmndspec *cs;
1132 struct member *m, *binding;
1133 struct privilege *priv;
1134 struct userspec *us;
1136 int atype, errors = 0;
1137 debug_decl(check_aliases, SUDO_DEBUG_ALIAS)
1139 alias_freelist = rbcreate(alias_compare);
1141 /* Forward check. */
1142 tq_foreach_fwd(&userspecs, us) {
1143 tq_foreach_fwd(&us->users, m) {
1144 if (m->type == ALIAS) {
1146 errors += check_alias(m->name, USERALIAS, strict, quiet);
1149 tq_foreach_fwd(&us->privileges, priv) {
1150 tq_foreach_fwd(&priv->hostlist, m) {
1151 if (m->type == ALIAS) {
1153 errors += check_alias(m->name, HOSTALIAS, strict, quiet);
1156 tq_foreach_fwd(&priv->cmndlist, cs) {
1157 tq_foreach_fwd(&cs->runasuserlist, m) {
1158 if (m->type == ALIAS) {
1160 errors += check_alias(m->name, RUNASALIAS, strict, quiet);
1163 if ((m = cs->cmnd)->type == ALIAS) {
1165 errors += check_alias(m->name, CMNDALIAS, strict, quiet);
1171 /* Reverse check (destructive) */
1172 tq_foreach_fwd(&userspecs, us) {
1173 tq_foreach_fwd(&us->users, m) {
1174 if (m->type == ALIAS) {
1176 if (!alias_remove_recursive(m->name, USERALIAS))
1180 tq_foreach_fwd(&us->privileges, priv) {
1181 tq_foreach_fwd(&priv->hostlist, m) {
1182 if (m->type == ALIAS) {
1184 if (!alias_remove_recursive(m->name, HOSTALIAS))
1188 tq_foreach_fwd(&priv->cmndlist, cs) {
1189 tq_foreach_fwd(&cs->runasuserlist, m) {
1190 if (m->type == ALIAS) {
1192 if (!alias_remove_recursive(m->name, RUNASALIAS))
1196 if ((m = cs->cmnd)->type == ALIAS) {
1198 if (!alias_remove_recursive(m->name, CMNDALIAS))
1204 tq_foreach_fwd(&defaults, d) {
1212 case DEFAULTS_RUNAS:
1219 continue; /* not an alias */
1221 tq_foreach_fwd(&d->binding, binding) {
1222 for (m = binding; m != NULL; m = m->next) {
1223 if (m->type == ALIAS) {
1225 if (!alias_remove_recursive(m->name, atype))
1231 rbdestroy(alias_freelist, alias_free);
1233 /* If all aliases were referenced we will have an empty tree. */
1234 if (!no_aliases() && !quiet)
1235 alias_apply(print_unused, strict ? "Error" : "Warning");
1237 debug_return_int(strict ? errors : 0);
1241 print_unused(void *v1, void *v2)
1243 struct alias *a = (struct alias *)v1;
1244 char *prefix = (char *)v2;
1246 warningx2(_("%s: unused %s_Alias %s"), prefix,
1247 a->type == HOSTALIAS ? "Host" : a->type == CMNDALIAS ? "Cmnd" :
1248 a->type == USERALIAS ? "User" : a->type == RUNASALIAS ? "Runas" :
1249 "Unknown", a->name);
1254 * Unlink any sudoers temp files that remain.
1257 cleanup(int gotsignal)
1259 struct sudoersfile *sp;
1261 tq_foreach_fwd(&sudoerslist, sp) {
1262 if (sp->tpath != NULL)
1263 (void) unlink(sp->tpath);
1272 * Unlink sudoers temp files (if any) and exit.
1277 const char *signame, *myname;
1280 #define emsg " exiting due to signal: "
1281 myname = getprogname();
1282 signame = strsignal(signo);
1283 if (write(STDERR_FILENO, myname, strlen(myname)) == -1 ||
1284 write(STDERR_FILENO, emsg, sizeof(emsg) - 1) == -1 ||
1285 write(STDERR_FILENO, signame, strlen(signame)) == -1 ||
1286 write(STDERR_FILENO, "\n", 1) == -1)
1287 /* shut up glibc */;
1294 (void) fprintf(fatal ? stderr : stdout,
1295 "usage: %s [-chqsV] [-f sudoers]\n", getprogname());
1303 (void) printf(_("%s - safely edit the sudoers file\n\n"), getprogname());
1305 (void) puts(_("\nOptions:\n"
1306 " -c check-only mode\n"
1307 " -f sudoers specify sudoers file location\n"
1308 " -h display help message and exit\n"
1309 " -q less verbose (quiet) syntax error messages\n"
1310 " -s strict syntax checking\n"
1311 " -V display version information and exit"));
1316 visudo_printf(int msg_type, const char *fmt, ...)
1322 case SUDO_CONV_INFO_MSG:
1325 case SUDO_CONV_ERROR_MSG:
1334 vfprintf(fp, fmt, ap);