2 * Copyright (c) 1996, 1998-2005, 2007-2013
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>
36 #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>
70 #if TIME_WITH_SYS_TIME
78 #include "sudoers_version.h"
79 #include "sudo_conf.h"
83 struct sudoersfile *prev, *next;
90 TQ_DECLARE(sudoersfile)
95 static void quit(int);
96 static char *get_args(char *);
97 static char *get_editor(char **);
98 static void get_hostname(void);
99 static int whatnow(void);
100 static int check_aliases(bool, bool);
101 static bool check_syntax(char *, bool, bool, bool);
102 static bool edit_sudoers(struct sudoersfile *, char *, char *, int);
103 static bool install_sudoers(struct sudoersfile *, bool);
104 static int print_unused(void *, void *);
105 static bool reparse_sudoers(char *, char *, bool, bool);
106 static int run_command(char *, char **);
107 static void setup_signals(void);
108 static void help(void) __attribute__((__noreturn__));
109 static void usage(int);
110 static void visudo_cleanup(void);
112 extern void sudoerserror(const char *);
113 extern void sudoersrestart(FILE *);
116 * External globals exported by the parser
118 extern struct rbtree *aliases;
119 extern FILE *sudoersin;
120 extern char *sudoers, *errorfile;
121 extern int errorlineno;
122 extern bool parse_error;
130 struct sudo_user sudo_user;
131 struct passwd *list_pw;
132 static struct sudoersfile_list sudoerslist;
133 static struct rbtree *alias_freelist;
134 static bool checkonly;
136 __dso_public int main(int argc, char *argv[]);
139 main(int argc, char *argv[])
141 struct sudoersfile *sp;
142 char *args, *editor, *sudoers_path;
143 int ch, exitcode = 0;
144 bool quiet, strict, oldperms;
145 debug_decl(main, SUDO_DEBUG_MAIN)
147 #if defined(SUDO_DEVEL) && defined(__OpenBSD__)
149 extern char *malloc_options;
150 malloc_options = "AFGJPR";
154 #if !defined(HAVE_GETPROGNAME) && !defined(HAVE___PROGNAME)
155 setprogname(argc > 0 ? argv[0] : "visudo");
158 sudoers_setlocale(SUDOERS_LOCALE_USER, NULL);
159 bindtextdomain("sudoers", LOCALEDIR); /* XXX - should have visudo domain */
160 textdomain("sudoers");
165 /* Register fatal/fatalx callback. */
166 fatal_callback_register(visudo_cleanup);
168 /* Read sudo.conf. */
169 sudo_conf_read(NULL);
174 checkonly = oldperms = quiet = strict = false;
175 sudoers_path = _PATH_SUDOERS;
176 while ((ch = getopt(argc, argv, "Vcf:sq")) != -1) {
179 (void) printf(_("%s version %s\n"), getprogname(), PACKAGE_VERSION);
180 (void) printf(_("%s grammar version %d\n"), getprogname(), SUDOERS_GRAMMAR_VERSION);
183 checkonly = true; /* check mode */
186 sudoers_path = optarg; /* sudoers file path */
193 strict = true; /* strict mode */
196 quiet = false; /* quiet mode */
202 /* There should be no other command line arguments. */
203 if (argc - optind != 0)
209 /* Mock up a fake sudo_user struct. */
211 if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL)
212 fatalx(_("you do not exist in the %s database"), "passwd");
215 /* Setup defaults data structures. */
219 exitcode = check_syntax(sudoers_path, quiet, strict, oldperms) ? 0 : 1;
224 * Parse the existing sudoers file(s) to highlight any existing
225 * errors and to pull in editor and env_editor conf values.
227 if ((sudoersin = open_sudoers(sudoers_path, true, NULL)) == NULL)
229 init_parser(sudoers_path, false);
231 (void) update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER);
233 editor = get_editor(&args);
235 /* Install signal handlers to clean up temp files if we are killed. */
238 /* Edit the sudoers file(s) */
239 tq_foreach_fwd(&sudoerslist, sp) {
242 if (sp != tq_first(&sudoerslist)) {
243 printf(_("press return to edit %s: "), sp->path);
244 while ((ch = getchar()) != EOF && ch != '\n')
247 edit_sudoers(sp, editor, args, -1);
251 * Check edited files for a parse error, re-edit any that fail
252 * and install the edited files as needed.
254 if (reparse_sudoers(editor, args, strict, quiet)) {
255 tq_foreach_fwd(&sudoerslist, sp) {
256 (void) install_sudoers(sp, oldperms);
261 sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, exitcode);
266 * List of editors that support the "+lineno" command line syntax.
267 * If an entry starts with '*' the tail end of the string is matched.
268 * No other wild cards are supported.
270 static char *lineno_editors[] = {
290 * Edit each sudoers file.
291 * Returns true on success, else false.
294 edit_sudoers(struct sudoersfile *sp, char *editor, char *args, int lineno)
296 int tfd; /* sudoers temp file descriptor */
297 bool modified; /* was the file modified? */
298 int ac; /* argument count */
299 char **av; /* argument vector for run_command */
300 char *cp; /* scratch char pointer */
301 char buf[PATH_MAX*2]; /* buffer used for copying files */
302 char linestr[64]; /* string version of lineno */
303 struct timeval tv, tv1, tv2; /* time before and after edit */
304 struct timeval orig_mtim; /* starting mtime of sudoers file */
305 off_t orig_size; /* starting size of sudoers file */
306 ssize_t nread; /* number of bytes read */
307 struct stat sb; /* stat buffer */
308 bool rval = false; /* return value */
309 debug_decl(edit_sudoers, SUDO_DEBUG_UTIL)
311 if (fstat(sp->fd, &sb) == -1)
312 fatal(_("unable to stat %s"), sp->path);
313 orig_size = sb.st_size;
314 mtim_get(&sb, &orig_mtim);
316 /* Create the temp file if needed and set timestamp. */
317 if (sp->tpath == NULL) {
318 easprintf(&sp->tpath, "%s.tmp", sp->path);
319 tfd = open(sp->tpath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
321 fatal("%s", sp->tpath);
323 /* Copy sp->path -> sp->tpath and reset the mtime. */
324 if (orig_size != 0) {
325 (void) lseek(sp->fd, (off_t)0, SEEK_SET);
326 while ((nread = read(sp->fd, buf, sizeof(buf))) > 0)
327 if (write(tfd, buf, nread) != nread)
328 fatal(_("write error"));
330 /* Add missing newline at EOF if needed. */
331 if (nread > 0 && buf[nread - 1] != '\n') {
333 if (write(tfd, buf, 1) != 1)
334 fatal(_("write error"));
339 (void) touch(-1, sp->tpath, &orig_mtim);
341 /* Does the editor support +lineno? */
344 char *editor_base = strrchr(editor, '/');
345 if (editor_base != NULL)
348 editor_base = editor;
349 if (*editor_base == 'r')
352 for (av = lineno_editors; (cp = *av) != NULL; av++) {
353 /* We only handle a leading '*' wildcard. */
355 size_t blen = strlen(editor_base);
356 size_t clen = strlen(++cp);
358 if (strcmp(cp, editor_base + blen - clen) == 0)
361 } else if (strcmp(cp, editor_base) == 0)
364 /* Disable +lineno if editor doesn't support it. */
369 /* Find the length of the argument vector */
370 ac = 3 + (lineno > 0);
375 for (wasblank = false, cp = args; *cp; cp++) {
376 if (isblank((unsigned char) *cp))
385 /* Build up argument vector for the command */
386 av = emalloc2(ac, sizeof(char *));
387 if ((av[0] = strrchr(editor, '/')) != NULL)
393 (void) snprintf(linestr, sizeof(linestr), "+%d", lineno);
397 for ((cp = strtok(args, " \t")); cp; (cp = strtok(NULL, " \t")))
400 av[ac++] = sp->tpath;
405 * We cannot check the editor's exit value against 0 since
406 * XPG4 specifies that vi's exit value is a function of the
407 * number of errors during editing (?!?!).
409 gettimeofday(&tv1, NULL);
410 if (run_command(editor, av) != -1) {
411 gettimeofday(&tv2, NULL);
415 if (stat(sp->tpath, &sb) < 0) {
416 warningx(_("unable to stat temporary file (%s), %s unchanged"),
417 sp->tpath, sp->path);
420 if (sb.st_size == 0 && orig_size != 0) {
421 warningx(_("zero length temporary file (%s), %s unchanged"),
422 sp->tpath, sp->path);
427 warningx(_("editor (%s) failed, %s unchanged"), editor, sp->path);
431 /* Set modified bit if use changed the file. */
434 if (orig_size == sb.st_size && timevalcmp(&orig_mtim, &tv, ==)) {
436 * If mtime and size match but the user spent no measurable
437 * time in the editor we can't tell if the file was changed.
439 timevalsub(&tv1, &tv2);
440 if (timevalisset(&tv2))
445 * If modified in this edit session, mark as modified.
448 sp->modified = modified;
450 warningx(_("%s unchanged"), sp->tpath);
454 debug_return_bool(rval);
458 * Parse sudoers after editing and re-edit any ones that caused a parse error.
461 reparse_sudoers(char *editor, char *args, bool strict, bool quiet)
463 struct sudoersfile *sp, *last;
466 debug_decl(reparse_sudoers, SUDO_DEBUG_UTIL)
469 * Parse the edited sudoers files and do sanity checking
471 while ((sp = tq_first(&sudoerslist)) != NULL) {
472 last = tq_last(&sudoerslist);
473 fp = fopen(sp->tpath, "r+");
475 fatalx(_("unable to re-open temporary file (%s), %s unchanged."),
476 sp->tpath, sp->path);
478 /* Clean slate for each parse */
480 init_parser(sp->path, quiet);
482 /* Parse the sudoers temp file(s) */
484 if (sudoersparse() && !parse_error) {
485 warningx(_("unabled to parse temporary file (%s), unknown error"),
488 errorfile = sp->path;
492 if (!check_defaults(SETDEF_ALL, quiet) ||
493 check_aliases(strict, quiet) != 0) {
500 * Got an error, prompt the user for what to do now.
505 parse_error = false; /* ignore parse error */
508 visudo_cleanup(); /* discard changes */
509 debug_return_bool(false);
512 /* Edit file with the parse error */
513 tq_foreach_fwd(&sudoerslist, sp) {
514 if (errorfile == NULL || strcmp(sp->path, errorfile) == 0) {
515 edit_sudoers(sp, editor, args, errorlineno);
516 if (errorfile != NULL)
520 if (errorfile != NULL && sp == NULL) {
521 fatalx(_("internal error, unable to find %s in list!"),
528 /* If any new #include directives were added, edit them too. */
529 for (sp = last->next; sp != NULL; sp = sp->next) {
530 printf(_("press return to edit %s: "), sp->path);
531 while ((ch = getchar()) != EOF && ch != '\n')
533 edit_sudoers(sp, editor, args, errorlineno);
536 /* If all sudoers files parsed OK we are done. */
541 debug_return_bool(true);
545 * Set the owner and mode on a sudoers temp file and
546 * move it into place. Returns true on success, else false.
549 install_sudoers(struct sudoersfile *sp, bool oldperms)
553 debug_decl(install_sudoers, SUDO_DEBUG_UTIL)
557 * No changes but fix owner/mode if needed.
559 (void) unlink(sp->tpath);
560 if (!oldperms && fstat(sp->fd, &sb) != -1) {
561 if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID)
562 ignore_result(chown(sp->path, SUDOERS_UID, SUDOERS_GID));
563 if ((sb.st_mode & 0777) != SUDOERS_MODE)
564 ignore_result(chmod(sp->path, SUDOERS_MODE));
571 * Change mode and ownership of temp file so when
572 * we move it to sp->path things are kosher.
575 /* Use perms of the existing file. */
576 if (fstat(sp->fd, &sb) == -1)
577 fatal(_("unable to stat %s"), sp->path);
578 if (chown(sp->tpath, sb.st_uid, sb.st_gid) != 0) {
579 warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
580 sp->tpath, (unsigned int)sb.st_uid, (unsigned int)sb.st_gid);
582 if (chmod(sp->tpath, sb.st_mode & 0777) != 0) {
583 warning(_("unable to change mode of %s to 0%o"), sp->tpath,
584 (unsigned int)(sb.st_mode & 0777));
587 if (chown(sp->tpath, SUDOERS_UID, SUDOERS_GID) != 0) {
588 warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
589 sp->tpath, SUDOERS_UID, SUDOERS_GID);
592 if (chmod(sp->tpath, SUDOERS_MODE) != 0) {
593 warning(_("unable to change mode of %s to 0%o"), sp->tpath,
600 * Now that sp->tpath is sane (parses ok) it needs to be
601 * rename(2)'d to sp->path. If the rename(2) fails we try using
602 * mv(1) in case sp->tpath and sp->path are on different file systems.
604 if (rename(sp->tpath, sp->path) == 0) {
608 if (errno == EXDEV) {
610 warningx(_("%s and %s not on the same file system, using mv to rename"),
611 sp->tpath, sp->path);
613 /* Build up argument vector for the command */
614 if ((av[0] = strrchr(_PATH_MV, '/')) != NULL)
623 if (run_command(_PATH_MV, av)) {
624 warningx(_("command failed: '%s %s %s', %s unchanged"),
625 _PATH_MV, sp->tpath, sp->path, sp->path);
626 (void) unlink(sp->tpath);
634 warning(_("error renaming %s, %s unchanged"), sp->tpath, sp->path);
635 (void) unlink(sp->tpath);
641 debug_return_bool(rval);
674 group_plugin_query(const char *user, const char *group, const struct passwd *pw)
680 struct interface *get_interfaces(void)
686 * Assuming a parse error occurred, prompt the user for what they want
687 * to do now. Returns the first letter of their choice.
693 debug_decl(whatnow, SUDO_DEBUG_UTIL)
696 (void) fputs(_("What now? "), stdout);
698 for (c = choice; c != '\n' && c != EOF;)
708 debug_return_int(choice);
710 (void) puts(_("Options are:\n"
711 " (e)dit sudoers file again\n"
712 " e(x)it without saving changes to sudoers file\n"
713 " (Q)uit and save changes to sudoers file (DANGER!)\n"));
719 * Install signal handlers for visudo.
725 debug_decl(setup_signals, SUDO_DEBUG_UTIL)
728 * Setup signal handlers to cleanup nicely.
730 zero_bytes(&sa, sizeof(sa));
731 sigemptyset(&sa.sa_mask);
732 sa.sa_flags = SA_RESTART;
733 sa.sa_handler = quit;
734 (void) sigaction(SIGTERM, &sa, NULL);
735 (void) sigaction(SIGHUP, &sa, NULL);
736 (void) sigaction(SIGINT, &sa, NULL);
737 (void) sigaction(SIGQUIT, &sa, NULL);
743 run_command(char *path, char **argv)
747 debug_decl(run_command, SUDO_DEBUG_UTIL)
749 switch (pid = sudo_debug_fork()) {
751 fatal(_("unable to execute %s"), path);
752 break; /* NOTREACHED */
756 closefrom(STDERR_FILENO + 1);
758 warning(_("unable to run %s"), path);
760 break; /* NOTREACHED */
764 rv = waitpid(pid, &status, 0);
765 } while (rv == -1 && errno == EINTR);
768 rv = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
769 debug_return_int(rv);
773 check_owner(const char *path, bool quiet)
777 debug_decl(check_owner, SUDO_DEBUG_UTIL)
779 if (stat(path, &sb) == 0) {
780 if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID) {
784 _("%s: wrong owner (uid, gid) should be (%u, %u)\n"),
785 path, SUDOERS_UID, SUDOERS_GID);
788 if ((sb.st_mode & 07777) != SUDOERS_MODE) {
791 fprintf(stderr, _("%s: bad permissions, should be mode 0%o\n"),
796 debug_return_bool(ok);
800 check_syntax(char *sudoers_path, bool quiet, bool strict, bool oldperms)
803 debug_decl(check_syntax, SUDO_DEBUG_UTIL)
805 if (strcmp(sudoers_path, "-") == 0) {
807 sudoers_path = "stdin";
808 } else if ((sudoersin = fopen(sudoers_path, "r")) == NULL) {
810 warning(_("unable to open %s"), sudoers_path);
813 init_parser(sudoers_path, quiet);
814 if (sudoersparse() && !parse_error) {
816 warningx(_("failed to parse %s file, unknown error"), sudoers_path);
818 errorfile = sudoers_path;
821 if (!check_defaults(SETDEF_ALL, quiet) ||
822 check_aliases(strict, quiet) != 0) {
831 if (errorlineno != -1)
832 (void) printf(_("parse error in %s near line %d\n"),
833 errorfile, errorlineno);
834 else if (errorfile != NULL)
835 (void) printf(_("parse error in %s\n"), errorfile);
838 struct sudoersfile *sp;
840 /* Parsed OK, check mode and owner. */
841 if (oldperms || check_owner(sudoers_path, quiet))
842 (void) printf(_("%s: parsed OK\n"), sudoers_path);
845 tq_foreach_fwd(&sudoerslist, sp) {
846 if (oldperms || check_owner(sp->path, quiet))
847 (void) printf(_("%s: parsed OK\n"), sp->path);
854 debug_return_bool(ok);
858 * Used to open (and lock) the initial sudoers file and to also open
859 * any subsequent files #included via a callback from the parser.
862 open_sudoers(const char *path, bool doedit, bool *keepopen)
864 struct sudoersfile *entry;
867 debug_decl(open_sudoers, SUDO_DEBUG_UTIL)
870 open_flags = O_RDONLY;
872 open_flags = O_RDWR | O_CREAT;
874 /* Check for existing entry */
875 tq_foreach_fwd(&sudoerslist, entry) {
876 if (strcmp(path, entry->path) == 0)
880 entry = ecalloc(1, sizeof(*entry));
881 entry->path = estrdup(path);
882 /* entry->modified = 0; */
884 /* entry->next = NULL; */
885 entry->fd = open(entry->path, open_flags, SUDOERS_MODE);
886 /* entry->tpath = NULL; */
887 entry->doedit = doedit;
888 if (entry->fd == -1) {
889 warning("%s", entry->path);
891 debug_return_ptr(NULL);
893 if (!checkonly && !lock_file(entry->fd, SUDO_TLOCK))
894 fatalx(_("%s busy, try again later"), entry->path);
895 if ((fp = fdopen(entry->fd, "r")) == NULL)
896 fatal("%s", entry->path);
897 tq_append(&sudoerslist, entry);
899 /* Already exists, open .tmp version if there is one. */
900 if (entry->tpath != NULL) {
901 if ((fp = fopen(entry->tpath, "r")) == NULL)
902 fatal("%s", entry->tpath);
904 if ((fp = fdopen(entry->fd, "r")) == NULL)
905 fatal("%s", entry->path);
909 if (keepopen != NULL)
911 debug_return_ptr(fp);
915 get_editor(char **args)
917 char *Editor, *EditorArgs, *EditorPath, *UserEditor, *UserEditorArgs;
918 debug_decl(get_editor, SUDO_DEBUG_UTIL)
921 * Check VISUAL and EDITOR environment variables to see which editor
922 * the user wants to use (we may not end up using it though).
923 * If the path is not fully-qualified, make it so and check that
924 * the specified executable actually exists.
926 UserEditorArgs = NULL;
927 if ((UserEditor = getenv("VISUAL")) == NULL || *UserEditor == '\0')
928 UserEditor = getenv("EDITOR");
929 if (UserEditor && *UserEditor == '\0')
931 else if (UserEditor) {
932 UserEditorArgs = get_args(UserEditor);
933 if (find_path(UserEditor, &Editor, NULL, getenv("PATH"), 0) == FOUND) {
936 if (def_env_editor) {
937 /* If we are honoring $EDITOR this is a fatal error. */
938 fatalx(_("specified editor (%s) doesn't exist"), UserEditor);
940 /* Otherwise, just ignore $EDITOR. */
947 * See if we can use the user's choice of editors either because
948 * we allow any $EDITOR or because $EDITOR is in the allowable list.
950 Editor = EditorArgs = EditorPath = NULL;
951 if (def_env_editor && UserEditor) {
953 EditorArgs = UserEditorArgs;
954 } else if (UserEditor) {
955 struct stat editor_sb;
956 struct stat user_editor_sb;
957 char *base, *userbase;
959 if (stat(UserEditor, &user_editor_sb) != 0) {
960 /* Should never happen since we already checked above. */
961 fatal(_("unable to stat editor (%s)"), UserEditor);
963 EditorPath = estrdup(def_editor);
964 Editor = strtok(EditorPath, ":");
966 EditorArgs = get_args(Editor);
968 * Both Editor and UserEditor should be fully qualified but
971 if ((base = strrchr(Editor, '/')) == NULL)
973 if ((userbase = strrchr(UserEditor, '/')) == NULL) {
980 * We compare the basenames first and then use stat to match
983 if (strcmp(base, userbase) == 0) {
984 if (stat(Editor, &editor_sb) == 0 && S_ISREG(editor_sb.st_mode)
985 && (editor_sb.st_mode & 0000111) &&
986 editor_sb.st_dev == user_editor_sb.st_dev &&
987 editor_sb.st_ino == user_editor_sb.st_ino)
990 } while ((Editor = strtok(NULL, ":")));
994 * Can't use $EDITOR, try each element of def_editor until we
995 * find one that exists, is regular, and is executable.
997 if (Editor == NULL || *Editor == '\0') {
999 EditorPath = estrdup(def_editor);
1000 Editor = strtok(EditorPath, ":");
1002 EditorArgs = get_args(Editor);
1003 if (sudo_goodpath(Editor, NULL))
1005 } while ((Editor = strtok(NULL, ":")));
1007 /* Bleah, none of the editors existed! */
1008 if (Editor == NULL || *Editor == '\0')
1009 fatalx(_("no editor found (editor path = %s)"), def_editor);
1012 debug_return_str(Editor);
1016 * Split out any command line arguments and return them.
1019 get_args(char *cmnd)
1022 debug_decl(get_args, SUDO_DEBUG_UTIL)
1025 while (*args && !isblank((unsigned char) *args))
1029 while (*args && isblank((unsigned char) *args))
1032 debug_return_str(*args ? args : NULL);
1036 * Look up the hostname and set user_host and user_shost.
1041 char *p, thost[HOST_NAME_MAX + 1];
1042 debug_decl(get_hostname, SUDO_DEBUG_UTIL)
1044 if (gethostname(thost, sizeof(thost)) != -1) {
1045 thost[sizeof(thost) - 1] = '\0';
1046 user_host = estrdup(thost);
1048 if ((p = strchr(user_host, '.'))) {
1050 user_shost = estrdup(user_host);
1053 user_shost = user_host;
1056 user_host = user_shost = "localhost";
1062 alias_remove_recursive(char *name, int type)
1067 debug_decl(alias_remove_recursive, SUDO_DEBUG_ALIAS)
1069 if ((a = alias_remove(name, type)) != NULL) {
1070 tq_foreach_fwd(&a->members, m) {
1071 if (m->type == ALIAS) {
1072 if (!alias_remove_recursive(m->name, type))
1076 rbinsert(alias_freelist, a);
1078 debug_return_bool(rval);
1082 check_alias(char *name, int type, int strict, int quiet)
1087 debug_decl(check_alias, SUDO_DEBUG_ALIAS)
1089 if ((a = alias_get(name, type)) != NULL) {
1090 /* check alias contents */
1091 tq_foreach_fwd(&a->members, m) {
1092 if (m->type == ALIAS)
1093 errors += check_alias(m->name, type, strict, quiet);
1099 if (errno == ELOOP) {
1101 _("Error: cycle in %s_Alias `%s'") :
1102 _("Warning: cycle in %s_Alias `%s'");
1105 _("Error: %s_Alias `%s' referenced but not defined") :
1106 _("Warning: %s_Alias `%s' referenced but not defined");
1109 type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
1110 type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
1116 debug_return_int(errors);
1120 * Iterate through the sudoers datastructures looking for undefined
1121 * aliases or unused aliases.
1124 check_aliases(bool strict, bool quiet)
1126 struct cmndspec *cs;
1127 struct member *m, *binding;
1128 struct privilege *priv;
1129 struct userspec *us;
1131 int atype, errors = 0;
1132 debug_decl(check_aliases, SUDO_DEBUG_ALIAS)
1134 alias_freelist = rbcreate(alias_compare);
1136 /* Forward check. */
1137 tq_foreach_fwd(&userspecs, us) {
1138 tq_foreach_fwd(&us->users, m) {
1139 if (m->type == ALIAS) {
1140 errors += check_alias(m->name, USERALIAS, strict, quiet);
1143 tq_foreach_fwd(&us->privileges, priv) {
1144 tq_foreach_fwd(&priv->hostlist, m) {
1145 if (m->type == ALIAS) {
1146 errors += check_alias(m->name, HOSTALIAS, strict, quiet);
1149 tq_foreach_fwd(&priv->cmndlist, cs) {
1150 tq_foreach_fwd(&cs->runasuserlist, m) {
1151 if (m->type == ALIAS) {
1152 errors += check_alias(m->name, RUNASALIAS, strict, quiet);
1155 if ((m = cs->cmnd)->type == ALIAS) {
1156 errors += check_alias(m->name, CMNDALIAS, strict, quiet);
1162 /* Reverse check (destructive) */
1163 tq_foreach_fwd(&userspecs, us) {
1164 tq_foreach_fwd(&us->users, m) {
1165 if (m->type == ALIAS) {
1166 if (!alias_remove_recursive(m->name, USERALIAS))
1170 tq_foreach_fwd(&us->privileges, priv) {
1171 tq_foreach_fwd(&priv->hostlist, m) {
1172 if (m->type == ALIAS) {
1173 if (!alias_remove_recursive(m->name, HOSTALIAS))
1177 tq_foreach_fwd(&priv->cmndlist, cs) {
1178 tq_foreach_fwd(&cs->runasuserlist, m) {
1179 if (m->type == ALIAS) {
1180 if (!alias_remove_recursive(m->name, RUNASALIAS))
1184 if ((m = cs->cmnd)->type == ALIAS) {
1185 if (!alias_remove_recursive(m->name, CMNDALIAS))
1191 tq_foreach_fwd(&defaults, d) {
1199 case DEFAULTS_RUNAS:
1206 continue; /* not an alias */
1208 tq_foreach_fwd(&d->binding, binding) {
1209 for (m = binding; m != NULL; m = m->next) {
1210 if (m->type == ALIAS) {
1211 if (!alias_remove_recursive(m->name, atype))
1217 rbdestroy(alias_freelist, alias_free);
1219 /* If all aliases were referenced we will have an empty tree. */
1220 if (!no_aliases() && !quiet)
1221 alias_apply(print_unused, strict ? "Error" : "Warning");
1223 debug_return_int(strict ? errors : 0);
1227 print_unused(void *v1, void *v2)
1229 struct alias *a = (struct alias *)v1;
1230 char *prefix = (char *)v2;
1232 warningx_nodebug(_("%s: unused %s_Alias %s"), prefix,
1233 a->type == HOSTALIAS ? "Host" : a->type == CMNDALIAS ? "Cmnd" :
1234 a->type == USERALIAS ? "User" : a->type == RUNASALIAS ? "Runas" :
1235 "Unknown", a->name);
1240 * Unlink any sudoers temp files that remain.
1243 visudo_cleanup(void)
1245 struct sudoersfile *sp;
1247 tq_foreach_fwd(&sudoerslist, sp) {
1248 if (sp->tpath != NULL)
1249 (void) unlink(sp->tpath);
1256 * Unlink sudoers temp files (if any) and exit.
1261 struct sudoersfile *sp;
1262 struct iovec iov[4];
1264 tq_foreach_fwd(&sudoerslist, sp) {
1265 if (sp->tpath != NULL)
1266 (void) unlink(sp->tpath);
1269 #define emsg " exiting due to signal: "
1270 iov[0].iov_base = (char *)getprogname();
1271 iov[0].iov_len = strlen(iov[0].iov_base);
1272 iov[1].iov_base = emsg;
1273 iov[1].iov_len = sizeof(emsg) - 1;
1274 iov[2].iov_base = strsignal(signo);
1275 iov[2].iov_len = strlen(iov[2].iov_base);
1276 iov[3].iov_base = "\n";
1278 ignore_result(writev(STDERR_FILENO, iov, 4));
1285 (void) fprintf(fatal ? stderr : stdout,
1286 "usage: %s [-chqsV] [-f sudoers]\n", getprogname());
1294 (void) printf(_("%s - safely edit the sudoers file\n\n"), getprogname());
1296 (void) puts(_("\nOptions:\n"
1297 " -c check-only mode\n"
1298 " -f sudoers specify sudoers file location\n"
1299 " -h display help message and exit\n"
1300 " -q less verbose (quiet) syntax error messages\n"
1301 " -s strict syntax checking\n"
1302 " -V display version information and exit"));