add sudo.postrm and add code to flush /var/lib/sudo on purge
[debian/sudo] / visudo.c
index 81b57185395c428ef107f351504466969ff1ac2f..ab8d58744e258899cf59ee97631d6f2ada935e6d 100644 (file)
--- a/visudo.c
+++ b/visudo.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 1998-2005, 2007-2008
+ * Copyright (c) 1996, 1998-2005, 2007-2010
  *     Todd C. Miller <Todd.Miller@courtesan.com>
  *
  * Permission to use, copy, modify, and distribute this software for any
 #endif /* STDC_HEADERS */
 #ifdef HAVE_STRING_H
 # include <string.h>
-#else
-# ifdef HAVE_STRINGS_H
-#  include <strings.h>
-# endif
 #endif /* HAVE_STRING_H */
+#ifdef HAVE_STRINGS_H
+# include <strings.h>
+#endif /* HAVE_STRINGS_H */
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif /* HAVE_UNISTD_H */
 #else
 # include <varargs.h>
 #endif
-#ifndef HAVE_TIMESPEC
-# include <emul/timespec.h>
-#endif
 
 #include "sudo.h"
 #include "interfaces.h"
 #include "parse.h"
+#include "redblack.h"
 #include <gram.h>
-#include "version.h"
-
-#ifndef lint
-__unused static const char rcsid[] = "$Sudo: visudo.c,v 1.223 2008/11/22 15:12:26 millert Exp $";
-#endif /* lint */
 
 struct sudoersfile {
+    struct sudoersfile *prev, *next;
     char *path;
-    int fd;
     char *tpath;
-    int tfd;
+    int fd;
     int modified;
-    struct sudoersfile *next;
+    int doedit;
 };
+TQ_DECLARE(sudoersfile);
 
 /*
  * Function prototypes
@@ -105,14 +98,17 @@ struct sudoersfile {
 static RETSIGTYPE quit         __P((int));
 static char *get_args          __P((char *));
 static char *get_editor                __P((char **));
+static void get_hostname       __P((void));
 static char whatnow            __P((void));
-static int check_aliases       __P((int));
+static int check_aliases       __P((int, int));
 static int check_syntax                __P((char *, int, int));
 static int edit_sudoers                __P((struct sudoersfile *, char *, char *, int));
 static int install_sudoers     __P((struct sudoersfile *, int));
 static int print_unused                __P((void *, void *));
 static int reparse_sudoers     __P((char *, char *, int, int));
 static int run_command         __P((char *, char **));
+static void print_selfref      __P((char *, int, int, int));
+static void print_undefined    __P((char *, int, int, int));
 static void setup_signals      __P((void));
 static void usage              __P((void)) __attribute__((__noreturn__));
 
@@ -122,6 +118,7 @@ extern void yyrestart               __P((FILE *));
 /*
  * External globals exported by the parser
  */
+extern struct rbtree *aliases;
 extern FILE *yyin;
 extern char *sudoers, *errorfile;
 extern int errorlineno, parse_error;
@@ -138,9 +135,8 @@ int num_interfaces;
 struct interface *interfaces;
 struct sudo_user sudo_user;
 struct passwd *list_pw;
-static struct sudoerslist {
-    struct sudoersfile *first, *last;
-} sudoerslist;
+static struct sudoersfile_list sudoerslist;
+static struct rbtree *alias_freelist;
 
 int
 main(argc, argv)
