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 = true; /* check mode */
194 sudoers_path = optarg; /* sudoers file path */
201 strict = true; /* strict mode */
204 quiet = false; /* 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, false);
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)
475 if (tq_empty(&sudoerslist))
479 * Parse the edited sudoers files and do sanity checking
482 sp = tq_first(&sudoerslist);
483 last = tq_last(&sudoerslist);
484 fp = fopen(sp->tpath, "r+");
486 errorx(1, _("unable to re-open temporary file (%s), %s unchanged."),
487 sp->tpath, sp->path);
489 /* Clean slate for each parse */
491 init_parser(sp->path, quiet);
493 /* Parse the sudoers temp file */
495 if (yyparse() && !parse_error) {
496 warningx(_("unabled to parse temporary file (%s), unknown error"),
499 errorfile = sp->path;
503 if (!check_defaults(SETDEF_ALL, quiet) ||
504 check_aliases(strict, quiet) != 0) {
511 * Got an error, prompt the user for what to do now
515 case 'Q' : parse_error = false; /* ignore parse error */
517 case 'x' : /* XXX - should return instead of exiting */
519 sudo_debug_exit_int(__func__, __FILE__,
520 __LINE__, sudo_debug_subsys, 0);
526 /* Edit file with the parse error */
527 tq_foreach_fwd(&sudoerslist, sp) {
528 if (errorfile == NULL || strcmp(sp->path, errorfile) == 0) {
529 edit_sudoers(sp, editor, args, errorlineno);
530 if (errorfile != NULL)
534 if (errorfile != NULL && sp == NULL) {
535 errorx(1, _("internal error, unable to find %s in list!"),
540 /* If any new #include directives were added, edit them too. */
541 for (sp = last->next; sp != NULL; sp = sp->next) {
542 printf(_("press return to edit %s: "), sp->path);
543 while ((ch = getchar()) != EOF && ch != '\n')
545 edit_sudoers(sp, editor, args, errorlineno);
547 } while (parse_error);
553 * Set the owner and mode on a sudoers temp file and
554 * move it into place. Returns true on success, else false.
557 install_sudoers(struct sudoersfile *sp, bool oldperms)
561 debug_decl(install_sudoers, SUDO_DEBUG_UTIL)
565 * No changes but fix owner/mode if needed.
567 (void) unlink(sp->tpath);
568 if (!oldperms && fstat(sp->fd, &sb) != -1) {
569 if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID)
570 ignore_result(chown(sp->path, SUDOERS_UID, SUDOERS_GID));
571 if ((sb.st_mode & 0777) != SUDOERS_MODE)
572 ignore_result(chmod(sp->path, SUDOERS_MODE));
579 * Change mode and ownership of temp file so when
580 * we move it to sp->path things are kosher.
583 /* Use perms of the existing file. */
584 if (fstat(sp->fd, &sb) == -1)
585 error(1, _("unable to stat %s"), sp->path);
586 if (chown(sp->tpath, sb.st_uid, sb.st_gid) != 0) {
587 warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
588 sp->tpath, (unsigned int)sb.st_uid, (unsigned int)sb.st_gid);
590 if (chmod(sp->tpath, sb.st_mode & 0777) != 0) {
591 warning(_("unable to change mode of %s to 0%o"), sp->tpath,
592 (unsigned int)(sb.st_mode & 0777));
595 if (chown(sp->tpath, SUDOERS_UID, SUDOERS_GID) != 0) {
596 warning(_("unable to set (uid, gid) of %s to (%u, %u)"),
597 sp->tpath, SUDOERS_UID, SUDOERS_GID);
600 if (chmod(sp->tpath, SUDOERS_MODE) != 0) {
601 warning(_("unable to change mode of %s to 0%o"), sp->tpath,
608 * Now that sp->tpath is sane (parses ok) it needs to be
609 * rename(2)'d to sp->path. If the rename(2) fails we try using
610 * mv(1) in case sp->tpath and sp->path are on different file systems.
612 if (rename(sp->tpath, sp->path) == 0) {
616 if (errno == EXDEV) {
618 warningx(_("%s and %s not on the same file system, using mv to rename"),
619 sp->tpath, sp->path);
621 /* Build up argument vector for the command */
622 if ((av[0] = strrchr(_PATH_MV, '/')) != NULL)
631 if (run_command(_PATH_MV, av)) {
632 warningx(_("command failed: '%s %s %s', %s unchanged"),
633 _PATH_MV, sp->tpath, sp->path, sp->path);
634 (void) unlink(sp->tpath);
642 warning(_("error renaming %s, %s unchanged"), sp->tpath, sp->path);
643 (void) unlink(sp->tpath);
649 debug_return_bool(rval);
689 group_plugin_query(const char *user, const char *group, const struct passwd *pw)
695 * Assuming a parse error occurred, prompt the user for what they want
696 * to do now. Returns the first letter of their choice.
702 debug_decl(whatnow, SUDO_DEBUG_UTIL)
705 (void) fputs(_("What now? "), stdout);
707 for (c = choice; c != '\n' && c != EOF;)
717 debug_return_int(choice);
719 (void) puts(_("Options are:\n"
720 " (e)dit sudoers file again\n"
721 " e(x)it without saving changes to sudoers file\n"
722 " (Q)uit and save changes to sudoers file (DANGER!)\n"));
728 * Install signal handlers for visudo.
734 debug_decl(setup_signals, SUDO_DEBUG_UTIL)
737 * Setup signal handlers to cleanup nicely.
739 zero_bytes(&sa, sizeof(sa));
740 sigemptyset(&sa.sa_mask);
741 sa.sa_flags = SA_RESTART;
742 sa.sa_handler = quit;
743 (void) sigaction(SIGTERM, &sa, NULL);
744 (void) sigaction(SIGHUP, &sa, NULL);
745 (void) sigaction(SIGINT, &sa, NULL);
746 (void) sigaction(SIGQUIT, &sa, NULL);
752 run_command(char *path, char **argv)
756 debug_decl(run_command, SUDO_DEBUG_UTIL)
758 switch (pid = sudo_debug_fork()) {
760 error(1, _("unable to execute %s"), path);
761 break; /* NOTREACHED */
765 closefrom(STDERR_FILENO + 1);
767 warning(_("unable to run %s"), path);
769 break; /* NOTREACHED */
773 rv = waitpid(pid, &status, 0);
774 } while (rv == -1 && errno == EINTR);
777 rv = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
778 debug_return_int(rv);
782 check_owner(const char *path, bool quiet)
786 debug_decl(check_owner, SUDO_DEBUG_UTIL)
788 if (stat(path, &sb) == 0) {
789 if (sb.st_uid != SUDOERS_UID || sb.st_gid != SUDOERS_GID) {
793 _("%s: wrong owner (uid, gid) should be (%u, %u)\n"),
794 path, SUDOERS_UID, SUDOERS_GID);
797 if ((sb.st_mode & 07777) != SUDOERS_MODE) {
800 fprintf(stderr, _("%s: bad permissions, should be mode 0%o\n"),
805 debug_return_bool(ok);
809 check_syntax(char *sudoers_path, bool quiet, bool strict, bool oldperms)
812 debug_decl(check_syntax, SUDO_DEBUG_UTIL)
814 if (strcmp(sudoers_path, "-") == 0) {
816 sudoers_path = "stdin";
817 } else if ((yyin = fopen(sudoers_path, "r")) == NULL) {
819 warning(_("unable to open %s"), sudoers_path);
822 init_parser(sudoers_path, quiet);
823 if (yyparse() && !parse_error) {
825 warningx(_("failed to parse %s file, unknown error"), sudoers_path);
827 errorfile = sudoers_path;
830 if (!check_defaults(SETDEF_ALL, quiet) ||
831 check_aliases(strict, quiet) != 0) {
840 if (errorlineno != -1)
841 (void) printf(_("parse error in %s near line %d\n"),
842 errorfile, errorlineno);
843 else if (errorfile != NULL)
844 (void) printf(_("parse error in %s\n"), errorfile);
847 struct sudoersfile *sp;
849 /* Parsed OK, check mode and owner. */
850 if (oldperms || check_owner(sudoers_path, quiet))
851 (void) printf(_("%s: parsed OK\n"), sudoers_path);
854 tq_foreach_fwd(&sudoerslist, sp) {
855 if (oldperms || check_owner(sp->path, quiet))
856 (void) printf(_("%s: parsed OK\n"), sp->path);
863 debug_return_bool(ok);
867 * Used to open (and lock) the initial sudoers file and to also open
868 * any subsequent files #included via a callback from the parser.
871 open_sudoers(const char *path, bool doedit, bool *keepopen)
873 struct sudoersfile *entry;
876 debug_decl(open_sudoers, SUDO_DEBUG_UTIL)
879 open_flags = O_RDONLY;
881 open_flags = O_RDWR | O_CREAT;
883 /* Check for existing entry */
884 tq_foreach_fwd(&sudoerslist, entry) {
885 if (strcmp(path, entry->path) == 0)
889 entry = ecalloc(1, sizeof(*entry));
890 entry->path = estrdup(path);
891 /* entry->modified = 0; */
893 /* entry->next = NULL; */
894 entry->fd = open(entry->path, open_flags, SUDOERS_MODE);
895 /* entry->tpath = NULL; */
896 entry->doedit = doedit;
897 if (entry->fd == -1) {
898 warning("%s", entry->path);
900 debug_return_ptr(NULL);
902 if (!checkonly && !lock_file(entry->fd, SUDO_TLOCK))
903 errorx(1, _("%s busy, try again later"), entry->path);
904 if ((fp = fdopen(entry->fd, "r")) == NULL)
905 error(1, "%s", entry->path);
906 tq_append(&sudoerslist, entry);
908 /* Already exists, open .tmp version if there is one. */
909 if (entry->tpath != NULL) {
910 if ((fp = fopen(entry->tpath, "r")) == NULL)
911 error(1, "%s", entry->tpath);
913 if ((fp = fdopen(entry->fd, "r")) == NULL)
914 error(1, "%s", entry->path);
918 if (keepopen != NULL)
920 debug_return_ptr(fp);
924 get_editor(char **args)
926 char *Editor, *EditorArgs, *EditorPath, *UserEditor, *UserEditorArgs;
927 debug_decl(get_editor, SUDO_DEBUG_UTIL)
930 * Check VISUAL and EDITOR environment variables to see which editor
931 * the user wants to use (we may not end up using it though).
932 * If the path is not fully-qualified, make it so and check that
933 * the specified executable actually exists.
935 UserEditorArgs = NULL;
936 if ((UserEditor = getenv("VISUAL")) == NULL || *UserEditor == '\0')
937 UserEditor = getenv("EDITOR");
938 if (UserEditor && *UserEditor == '\0')
940 else if (UserEditor) {
941 UserEditorArgs = get_args(UserEditor);
942 if (find_path(UserEditor, &Editor, NULL, getenv("PATH"), 0) == FOUND) {
945 if (def_env_editor) {
946 /* If we are honoring $EDITOR this is a fatal error. */
947 errorx(1, _("specified editor (%s) doesn't exist"), UserEditor);
949 /* Otherwise, just ignore $EDITOR. */
956 * See if we can use the user's choice of editors either because
957 * we allow any $EDITOR or because $EDITOR is in the allowable list.
959 Editor = EditorArgs = EditorPath = NULL;
960 if (def_env_editor && UserEditor) {
962 EditorArgs = UserEditorArgs;
963 } else if (UserEditor) {
964 struct stat editor_sb;
965 struct stat user_editor_sb;
966 char *base, *userbase;
968 if (stat(UserEditor, &user_editor_sb) != 0) {
969 /* Should never happen since we already checked above. */
970 error(1, _("unable to stat editor (%s)"), UserEditor);
972 EditorPath = estrdup(def_editor);
973 Editor = strtok(EditorPath, ":");
975 EditorArgs = get_args(Editor);
977 * Both Editor and UserEditor should be fully qualified but
980 if ((base = strrchr(Editor, '/')) == NULL)
982 if ((userbase = strrchr(UserEditor, '/')) == NULL) {
989 * We compare the basenames first and then use stat to match
992 if (strcmp(base, userbase) == 0) {
993 if (stat(Editor, &editor_sb) == 0 && S_ISREG(editor_sb.st_mode)
994 && (editor_sb.st_mode & 0000111) &&
995 editor_sb.st_dev == user_editor_sb.st_dev &&
996 editor_sb.st_ino == user_editor_sb.st_ino)
999 } while ((Editor = strtok(NULL, ":")));
1003 * Can't use $EDITOR, try each element of def_editor until we
1004 * find one that exists, is regular, and is executable.
1006 if (Editor == NULL || *Editor == '\0') {
1008 EditorPath = estrdup(def_editor);
1009 Editor = strtok(EditorPath, ":");
1011 EditorArgs = get_args(Editor);
1012 if (sudo_goodpath(Editor, NULL))
1014 } while ((Editor = strtok(NULL, ":")));
1016 /* Bleah, none of the editors existed! */
1017 if (Editor == NULL || *Editor == '\0')
1018 errorx(1, _("no editor found (editor path = %s)"), def_editor);
1021 debug_return_str(Editor);
1025 * Split out any command line arguments and return them.
1028 get_args(char *cmnd)
1031 debug_decl(get_args, SUDO_DEBUG_UTIL)
1034 while (*args && !isblank((unsigned char) *args))
1038 while (*args && isblank((unsigned char) *args))
1041 debug_return_str(*args ? args : NULL);
1045 * Look up the hostname and set user_host and user_shost.
1050 char *p, thost[MAXHOSTNAMELEN + 1];
1051 debug_decl(get_hostname, SUDO_DEBUG_UTIL)
1053 if (gethostname(thost, sizeof(thost)) != -1) {
1054 thost[sizeof(thost) - 1] = '\0';
1055 user_host = estrdup(thost);
1057 if ((p = strchr(user_host, '.'))) {
1059 user_shost = estrdup(user_host);
1062 user_shost = user_host;
1065 user_host = user_shost = "localhost";
1071 alias_remove_recursive(char *name, int type)
1076 debug_decl(alias_remove_recursive, SUDO_DEBUG_ALIAS)
1078 if ((a = alias_remove(name, type)) != NULL) {
1079 tq_foreach_fwd(&a->members, m) {
1080 if (m->type == ALIAS) {
1081 if (!alias_remove_recursive(m->name, type))
1085 rbinsert(alias_freelist, a);
1088 debug_return_bool(rval);
1092 check_alias(char *name, int type, int strict, int quiet)
1097 debug_decl(check_alias, SUDO_DEBUG_ALIAS)
1099 if ((a = alias_find(name, type)) != NULL) {
1100 /* check alias contents */
1101 tq_foreach_fwd(&a->members, m) {
1102 if (m->type == ALIAS)
1103 errors += check_alias(m->name, type, strict, quiet);
1108 if (errno == ELOOP) {
1110 _("Error: cycle in %s_Alias `%s'") :
1111 _("Warning: cycle in %s_Alias `%s'");
1114 _("Error: %s_Alias `%s' referenced but not defined") :
1115 _("Warning: %s_Alias `%s' referenced but not defined");
1118 type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
1119 type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
1125 debug_return_int(errors);
1129 * Iterate through the sudoers datastructures looking for undefined
1130 * aliases or unused aliases.
1133 check_aliases(bool strict, bool quiet)
1135 struct cmndspec *cs;
1136 struct member *m, *binding;
1137 struct privilege *priv;
1138 struct userspec *us;
1140 int atype, errors = 0;
1141 debug_decl(check_aliases, SUDO_DEBUG_ALIAS)
1143 alias_freelist = rbcreate(alias_compare);
1145 /* Forward check. */
1146 tq_foreach_fwd(&userspecs, us) {
1147 tq_foreach_fwd(&us->users, m) {
1148 if (m->type == ALIAS) {
1150 errors += check_alias(m->name, USERALIAS, strict, quiet);
1153 tq_foreach_fwd(&us->privileges, priv) {
1154 tq_foreach_fwd(&priv->hostlist, m) {
1155 if (m->type == ALIAS) {
1157 errors += check_alias(m->name, HOSTALIAS, strict, quiet);
1160 tq_foreach_fwd(&priv->cmndlist, cs) {
1161 tq_foreach_fwd(&cs->runasuserlist, m) {
1162 if (m->type == ALIAS) {
1164 errors += check_alias(m->name, RUNASALIAS, strict, quiet);
1167 if ((m = cs->cmnd)->type == ALIAS) {
1169 errors += check_alias(m->name, CMNDALIAS, strict, quiet);
1175 /* Reverse check (destructive) */
1176 tq_foreach_fwd(&userspecs, us) {
1177 tq_foreach_fwd(&us->users, m) {
1178 if (m->type == ALIAS) {
1180 if (!alias_remove_recursive(m->name, USERALIAS))
1184 tq_foreach_fwd(&us->privileges, priv) {
1185 tq_foreach_fwd(&priv->hostlist, m) {
1186 if (m->type == ALIAS) {
1188 if (!alias_remove_recursive(m->name, HOSTALIAS))
1192 tq_foreach_fwd(&priv->cmndlist, cs) {
1193 tq_foreach_fwd(&cs->runasuserlist, m) {
1194 if (m->type == ALIAS) {
1196 if (!alias_remove_recursive(m->name, RUNASALIAS))
1200 if ((m = cs->cmnd)->type == ALIAS) {
1202 if (!alias_remove_recursive(m->name, CMNDALIAS))
1208 tq_foreach_fwd(&defaults, d) {
1216 case DEFAULTS_RUNAS:
1223 continue; /* not an alias */
1225 tq_foreach_fwd(&d->binding, binding) {
1226 for (m = binding; m != NULL; m = m->next) {
1227 if (m->type == ALIAS) {
1229 if (!alias_remove_recursive(m->name, atype))
1235 rbdestroy(alias_freelist, alias_free);
1237 /* If all aliases were referenced we will have an empty tree. */
1238 if (!no_aliases() && !quiet)
1239 alias_apply(print_unused, strict ? "Error" : "Warning");
1241 debug_return_int(strict ? errors : 0);
1245 print_unused(void *v1, void *v2)
1247 struct alias *a = (struct alias *)v1;
1248 char *prefix = (char *)v2;
1250 warningx2(_("%s: unused %s_Alias %s"), prefix,
1251 a->type == HOSTALIAS ? "Host" : a->type == CMNDALIAS ? "Cmnd" :
1252 a->type == USERALIAS ? "User" : a->type == RUNASALIAS ? "Runas" :
1253 "Unknown", a->name);
1258 * Unlink any sudoers temp files that remain.
1261 cleanup(int gotsignal)
1263 struct sudoersfile *sp;
1265 tq_foreach_fwd(&sudoerslist, sp) {
1266 if (sp->tpath != NULL)
1267 (void) unlink(sp->tpath);
1276 * Unlink sudoers temp files (if any) and exit.
1281 const char *signame, *myname;
1284 #define emsg " exiting due to signal: "
1285 myname = getprogname();
1286 signame = strsignal(signo);
1287 ignore_result(write(STDERR_FILENO, myname, strlen(myname)));
1288 ignore_result(write(STDERR_FILENO, emsg, sizeof(emsg) - 1));
1289 ignore_result(write(STDERR_FILENO, signame, strlen(signame)));
1290 ignore_result(write(STDERR_FILENO, "\n", 1));
1297 (void) fprintf(fatal ? stderr : stdout,
1298 "usage: %s [-chqsV] [-f sudoers]\n", getprogname());
1306 (void) printf(_("%s - safely edit the sudoers file\n\n"), getprogname());
1308 (void) puts(_("\nOptions:\n"
1309 " -c check-only mode\n"
1310 " -f sudoers specify sudoers file location\n"
1311 " -h display help message and exit\n"
1312 " -q less verbose (quiet) syntax error messages\n"
1313 " -s strict syntax checking\n"
1314 " -V display version information and exit"));
1319 visudo_printf(int msg_type, const char *fmt, ...)
1325 case SUDO_CONV_INFO_MSG:
1328 case SUDO_CONV_ERROR_MSG:
1337 vfprintf(fp, fmt, ap);