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 */
210 /* There should be no other command line arguments. */
211 if (argc - optind != 0)
217 /* Mock up a fake sudo_user struct. */
219 if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL)
220 errorx(1, _("you do not exist in the %s database"), "passwd");
223 /* Setup defaults data structures. */
227 exitcode = check_syntax(sudoers_path, quiet, strict, oldperms) ? 0 : 1;
232 * Parse the existing sudoers file(s) in quiet mode to highlight any
233 * existing errors and to pull in editor and env_editor conf values.
235 if ((yyin = open_sudoers(sudoers_path, true, NULL)) == NULL) {
236 error(1, "%s", sudoers_path);
238 init_parser(sudoers_path, 0);
240 (void) update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER);
242 editor = get_editor(&args);
244 /* Install signal handlers to clean up temp files if we are killed. */
247 /* Edit the sudoers file(s) */
248 tq_foreach_fwd(&sudoerslist, sp) {
251 if (sp != tq_first(&sudoerslist)) {
252 printf(_("press return to edit %s: "), sp->path);
253 while ((ch = getchar()) != EOF && ch != '\n')
256 edit_sudoers(sp, editor, args, -1);
259 /* Check edited files for a parse error and re-edit any that fail. */
260 reparse_sudoers(editor, args, strict, quiet);
262 /* Install the sudoers temp files as needed. */
263 tq_foreach_fwd(&sudoerslist, sp) {
264 (void) install_sudoers(sp, oldperms);
268 sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, exitcode);
273 * List of editors that support the "+lineno" command line syntax.
274 * If an entry starts with '*' the tail end of the string is matched.
275 * No other wild cards are supported.
277 static char *lineno_editors[] = {
297 * Edit each sudoers file.
298 * Returns true on success, else false.
301 edit_sudoers(struct sudoersfile *sp, char *editor, char *args, int lineno)
303 int tfd; /* sudoers temp file descriptor */
304 bool modified; /* was the file modified? */
305 int ac; /* argument count */
306 char **av; /* argument vector for run_command */
307 char *cp; /* scratch char pointer */
308 char buf[PATH_MAX*2]; /* buffer used for copying files */
309 char linestr[64]; /* string version of lineno */
310 struct timeval tv, tv1, tv2; /* time before and after edit */
311 struct timeval orig_mtim; /* starting mtime of sudoers file */
312 off_t orig_size; /* starting size of sudoers file */
313 ssize_t nread; /* number of bytes read */
314 struct stat sb; /* stat buffer */
315 bool rval = false; /* return value */
316 debug_decl(edit_sudoers, SUDO_DEBUG_UTIL)
318 if (fstat(sp->fd, &sb) == -1)
319 error(1, _("unable to stat %s"), sp->path);
320 orig_size = sb.st_size;
321 mtim_get(&sb, &orig_mtim);
323 /* Create the temp file if needed and set timestamp. */
324 if (sp->tpath == NULL) {
325 easprintf(&sp->tpath, "%s.tmp", sp->path);
326 tfd = open(sp->tpath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
328 error(1, "%s", sp->tpath);
330 /* Copy sp->path -> sp->tpath and reset the mtime. */
331 if (orig_size != 0) {
332 (void) lseek(sp->fd, (off_t)0, SEEK_SET);
333 while ((nread = read(sp->fd, buf, sizeof(buf))) > 0)
334 if (write(tfd, buf, nread) != nread)
335 error(1, _("write error"));
337 /* Add missing newline at EOF if needed. */
338 if (nread > 0 && buf[nread - 1] != '\n') {
340 if (write(tfd, buf, 1) != 1)
341 error(1, _("write error"));
346 (void) touch(-1, sp->tpath, &orig_mtim);
348 /* Does the editor support +lineno? */
351 char *editor_base = strrchr(editor, '/');
352 if (editor_base != NULL)
355 editor_base = editor;
356 if (*editor_base == 'r')
359 for (av = lineno_editors; (cp = *av) != NULL; av++) {
360 /* We only handle a leading '*' wildcard. */
362 size_t blen = strlen(editor_base);
363 size_t clen = strlen(++cp);
365 if (strcmp(cp, editor_base + blen - clen) == 0)
368 } else if (strcmp(cp, editor_base) == 0)
371 /* Disable +lineno if editor doesn't support it. */
376 /* Find the length of the argument vector */
377 ac = 3 + (lineno > 0);
382 for (wasblank = false, cp = args; *cp; cp++) {
383 if (isblank((unsigned char) *cp))
392 /* Build up argument vector for the command */
393 av = emalloc2(ac, sizeof(char *));
394 if ((av[0] = strrchr(editor, '/')) != NULL)
400 (void) snprintf(linestr, sizeof(linestr), "+%d", lineno);
404 for ((cp = strtok(args, " \t")); cp; (cp = strtok(NULL, " \t")))
407 av[ac++] = sp->tpath;
412 * We cannot check the editor's exit value against 0 since
413 * XPG4 specifies that vi's exit value is a function of the
414 * number of errors during editing (?!?!).
416 gettimeofday(&tv1, NULL);
417 if (run_command(editor, av) != -1) {
418 gettimeofday(&tv2, NULL);
422 if (stat(sp->tpath, &sb) < 0) {
423 warningx(_("unable to stat temporary file (%s), %s unchanged"),
424 sp->tpath, sp->path);
427 if (sb.st_size == 0 && orig_size != 0) {
428 warningx(_("zero length temporary file (%s), %s unchanged"),
429 sp->tpath, sp->path);
434 warningx(_("editor (%s) failed, %s unchanged"), editor, sp->path);
438 /* Set modified bit if use changed the file. */
441 if (orig_size == sb.st_size && timevalcmp(&orig_mtim, &tv, ==)) {
443 * If mtime and size match but the user spent no measurable
444 * time in the editor we can't tell if the file was changed.
446 timevalsub(&tv1, &tv2);
447 if (timevalisset(&tv2))
452 * If modified in this edit session, mark as modified.
455 sp->modified = modified;
457 warningx(_("%s unchanged"), sp->tpath);
461 debug_return_bool(rval);
465 * Parse sudoers after editing and re-edit any ones that caused a parse error.
468 reparse_sudoers(char *editor, char *args, bool strict, bool quiet)
470 struct sudoersfile *sp, *last;
473 debug_decl(reparse_sudoers, SUDO_DEBUG_UTIL)
476 * Parse the edited sudoers files and do sanity checking
479 sp = tq_first(&sudoerslist);
480 last = tq_last(&sudoerslist);
481 fp = fopen(sp->tpath, "r+");
483 errorx(1, _("unable to re-open temporary file (%s), %s unchanged."),
484 sp->tpath, sp->path);
486 /* Clean slate for each parse */
488 init_parser(sp->path, quiet);
490 /* Parse the sudoers temp file */
492 if (yyparse() && !parse_error) {
493 warningx(_("unabled to parse temporary file (%s), unknown error"),
496 errorfile = sp->path;
500 if (!update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER) ||
501 check_aliases(strict, quiet) != 0) {
503 errorfile = sp->path;
508 * Got an error, prompt the user for what to do now
512 case 'Q' : parse_error = false; /* ignore parse error */
514 case 'x' : /* XXX - should return instead of exiting */
516 sudo_debug_exit_int(__func__, __FILE__,
517 __LINE__, sudo_debug_subsys, 0);
523 /* Edit file with the parse error */
524 tq_foreach_fwd(&sudoerslist, sp) {
525 if (errorfile == NULL || strcmp(sp->path, errorfile) == 0) {
526 edit_sudoers(sp, editor, args, errorlineno);
531 errorx(1, _("internal error, unable to find %s in list!"),
536 /* If any new #include directives were added, edit them too. */
537 for (sp = last->next; sp != NULL; sp = sp->next) {
538 printf(_("press return to edit %s: "), sp->path);
539 while ((ch = getchar()) != EOF && ch != '\n')
541 edit_sudoers(sp, editor, args, errorlineno);
543 } while (parse_error);
549 * Set the owner and mode on a sudoers temp file and
550 * move it into place. Returns true on success, else false.
553 install_sudoers(struct sudoersfile *sp, bool oldperms)
557 debug_decl(install_sudoers, SUDO_DEBUG_UTIL)
561 * No changes but fix owner/mode if needed.
563 (void) unlink(sp->tpath);
564 if (!oldperms && fstat(sp->fd, &sb) != -1) {
565 if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID)
566 ignore_result(chown(sp->path, SUDOERS_UID, SUDOERS_GID));
567 if ((sb.st_mode & 0777) != SUDOERS_MODE)
568 ignore_result(chmod(sp->path, SUDOERS_MODE));
575 * Change mode and ownership of temp file so when
576 * we move it to sp->path things are kosher.
579 /* Use perms of the existing file. */
580 if (fstat(sp->fd, &sb) == -1)
581 error(1, _("unable to stat %s"), sp->path);
582 if (chown(sp->tpath, sb.st_uid, sb.st_gid) != 0) {
583 warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
584 sp->tpath, (unsigned int)sb.st_uid, (unsigned int)sb.st_gid);
586 if (chmod(sp->tpath, sb.st_mode & 0777) != 0) {
587 warning(_("unable to change mode of %s to 0%o"), sp->tpath,
588 (unsigned int)(sb.st_mode & 0777));
591 if (chown(sp->tpath, SUDOERS_UID, SUDOERS_GID) != 0) {
592 warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
593 sp->tpath, SUDOERS_UID, SUDOERS_GID);
596 if (chmod(sp->tpath, SUDOERS_MODE) != 0) {
597 warning(_("unable to change mode of %s to 0%o"), sp->tpath,
604 * Now that sp->tpath is sane (parses ok) it needs to be
605 * rename(2)'d to sp->path. If the rename(2) fails we try using
606 * mv(1) in case sp->tpath and sp->path are on different file systems.
608 if (rename(sp->tpath, sp->path) == 0) {
612 if (errno == EXDEV) {
614 warningx(_("%s and %s not on the same file system, using mv to rename"),
615 sp->tpath, sp->path);
617 /* Build up argument vector for the command */
618 if ((av[0] = strrchr(_PATH_MV, '/')) != NULL)
627 if (run_command(_PATH_MV, av)) {
628 warningx(_("command failed: '%s %s %s', %s unchanged"),
629 _PATH_MV, sp->tpath, sp->path, sp->path);
630 (void) unlink(sp->tpath);
638 warning(_("error renaming %s, %s unchanged"), sp->tpath, sp->path);
639 (void) unlink(sp->tpath);
645 debug_return_bool(rval);
685 group_plugin_query(const char *user, const char *group, const struct passwd *pw)
691 * Assuming a parse error occurred, prompt the user for what they want
692 * to do now. Returns the first letter of their choice.
698 debug_decl(whatnow, SUDO_DEBUG_UTIL)
701 (void) fputs(_("What now? "), stdout);
703 for (c = choice; c != '\n' && c != EOF;)
713 debug_return_int(choice);
715 (void) puts(_("Options are:\n"
716 " (e)dit sudoers file again\n"
717 " e(x)it without saving changes to sudoers file\n"
718 " (Q)uit and save changes to sudoers file (DANGER!)\n"));
724 * Install signal handlers for visudo.
730 debug_decl(setup_signals, SUDO_DEBUG_UTIL)
733 * Setup signal handlers to cleanup nicely.
735 zero_bytes(&sa, sizeof(sa));
736 sigemptyset(&sa.sa_mask);
737 sa.sa_flags = SA_RESTART;
738 sa.sa_handler = quit;
739 (void) sigaction(SIGTERM, &sa, NULL);
740 (void) sigaction(SIGHUP, &sa, NULL);
741 (void) sigaction(SIGINT, &sa, NULL);
742 (void) sigaction(SIGQUIT, &sa, NULL);
748 run_command(char *path, char **argv)
752 debug_decl(run_command, SUDO_DEBUG_UTIL)
754 switch (pid = sudo_debug_fork()) {
756 error(1, _("unable to execute %s"), path);
757 break; /* NOTREACHED */
761 closefrom(STDERR_FILENO + 1);
763 warning(_("unable to run %s"), path);
765 break; /* NOTREACHED */
769 rv = waitpid(pid, &status, 0);
770 } while (rv == -1 && errno == EINTR);
773 rv = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
774 debug_return_int(rv);
778 check_owner(const char *path, bool quiet)
782 debug_decl(check_owner, SUDO_DEBUG_UTIL)
784 if (stat(path, &sb) == 0) {
785 if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID) {
789 _("%s: wrong owner (uid, gid) should be (%u, %u)\n"),
790 path, SUDOERS_UID, SUDOERS_GID);
793 if ((sb.st_mode & 07777) != SUDOERS_MODE) {
796 fprintf(stderr, _("%s: bad permissions, should be mode 0%o\n"),
801 debug_return_bool(ok);
805 check_syntax(char *sudoers_path, bool quiet, bool strict, bool oldperms)
808 debug_decl(check_syntax, SUDO_DEBUG_UTIL)
810 if (strcmp(sudoers_path, "-") == 0) {
812 sudoers_path = "stdin";
813 } else if ((yyin = fopen(sudoers_path, "r")) == NULL) {
815 warning(_("unable to open %s"), sudoers_path);
818 init_parser(sudoers_path, quiet);
819 if (yyparse() && !parse_error) {
821 warningx(_("failed to parse %s file, unknown error"), sudoers_path);
823 errorfile = sudoers_path;
825 if (!parse_error && check_aliases(strict, quiet) != 0) {
827 errorfile = sudoers_path;
833 if (errorlineno != -1)
834 (void) printf(_("parse error in %s near line %d\n"),
835 errorfile, errorlineno);
837 (void) printf(_("parse error in %s\n"), errorfile);
840 struct sudoersfile *sp;
842 /* Parsed OK, check mode and owner. */
843 if (oldperms || check_owner(sudoers_path, quiet))
844 (void) printf(_("%s: parsed OK\n"), sudoers_path);
847 tq_foreach_fwd(&sudoerslist, sp) {
848 if (oldperms || check_owner(sp->path, quiet))
849 (void) printf(_("%s: parsed OK\n"), sp->path);
856 debug_return_bool(ok);
860 * Used to open (and lock) the initial sudoers file and to also open
861 * any subsequent files #included via a callback from the parser.
864 open_sudoers(const char *path, bool doedit, bool *keepopen)
866 struct sudoersfile *entry;
869 debug_decl(open_sudoers, SUDO_DEBUG_UTIL)
872 open_flags = O_RDONLY;
874 open_flags = O_RDWR | O_CREAT;
876 /* Check for existing entry */
877 tq_foreach_fwd(&sudoerslist, entry) {
878 if (strcmp(path, entry->path) == 0)
882 entry = ecalloc(1, sizeof(*entry));
883 entry->path = estrdup(path);
884 /* entry->modified = 0; */
886 /* entry->next = NULL; */
887 entry->fd = open(entry->path, open_flags, SUDOERS_MODE);
888 /* entry->tpath = NULL; */
889 entry->doedit = doedit;
890 if (entry->fd == -1) {
891 warning("%s", entry->path);
893 debug_return_ptr(NULL);
895 if (!checkonly && !lock_file(entry->fd, SUDO_TLOCK))
896 errorx(1, _("%s busy, try again later"), entry->path);
897 if ((fp = fdopen(entry->fd, "r")) == NULL)
898 error(1, "%s", entry->path);
899 tq_append(&sudoerslist, entry);
901 /* Already exists, open .tmp version if there is one. */
902 if (entry->tpath != NULL) {
903 if ((fp = fopen(entry->tpath, "r")) == NULL)
904 error(1, "%s", entry->tpath);
906 if ((fp = fdopen(entry->fd, "r")) == NULL)
907 error(1, "%s", entry->path);
911 if (keepopen != NULL)
913 debug_return_ptr(fp);
917 get_editor(char **args)
919 char *Editor, *EditorArgs, *EditorPath, *UserEditor, *UserEditorArgs;
920 debug_decl(get_editor, SUDO_DEBUG_UTIL)
923 * Check VISUAL and EDITOR environment variables to see which editor
924 * the user wants to use (we may not end up using it though).
925 * If the path is not fully-qualified, make it so and check that
926 * the specified executable actually exists.
928 UserEditorArgs = NULL;
929 if ((UserEditor = getenv("VISUAL")) == NULL || *UserEditor == '\0')
930 UserEditor = getenv("EDITOR");
931 if (UserEditor && *UserEditor == '\0')
933 else if (UserEditor) {
934 UserEditorArgs = get_args(UserEditor);
935 if (find_path(UserEditor, &Editor, NULL, getenv("PATH"), 0) == FOUND) {
938 if (def_env_editor) {
939 /* If we are honoring $EDITOR this is a fatal error. */
940 errorx(1, _("specified editor (%s) doesn't exist"), UserEditor);
942 /* Otherwise, just ignore $EDITOR. */
949 * See if we can use the user's choice of editors either because
950 * we allow any $EDITOR or because $EDITOR is in the allowable list.
952 Editor = EditorArgs = EditorPath = NULL;
953 if (def_env_editor && UserEditor) {
955 EditorArgs = UserEditorArgs;
956 } else if (UserEditor) {
957 struct stat editor_sb;
958 struct stat user_editor_sb;
959 char *base, *userbase;
961 if (stat(UserEditor, &user_editor_sb) != 0) {
962 /* Should never happen since we already checked above. */
963 error(1, _("unable to stat editor (%s)"), UserEditor);
965 EditorPath = estrdup(def_editor);
966 Editor = strtok(EditorPath, ":");
968 EditorArgs = get_args(Editor);
970 * Both Editor and UserEditor should be fully qualified but
973 if ((base = strrchr(Editor, '/')) == NULL)
975 if ((userbase = strrchr(UserEditor, '/')) == NULL) {
982 * We compare the basenames first and then use stat to match
985 if (strcmp(base, userbase) == 0) {
986 if (stat(Editor, &editor_sb) == 0 && S_ISREG(editor_sb.st_mode)
987 && (editor_sb.st_mode & 0000111) &&
988 editor_sb.st_dev == user_editor_sb.st_dev &&
989 editor_sb.st_ino == user_editor_sb.st_ino)
992 } while ((Editor = strtok(NULL, ":")));
996 * Can't use $EDITOR, try each element of def_editor until we
997 * find one that exists, is regular, and is executable.
999 if (Editor == NULL || *Editor == '\0') {
1001 EditorPath = estrdup(def_editor);
1002 Editor = strtok(EditorPath, ":");
1004 EditorArgs = get_args(Editor);
1005 if (sudo_goodpath(Editor, NULL))
1007 } while ((Editor = strtok(NULL, ":")));
1009 /* Bleah, none of the editors existed! */
1010 if (Editor == NULL || *Editor == '\0')
1011 errorx(1, _("no editor found (editor path = %s)"), def_editor);
1014 debug_return_str(Editor);
1018 * Split out any command line arguments and return them.
1021 get_args(char *cmnd)
1024 debug_decl(get_args, SUDO_DEBUG_UTIL)
1027 while (*args && !isblank((unsigned char) *args))
1031 while (*args && isblank((unsigned char) *args))
1034 debug_return_str(*args ? args : NULL);
1038 * Look up the hostname and set user_host and user_shost.
1043 char *p, thost[MAXHOSTNAMELEN + 1];
1044 debug_decl(get_hostname, SUDO_DEBUG_UTIL)
1046 if (gethostname(thost, sizeof(thost)) != -1) {
1047 thost[sizeof(thost) - 1] = '\0';
1048 user_host = estrdup(thost);
1050 if ((p = strchr(user_host, '.'))) {
1052 user_shost = estrdup(user_host);
1055 user_shost = user_host;
1058 user_host = user_shost = "localhost";
1064 alias_remove_recursive(char *name, int type)
1069 debug_decl(alias_remove_recursive, SUDO_DEBUG_ALIAS)
1071 if ((a = alias_find(name, type)) != NULL) {
1072 tq_foreach_fwd(&a->members, m) {
1073 if (m->type == ALIAS) {
1074 if (!alias_remove_recursive(m->name, type))
1080 a = alias_remove(name, type);
1082 rbinsert(alias_freelist, a);
1083 debug_return_bool(rval);
1087 check_alias(char *name, int type, int strict, int quiet)
1092 debug_decl(check_alias, SUDO_DEBUG_ALIAS)
1094 if ((a = alias_find(name, type)) != NULL) {
1095 /* check alias contents */
1096 tq_foreach_fwd(&a->members, m) {
1097 if (m->type == ALIAS)
1098 errors += check_alias(m->name, type, strict, quiet);
1103 if (errno == ELOOP) {
1105 _("Error: cycle in %s_Alias `%s'") :
1106 _("Warning: cycle in %s_Alias `%s'");
1109 _("Error: %s_Alias `%s' referenced but not defined") :
1110 _("Warning: %s_Alias `%s' referenced but not defined");
1113 type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
1114 type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
1120 debug_return_int(errors);
1124 * Iterate through the sudoers datastructures looking for undefined
1125 * aliases or unused aliases.
1128 check_aliases(bool strict, bool quiet)
1130 struct cmndspec *cs;
1131 struct member *m, *binding;
1132 struct privilege *priv;
1133 struct userspec *us;
1135 int atype, errors = 0;
1136 debug_decl(check_aliases, SUDO_DEBUG_ALIAS)
1138 alias_freelist = rbcreate(alias_compare);
1140 /* Forward check. */
1141 tq_foreach_fwd(&userspecs, us) {
1142 tq_foreach_fwd(&us->users, m) {
1143 if (m->type == ALIAS) {
1145 errors += check_alias(m->name, USERALIAS, strict, quiet);
1148 tq_foreach_fwd(&us->privileges, priv) {
1149 tq_foreach_fwd(&priv->hostlist, m) {
1150 if (m->type == ALIAS) {
1152 errors += check_alias(m->name, HOSTALIAS, strict, quiet);
1155 tq_foreach_fwd(&priv->cmndlist, cs) {
1156 tq_foreach_fwd(&cs->runasuserlist, m) {
1157 if (m->type == ALIAS) {
1159 errors += check_alias(m->name, RUNASALIAS, strict, quiet);
1162 if ((m = cs->cmnd)->type == ALIAS) {
1164 errors += check_alias(m->name, CMNDALIAS, strict, quiet);
1170 /* Reverse check (destructive) */
1171 tq_foreach_fwd(&userspecs, us) {
1172 tq_foreach_fwd(&us->users, m) {
1173 if (m->type == ALIAS) {
1175 if (!alias_remove_recursive(m->name, USERALIAS))
1179 tq_foreach_fwd(&us->privileges, priv) {
1180 tq_foreach_fwd(&priv->hostlist, m) {
1181 if (m->type == ALIAS) {
1183 if (!alias_remove_recursive(m->name, HOSTALIAS))
1187 tq_foreach_fwd(&priv->cmndlist, cs) {
1188 tq_foreach_fwd(&cs->runasuserlist, m) {
1189 if (m->type == ALIAS) {
1191 if (!alias_remove_recursive(m->name, RUNASALIAS))
1195 if ((m = cs->cmnd)->type == ALIAS) {
1197 if (!alias_remove_recursive(m->name, CMNDALIAS))
1203 tq_foreach_fwd(&defaults, d) {
1211 case DEFAULTS_RUNAS:
1218 continue; /* not an alias */
1220 tq_foreach_fwd(&d->binding, binding) {
1221 for (m = binding; m != NULL; m = m->next) {
1222 if (m->type == ALIAS) {
1224 if (!alias_remove_recursive(m->name, atype))
1230 rbdestroy(alias_freelist, alias_free);
1232 /* If all aliases were referenced we will have an empty tree. */
1233 if (!no_aliases() && !quiet)
1234 alias_apply(print_unused, strict ? "Error" : "Warning");
1236 debug_return_int(strict ? errors : 0);
1240 print_unused(void *v1, void *v2)
1242 struct alias *a = (struct alias *)v1;
1243 char *prefix = (char *)v2;
1245 warningx2(_("%s: unused %s_Alias %s"), prefix,
1246 a->type == HOSTALIAS ? "Host" : a->type == CMNDALIAS ? "Cmnd" :
1247 a->type == USERALIAS ? "User" : a->type == RUNASALIAS ? "Runas" :
1248 "Unknown", a->name);
1253 * Unlink any sudoers temp files that remain.
1256 cleanup(int gotsignal)
1258 struct sudoersfile *sp;
1260 tq_foreach_fwd(&sudoerslist, sp) {
1261 if (sp->tpath != NULL)
1262 (void) unlink(sp->tpath);
1271 * Unlink sudoers temp files (if any) and exit.
1276 const char *signame, *myname;
1279 #define emsg " exiting due to signal: "
1280 myname = getprogname();
1281 signame = strsignal(signo);
1282 ignore_result(write(STDERR_FILENO, myname, strlen(myname)));
1283 ignore_result(write(STDERR_FILENO, emsg, sizeof(emsg) - 1));
1284 ignore_result(write(STDERR_FILENO, signame, strlen(signame)));
1285 ignore_result(write(STDERR_FILENO, "\n", 1));
1292 (void) fprintf(fatal ? stderr : stdout,
1293 "usage: %s [-chqsV] [-f sudoers]\n", getprogname());
1301 (void) printf(_("%s - safely edit the sudoers file\n\n"), getprogname());
1303 (void) puts(_("\nOptions:\n"
1304 " -c check-only mode\n"
1305 " -f sudoers specify sudoers file location\n"
1306 " -h display help message and exit\n"
1307 " -q less verbose (quiet) syntax error messages\n"
1308 " -s strict syntax checking\n"
1309 " -V display version information and exit"));
1314 visudo_printf(int msg_type, const char *fmt, ...)
1320 case SUDO_CONV_INFO_MSG:
1323 case SUDO_CONV_ERROR_MSG:
1332 vfprintf(fp, fmt, ap);