@@ -167,7 +163,7 @@ main(argc, argv)
     while ((ch = getopt(argc, argv, "Vcf:sq")) != -1) {
        switch (ch) {
            case 'V':
-               (void) printf("%s version %s\n", getprogname(), version);
+               (void) printf("%s version %s\n", getprogname(), PACKAGE_VERSION);
                exit(0);
            case 'c':
                checkonly++;            /* check mode */
@@ -195,9 +191,10 @@ main(argc, argv)
     sudo_setgrent();
 
     /* Mock up a fake sudo_user struct. */
-    user_host = user_shost = user_cmnd = "";
+    user_cmnd = "";
     if ((sudo_user.pw = sudo_getpwuid(getuid())) == NULL)
        errorx(1, "you don't exist in the passwd database");
+    get_hostname();
 
     /* Setup defaults data structures. */
     init_defaults();
@@ -209,8 +206,9 @@ main(argc, argv)
      * Parse the existing sudoers file(s) in quiet mode to highlight any
      * existing errors and to pull in editor and env_editor conf values.
      */
-    if ((yyin = open_sudoers(sudoers_path, NULL)) == NULL)
+    if ((yyin = open_sudoers(sudoers_path, TRUE, NULL)) == NULL) {
        error(1, "%s", sudoers_path);
+    }
     init_parser(sudoers_path, 0);
     yyparse();
     (void) update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER);
@@ -222,6 +220,8 @@ main(argc, argv)
 
     /* Edit the sudoers file(s) */
     tq_foreach_fwd(&sudoerslist, sp) {
+       if (!sp->doedit)
+           continue;
        if (sp != tq_first(&sudoerslist)) {
            printf("press return to edit %s: ", sp->path);
            while ((ch = getchar()) != EOF && ch != '\n')
@@ -261,8 +261,8 @@ edit_sudoers(sp, editor, args, lineno)
     char *cp;                          /* scratch char pointer */
     char buf[PATH_MAX*2];              /* buffer used for copying files */
     char linestr[64];                  /* string version of lineno */
-    struct timespec ts1, ts2;          /* time before and after edit */
-    struct timespec orig_mtim;         /* starting mtime of sudoers file */
+    struct timeval tv, tv1, tv2;       /* time before and after edit */
+    struct timeval orig_mtim;          /* starting mtime of sudoers file */
     off_t orig_size;                   /* starting size of sudoers file */
     ssize_t nread;                     /* number of bytes read */
     struct stat sb;                    /* stat buffer */
@@ -274,8 +274,7 @@ edit_sudoers(sp, editor, args, lineno)
 #endif
        error(1, "can't stat %s", sp->path);
     orig_size = sb.st_size;
-    orig_mtim.tv_sec = mtim_getsec(sb);
-    orig_mtim.tv_nsec = mtim_getnsec(sb);
+    mtim_get(&sb, &orig_mtim);
 
     /* Create the temp file if needed and set timestamp. */
     if (sp->tpath == NULL) {
@@ -341,9 +340,9 @@ edit_sudoers(sp, editor, args, lineno)
      *  XPG4 specifies that vi's exit value is a function of the
      *  number of errors during editing (?!?!).
      */
-    gettime(&ts1);
+    gettime(&tv1);
     if (run_command(editor, av) != -1) {
-       gettime(&ts2);
+       gettime(&tv2);
        /*
         * Sanity checks.
         */
@@ -365,19 +364,14 @@ edit_sudoers(sp, editor, args, lineno)
 
     /* Set modified bit if use changed the file. */
     modified = TRUE;
-    if (orig_size == sb.st_size &&
-       orig_mtim.tv_sec == mtim_getsec(sb) &&
-       orig_mtim.tv_nsec == mtim_getnsec(sb)) {
+    mtim_get(&sb, &tv);
+    if (orig_size == sb.st_size && timevalcmp(&orig_mtim, &tv, ==)) {
        /*
         * If mtime and size match but the user spent no measurable
         * time in the editor we can't tell if the file was changed.
         */
-#ifdef HAVE_TIMESPECSUB2
-       timespecsub(&ts1, &ts2);
-#else
-       timespecsub(&ts1, &ts2, &ts2);
-#endif
-       if (timespecisset(&ts2))
+       timevalsub(&tv1, &tv2);
+       if (timevalisset(&tv2))
            modified = FALSE;
     }
 
@@ -422,14 +416,20 @@ reparse_sudoers(editor, args, strict, quiet)
 
        /* Parse the sudoers temp file */
        yyrestart(fp);
-       if (yyparse() && parse_error != TRUE) {
+       if (yyparse() && !parse_error) {
            warningx("unabled to parse temporary file (%s), unknown error",
                sp->tpath);
            parse_error = TRUE;
+           errorfile = sp->path;
        }
        fclose(yyin);
-       if (check_aliases(strict) != 0)
-           parse_error = TRUE;
+       if (!parse_error) {
+           if (!update_defaults(SETDEF_GENERIC|SETDEF_HOST|SETDEF_USER) ||
+               check_aliases(strict, quiet) != 0) {
+               parse_error = TRUE;
+               errorfile = sp->path;
+           }
+       }
 
        /*
         * Got an error, prompt the user for what to do now
@@ -693,18 +693,27 @@ check_syntax(sudoers_path, quiet, strict)
        exit(1);
     }
     init_parser(sudoers_path, quiet);
-    if (yyparse() && parse_error != TRUE) {
+    if (yyparse() && !parse_error) {
        if (!quiet)
            warningx("failed to parse %s file, unknown error", sudoers_path);
        parse_error = TRUE;
+       errorfile = sudoers_path;
+    }
+    if (!parse_error && check_aliases(strict, quiet) != 0) {
+       parse_error = TRUE;
+       errorfile = sudoers_path;
     }
     error = parse_error;
     if (!quiet) {
-       if (parse_error)
-           (void) printf("parse error in %s near line %d\n", sudoers_path,
-               errorlineno);
-       else
+       if (parse_error) {
+           if (errorlineno != -1)
+               (void) printf("parse error in %s near line %d\n", errorfile,
+                   errorlineno);
+           else
+               (void) printf("parse error in %s\n", errorfile);
+       } else {
            (void) printf("%s: parsed OK\n", sudoers_path);
+       }
     }
     /* Check mode and owner in strict mode. */
 #ifdef HAVE_FSTAT
@@ -737,8 +746,9 @@ check_syntax(sudoers_path, quiet, strict)
  * any subsequent files #included via a callback from the parser.
  */
 FILE *
-open_sudoers(path, keepopen)
+open_sudoers(path, doedit, keepopen)
     const char *path;
+    int doedit;
     int *keepopen;
 {
     struct sudoersfile *entry;
@@ -753,9 +763,11 @@ open_sudoers(path, keepopen)
        entry = emalloc(sizeof(*entry));
        entry->path = estrdup(path);
        entry->modified = 0;
+       entry->prev = entry;
        entry->next = NULL;
        entry->fd = open(entry->path, O_RDWR | O_CREAT, SUDOERS_MODE);
        entry->tpath = NULL;
+       entry->doedit = doedit;
        if (entry->fd == -1) {
            warning("%s", entry->path);
            efree(entry);
@@ -765,15 +777,7 @@ open_sudoers(path, keepopen)
            errorx(1, "%s busy, try again later", entry->path);
        if ((fp = fdopen(entry->fd, "r")) == NULL)
            error(1, "%s", entry->path);
-       /* XXX - macro here? */
-       if (sudoerslist.last == NULL)
-           sudoerslist.first = sudoerslist.last = entry;
-       else {
-           sudoerslist.last->next = entry;
-           sudoerslist.last = entry;
-       }
-       if (keepopen != NULL)
-           *keepopen = TRUE;
+       tq_append(&sudoerslist, entry);
     } else {
        /* Already exists, open .tmp version if there is one. */
        if (entry->tpath != NULL) {
@@ -782,8 +786,11 @@ open_sudoers(path, keepopen)
        } else {
            if ((fp = fdopen(entry->fd, "r")) == NULL)
                error(1, "%s", entry->path);
+           rewind(fp);
        }
     }
+    if (keepopen != NULL)
+       *keepopen = TRUE;
     return(fp);
 }
 
@@ -806,7 +813,7 @@ get_editor(args)
        UserEditor = NULL;
     else if (UserEditor) {
        UserEditorArgs = get_args(UserEditor);
-       if (find_path(UserEditor, &Editor, NULL, getenv("PATH")) == FOUND) {
+       if (find_path(UserEditor, &Editor, NULL, getenv("PATH"), 0) == FOUND) {
            UserEditor = Editor;
        } else {
            if (def_env_editor) {
@@ -908,13 +915,69 @@ get_args(cmnd)
     return(*args ? args : NULL);
 }
 
+/*
+ * Look up the hostname and set user_host and user_shost.
+ */
+static void
+get_hostname()
+{
+    char *p, thost[MAXHOSTNAMELEN + 1];
+
+    if (gethostname(thost, sizeof(thost)) != 0) {
+       user_host = user_shost = "localhost";
+       return;
+    }
+    thost[sizeof(thost) - 1] = '\0';
+    user_host = estrdup(thost);
+
+    if ((p = strchr(user_host, '.'))) {
+       *p = '\0';
+       user_shost = estrdup(user_host);
+       *p = '.';
+    } else {
+       user_shost = user_host;
+    }
+}
+
+static int
+alias_remove_recursive(name, type, strict, quiet)
+    char *name;
+    int type;
+    int strict;
+    int quiet;
+{
+    struct member *m;
+    struct alias *a;
+    int error = 0;
+
+    if ((a = alias_find(name, type)) != NULL) {
+       tq_foreach_fwd(&a->members, m) {
+           if (m->type == ALIAS) {
+               if (strcmp(name, m->name) == 0) {
+                   print_selfref(m->name, type, strict, quiet);
+                   error = 1;
+               } else {
+                   if (!alias_remove_recursive(m->name, type, strict, quiet))
+                       error = 1;
+               }
+           }
+       }
+    }
+    alias_seqno++;
+    a = alias_remove(name, type);
+    if (a)
+       rbinsert(alias_freelist, a);
+    return(error);
+}
+
 /*
  * Iterate through the sudoers datastructures looking for undefined
  * aliases or unused aliases.
  */
 static int
-check_aliases(strict)
+check_aliases(strict, quiet)
     int strict;
+    int quiet;
 {
     struct cmndspec *cs;
     struct member *m, *binding;
@@ -923,14 +986,15 @@ check_aliases(strict)
     struct defaults *d;
     int atype, error = 0;
 
+    alias_freelist = rbcreate(alias_compare);
+
     /* Forward check. */
     tq_foreach_fwd(&userspecs, us) {
        tq_foreach_fwd(&us->users, m) {
            if (m->type == ALIAS) {
                alias_seqno++;
-               if (find_alias(m->name, USERALIAS) == NULL) {
-                   warningx("%s: User_Alias `%s' referenced but not defined",
-                       strict ? "Error" : "Warning", m->name);
+               if (alias_find(m->name, USERALIAS) == NULL) {
+                   print_undefined(m->name, USERALIAS, strict, quiet);
                    error++;
                }
            }
@@ -939,9 +1003,8 @@ check_aliases(strict)
            tq_foreach_fwd(&priv->hostlist, m) {
                if (m->type == ALIAS) {
                    alias_seqno++;
-                   if (find_alias(m->name, HOSTALIAS) == NULL) {
-                       warningx("%s: Host_Alias `%s' referenced but not defined",
-                           strict ? "Error" : "Warning", m->name);
+                   if (alias_find(m->name, HOSTALIAS) == NULL) {
+                       print_undefined(m->name, HOSTALIAS, strict, quiet);
                        error++;
                    }
                }
@@ -950,18 +1013,16 @@ check_aliases(strict)
                tq_foreach_fwd(&cs->runasuserlist, m) {
                    if (m->type == ALIAS) {
                        alias_seqno++;
-                       if (find_alias(m->name, RUNASALIAS) == NULL) {
-                           warningx("%s: Runas_Alias `%s' referenced but not defined",
-                               strict ? "Error" : "Warning", m->name);
+                       if (alias_find(m->name, RUNASALIAS) == NULL) {
+                           print_undefined(m->name, RUNASALIAS, strict, quiet);
                            error++;
                        }
                    }
                }
                if ((m = cs->cmnd)->type == ALIAS) {
                    alias_seqno++;
-                   if (find_alias(m->name, CMNDALIAS) == NULL) {
-                       warningx("%s: Cmnd_Alias `%s' referenced but not defined",
-                           strict ? "Error" : "Warning", m->name);
+                   if (alias_find(m->name, CMNDALIAS) == NULL) {
+                       print_undefined(m->name, CMNDALIAS, strict, quiet);
                        error++;
                    }
                }
@@ -972,21 +1033,29 @@ check_aliases(strict)
     /* Reverse check (destructive) */
     tq_foreach_fwd(&userspecs, us) {
        tq_foreach_fwd(&us->users, m) {
-           if (m->type == ALIAS)
-               (void) alias_remove(m->name, USERALIAS);
+           if (m->type == ALIAS) {
+               if (!alias_remove_recursive(m->name, USERALIAS, strict, quiet))
+                   error++;
+           }
        }
        tq_foreach_fwd(&us->privileges, priv) {
            tq_foreach_fwd(&priv->hostlist, m) {
                if (m->type == ALIAS)
-                   (void) alias_remove(m->name, HOSTALIAS);
+                   if (!alias_remove_recursive(m->name, HOSTALIAS, strict, 
+                       quiet))
+                       error++;
            }
            tq_foreach_fwd(&priv->cmndlist, cs) {
                tq_foreach_fwd(&cs->runasuserlist, m) {
                    if (m->type == ALIAS)
-                       (void) alias_remove(m->name, RUNASALIAS);
+                       if (!alias_remove_recursive(m->name, RUNASALIAS,
+                           strict, quiet))
+                           error++;
                }
                if ((m = cs->cmnd)->type == ALIAS)
-                   (void) alias_remove(m->name, CMNDALIAS);
+                   if (!alias_remove_recursive(m->name, CMNDALIAS, strict,
+                       quiet))
+                       error++;
            }
        }
     }
@@ -1010,16 +1079,50 @@ check_aliases(strict)
        tq_foreach_fwd(&d->binding, binding) {
            for (m = binding; m != NULL; m = m->next) {
                if (m->type == ALIAS)
-                   (void) alias_remove(m->name, atype);
+                   if (!alias_remove_recursive(m->name, atype, strict, quiet))
+                       error++;
            }
        }
     }
+    rbdestroy(alias_freelist, alias_free);
 
     /* If all aliases were referenced we will have an empty tree. */
-    if (no_aliases())
-       return(0);
-    alias_apply(print_unused, strict ? "Error" : "Warning");
-    return (strict ? 1 : 0);
+    if (!no_aliases() && !quiet)
+       alias_apply(print_unused, strict ? "Error" : "Warning");
+
+    return (strict ? error : 0);
+}
+
+static void
+print_undefined(name, type, strict, quiet)
+    char *name;
+    int type;
+    int strict;
+    int quiet;
+{
+    if (!quiet) {
+       warningx("%s: %s_Alias `%s' referenced but not defined",
+           strict ? "Error" : "Warning",
+           type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
+           type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
+           "Unknown", name);
+    }
+}
+
+static void
+print_selfref(name, type, strict, quiet)
+    char *name;
+    int type;
+    int strict;
+    int quiet;
+{
+    if (!quiet) {
+       warningx("%s: %s_Alias `%s' references self",
+           strict ? "Error" : "Warning",
+           type == HOSTALIAS ? "Host" : type == CMNDALIAS ? "Cmnd" :
+           type == USERALIAS ? "User" : type == RUNASALIAS ? "Runas" :
+           "Unknown", name);
+    }
 }
 
 static int