]> granicus.if.org Git - shadow/blobdiff - src/chage.c
* src/newusers.c: Fix typo.
[shadow] / src / chage.c
index c299ff9eeb1b1ad3fd1fc1bbfa7f99016e193185..c5e8b469c42fb6d3eb662ab61b84a60d40ddccd1 100644 (file)
@@ -1,5 +1,8 @@
 /*
- * Copyright 1989 - 1994, Julianne Frances Haugh
+ * Copyright (c) 1989 - 1994, Julianne Frances Haugh
+ * Copyright (c) 1996 - 2000, Marek Michałkiewicz
+ * Copyright (c) 2000 - 2006, Tomasz Kłoczko
+ * Copyright (c) 2007 - 2011, Nicolas François
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Julianne F. Haugh nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
+ * 3. The name of the copyright holders or contributors may not be used to
+ *    endorse or promote products derived from this software without
+ *    specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY JULIE HAUGH AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL JULIE HAUGH OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+ * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT
+ * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
 #include <config.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <time.h>
+#ifdef ACCT_TOOLS_SETUID
 #ifdef USE_PAM
 #include "pam_defs.h"
 #endif                         /* USE_PAM */
+#endif                         /* ACCT_TOOLS_SETUID */
 #include <pwd.h>
 #ifdef WITH_SELINUX
 #include <selinux/selinux.h>
 #include <selinux/av_permissions.h>
 #endif
-#include "exitcodes.h"
 #include "prototypes.h"
 #include "defines.h"
 #include "pwio.h"
 #include "shadowio.h"
+#ifdef WITH_TCB
+#include "tcbfuncs.h"
+#endif
+/*@-exitarg@*/
+#include "exitcodes.h"
+
 /*
  * Global variables
  */
-static char *Prog;
-
-static int
- dflg = 0,                     /* set last password change date */
-    Eflg = 0,                  /* set account expiration date */
-    Iflg = 0,                  /* set password inactive after expiration */
-    lflg = 0,                  /* show account aging information */
-    mflg = 0,                  /* set minimum number of days before password change */
-    Mflg = 0,                  /* set maximim number of days before password change */
-    Wflg = 0;                  /* set expiration warning days */
-static int amroot = 0;
+const char *Prog;
+
+static bool
+    dflg = false,              /* set last password change date */
+    Eflg = false,              /* set account expiration date */
+    Iflg = false,              /* set password inactive after expiration */
+    lflg = false,              /* show account aging information */
+    mflg = false,              /* set minimum number of days before password change */
+    Mflg = false,              /* set maximum number of days before password change */
+    Wflg = false;              /* set expiration warning days */
+static bool amroot = false;
+
+static bool pw_locked  = false;        /* Indicate if the password file is locked */
+static bool spw_locked = false;        /* Indicate if the shadow file is locked */
+/* The name and UID of the user being worked on */
+static char user_name[BUFSIZ] = "";
+static uid_t user_uid = -1;
 
 static long mindays;
 static long maxdays;
-static long lastday;
+static long lstchgdate;
 static long warndays;
 static long inactdays;
-static long expdays;
-
-#define        EPOCH           "1969-12-31"
+static long expdate;
 
 /* local function prototypes */
-static void usage (void);
-static void date_to_str (char *, size_t, time_t);
+static void usage (int status);
+static void date_to_str (char *buf, size_t maxsize, time_t date);
 static int new_fields (void);
-static void print_date (time_t);
+static void print_date (time_t date);
 static void list_fields (void);
 static void process_flags (int argc, char **argv);
 static void check_flags (int argc, int opt_index);
 static void check_perms (void);
-static void open_files (int readonly);
+static void open_files (bool readonly);
 static void close_files (void);
+static void fail_exit (int code);
 
 /*
- * isnum - determine whether or not a string is a number
+ * fail_exit - do some cleanup and exit with the given error code
  */
-int isnum (const char *s)
+static void fail_exit (int code)
 {
-       while ('\0' != *s) {
-               if (!isdigit (*s)) {
-                       return 0;
+       if (spw_locked) {
+               if (spw_unlock () == 0) {
+                       fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, spw_dbname ());
+                       SYSLOG ((LOG_ERR, "failed to unlock %s", spw_dbname ()));
+                       /* continue */
                }
-               s++;
        }
-       return 1;
+       if (pw_locked) {
+               if (pw_unlock () == 0) {
+                       fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, pw_dbname ());
+                       SYSLOG ((LOG_ERR, "failed to unlock %s", pw_dbname ()));
+                       /* continue */
+               }
+       }
+       closelog ();
+
+#ifdef WITH_AUDIT
+       if (E_SUCCESS != code) {
+               audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
+                             "change age",
+                             user_name, (unsigned int) user_uid, 0);
+       }
+#endif
+
+       exit (code);
 }
 
 /*
  * usage - print command line syntax and exit
  */
-static void usage (void)
+static void usage (int status)
 {
-       fprintf (stderr, _("Usage: chage [options] [LOGIN]\n"
-                          "\n"
-                          "Options:\n"
-                          "  -d, --lastday LAST_DAY        set last password change to LAST_DAY\n"
-                          "  -E, --expiredate EXPIRE_DATE  set account expiration date to EXPIRE_DATE\n"
-                          "  -h, --help                    display this help message and exit\n"
-                          "  -I, --inactive INACTIVE       set password inactive after expiration\n"
-                          "                                to INACTIVE\n"
-                          "  -l, --list                    show account aging information\n"
-                          "  -m, --mindays MIN_DAYS        set minimum number of days before password\n"
-                          "                                change to MIN_DAYS\n"
-                          "  -M, --maxdays MAX_DAYS        set maximim number of days before password\n"
-                          "                                change to MAX_DAYS\n"
-                          "  -W, --warndays WARN_DAYS      set expiration warning days to WARN_DAYS\n"
-                          "\n"));
-       exit (E_USAGE);
+       fputs (_("Usage: chage [options] LOGIN\n"
+                "\n"
+                "Options:\n"
+                "  -d, --lastday LAST_DAY        set date of last password change to LAST_DAY\n"
+                "  -E, --expiredate EXPIRE_DATE  set account expiration date to EXPIRE_DATE\n"
+                "  -h, --help                    display this help message and exit\n"
+                "  -I, --inactive INACTIVE       set password inactive after expiration\n"
+                "                                to INACTIVE\n"
+                "  -l, --list                    show account aging information\n"
+                "  -m, --mindays MIN_DAYS        set minimum number of days before password\n"
+                "                                change to MIN_DAYS\n"
+                "  -M, --maxdays MAX_DAYS        set maximim number of days before password\n"
+                "                                change to MAX_DAYS\n"
+                "  -W, --warndays WARN_DAYS      set expiration warning days to WARN_DAYS\n"
+                "\n"), (E_SUCCESS != status) ? stderr : stdout);
+       exit (status);
 }
 
 static void date_to_str (char *buf, size_t maxsize, time_t date)
@@ -131,10 +164,10 @@ static void date_to_str (char *buf, size_t maxsize, time_t date)
 
        tp = gmtime (&date);
 #ifdef HAVE_STRFTIME
-       strftime (buf, maxsize, "%Y-%m-%d", tp);
+       (void) strftime (buf, maxsize, "%Y-%m-%d", tp);
 #else
-       snprintf (buf, maxsize, "%04d-%02d-%02d",
-                 tp->tm_year + 1900, tp->tm_mon + 1, tp->tm_mday);
+       (void) snprintf (buf, maxsize, "%04d-%02d-%02d",
+                        tp->tm_year + 1900, tp->tm_mon + 1, tp->tm_mday);
 #endif                         /* HAVE_STRFTIME */
 }
 
@@ -150,58 +183,71 @@ static void date_to_str (char *buf, size_t maxsize, time_t date)
 static int new_fields (void)
 {
        char buf[200];
-       char *cp;
 
-       printf (_("Enter the new value, or press ENTER for the default\n"));
-       printf ("\n");
+       (void) puts (_("Enter the new value, or press ENTER for the default"));
+       (void) puts ("");
 
        snprintf (buf, sizeof buf, "%ld", mindays);
        change_field (buf, sizeof buf, _("Minimum Password Age"));
-       if (((mindays = strtol (buf, &cp, 10)) == 0 && ('\0' != *cp))
+       if (   (getlong (buf, &mindays) == 0)
            || (mindays < -1)) {
                return 0;
        }
 
        snprintf (buf, sizeof buf, "%ld", maxdays);
        change_field (buf, sizeof buf, _("Maximum Password Age"));
-       if (((maxdays = strtol (buf, &cp, 10)) == 0 && ('\0' != *cp))
+       if (   (getlong (buf, &maxdays) == 0)
            || (maxdays < -1)) {
                return 0;
        }
 
-       date_to_str (buf, sizeof buf, lastday * SCALE);
+       if (-1 == lstchgdate) {
+               strcpy (buf, "-1");
+       } else {
+               date_to_str (buf, sizeof buf, lstchgdate * SCALE);
+       }
 
        change_field (buf, sizeof buf, _("Last Password Change (YYYY-MM-DD)"));
 
-       if (strcmp (buf, EPOCH) == 0) {
-               lastday = -1;
-       } else if ((lastday = strtoday (buf)) == -1) {
-               return 0;
+       if (strcmp (buf, "-1") == 0) {
+               lstchgdate = -1;
+       } else {
+               lstchgdate = strtoday (buf);
+               if (lstchgdate <= -1) {
+                       return 0;
+               }
        }
 
        snprintf (buf, sizeof buf, "%ld", warndays);
        change_field (buf, sizeof buf, _("Password Expiration Warning"));
-       if (((warndays = strtol (buf, &cp, 10)) == 0 && ('\0' != *cp))
+       if (   (getlong (buf, &warndays) == 0)
            || (warndays < -1)) {
                return 0;
        }
 
        snprintf (buf, sizeof buf, "%ld", inactdays);
        change_field (buf, sizeof buf, _("Password Inactive"));
-       if (((inactdays = strtol (buf, &cp, 10)) == 0 && ('\0' != *cp))
+       if (   (getlong (buf, &inactdays) == 0)
            || (inactdays < -1)) {
                return 0;
        }
 
-       date_to_str (buf, sizeof buf, expdays * SCALE);
+       if (-1 == expdate) {
+               strcpy (buf, "-1");
+       } else {
+               date_to_str (buf, sizeof buf, expdate * SCALE);
+       }
 
        change_field (buf, sizeof buf,
                      _("Account Expiration Date (YYYY-MM-DD)"));
 
-       if (strcmp (buf, EPOCH) == 0) {
-               expdays = -1;
-       } else if ((expdays = strtoday (buf)) == -1) {
-               return 0;
+       if (strcmp (buf, "-1") == 0) {
+               expdate = -1;
+       } else {
+               expdate = strtoday (buf);
+               if (expdate <= -1) {
+                       return 0;
+               }
        }
 
        return 1;
@@ -214,15 +260,25 @@ static void print_date (time_t date)
        char buf[80];
 
        tp = gmtime (&date);
-       strftime (buf, sizeof buf, "%b %d, %Y", tp);
-       puts (buf);
+       if (NULL == tp) {
+               (void) printf ("time_t: %lu\n", date);
+       } else {
+               (void) strftime (buf, sizeof buf, "%b %d, %Y", tp);
+               (void) puts (buf);
+       }
 #else
        struct tm *tp;
-       char *cp;
+       char *cp = NULL;
 
        tp = gmtime (&date);
-       cp = asctime (tp);
-       printf ("%6.6s, %4.4s\n", cp + 4, cp + 20);
+       if (NULL != tp) {
+               cp = asctime (tp);
+       }
+       if (NULL != cp) {
+               (void) printf ("%6.6s, %4.4s\n", cp + 4, cp + 20);
+       } else {
+               (void) printf ("time_t: %lu\n", date);
+       }
 #endif
 }
 
@@ -242,27 +298,30 @@ static void list_fields (void)
         * The "last change" date is either "never" or the date the password
         * was last modified. The date is the number of days since 1/1/1970.
         */
-       printf (_("Last password change\t\t\t\t\t: "));
-       if (lastday < 0) {
-               printf (_("never\n"));
-       } else if (lastday == 0) {
-               printf (_("password must be changed\n"));
+       (void) fputs (_("Last password change\t\t\t\t\t: "), stdout);
+       if (lstchgdate < 0) {
+               (void) puts (_("never"));
+       } else if (lstchgdate == 0) {
+               (void) puts (_("password must be changed"));
        } else {
-               changed = lastday * SCALE;
-               print_date (changed);
+               changed = lstchgdate * SCALE;
+               print_date ((time_t) changed);
        }
 
        /*
         * The password expiration date is determined from the last change
         * date plus the number of days the password is valid for.
         */
-       printf (_("Password expires\t\t\t\t\t: "));
-       if ((lastday <= 0) || (maxdays >= (10000 * (DAY / SCALE)))
-           || (maxdays < 0)) {
-               printf (_("never\n"));
+       (void) fputs (_("Password expires\t\t\t\t\t: "), stdout);
+       if (lstchgdate == 0) {
+               (void) puts (_("password must be changed"));
+       } else if (   (lstchgdate < 0)
+                  || (maxdays >= (10000 * (DAY / SCALE)))
+                  || (maxdays < 0)) {
+               (void) puts (_("never"));
        } else {
                expires = changed + maxdays * SCALE;
-               print_date (expires);
+               print_date ((time_t) expires);
        }
 
        /*
@@ -271,25 +330,29 @@ static void list_fields (void)
         * number of inactive days is added. The resulting date is when the
         * active will be disabled.
         */
-       printf (_("Password inactive\t\t\t\t\t: "));
-       if ((lastday <= 0) || (inactdays < 0) ||
-           (maxdays >= (10000 * (DAY / SCALE))) || (maxdays < 0)) {
-               printf (_("never\n"));
+       (void) fputs (_("Password inactive\t\t\t\t\t: "), stdout);
+       if (lstchgdate == 0) {
+               (void) puts (_("password must be changed"));
+       } else if (   (lstchgdate < 0)
+                  || (inactdays < 0)
+                  || (maxdays >= (10000 * (DAY / SCALE)))
+                  || (maxdays < 0)) {
+               (void) puts (_("never"));
        } else {
                expires = changed + (maxdays + inactdays) * SCALE;
-               print_date (expires);
+               print_date ((time_t) expires);
        }
 
        /*
         * The account will expire on the given date regardless of the
         * password expiring or not.
         */
-       printf (_("Account expires\t\t\t\t\t\t: "));
-       if (expdays < 0) {
-               printf (_("never\n"));
+       (void) fputs (_("Account expires\t\t\t\t\t\t: "), stdout);
+       if (expdate < 0) {
+               (void) puts (_("never"));
        } else {
-               expires = expdays * SCALE;
-               print_date (expires);
+               expires = expdate * SCALE;
+               print_date ((time_t) expires);
        }
 
        /*
@@ -307,6 +370,11 @@ static void list_fields (void)
                warndays);
 }
 
+/*
+ * process_flags - parse the command line options
+ *
+ *     It will not return if an error is encountered.
+ */
 static void process_flags (int argc, char **argv)
 {
        /*
@@ -331,80 +399,126 @@ static void process_flags (int argc, char **argv)
                             &option_index)) != -1) {
                switch (c) {
                case 'd':
-                       dflg++;
-                       if (!isnum (optarg)) {
-                               lastday = strtoday (optarg);
-                       } else {
-                               lastday = strtol (optarg, 0, 10);
+                       dflg = true;
+                       lstchgdate = strtoday (optarg);
+                       if (lstchgdate < -1) {
+                               fprintf (stderr,
+                                        _("%s: invalid date '%s'\n"),
+                                        Prog, optarg);
+                               usage (E_USAGE);
                        }
                        break;
                case 'E':
-                       Eflg++;
-                       if (!isnum (optarg)) {
-                               expdays = strtoday (optarg);
-                       } else {
-                               expdays = strtol (optarg, 0, 10);
+                       Eflg = true;
+                       expdate = strtoday (optarg);
+                       if (expdate < -1) {
+                               fprintf (stderr,
+                                        _("%s: invalid date '%s'\n"),
+                                        Prog, optarg);
+                               usage (E_USAGE);
                        }
                        break;
                case 'h':
-                       usage ();
+                       usage (E_SUCCESS);
                        break;
                case 'I':
-                       Iflg++;
-                       inactdays = strtol (optarg, 0, 10);
+                       Iflg = true;
+                       if (   (getlong (optarg, &inactdays) == 0)
+                           || (inactdays < -1)) {
+                               fprintf (stderr,
+                                        _("%s: invalid numeric argument '%s'\n"),
+                                        Prog, optarg);
+                               usage (E_USAGE);
+                       }
                        break;
                case 'l':
-                       lflg++;
+                       lflg = true;
                        break;
                case 'm':
-                       mflg++;
-                       mindays = strtol (optarg, 0, 10);
+                       mflg = true;
+                       if (   (getlong (optarg, &mindays) == 0)
+                           || (mindays < -1)) {
+                               fprintf (stderr,
+                                        _("%s: invalid numeric argument '%s'\n"),
+                                        Prog, optarg);
+                               usage (E_USAGE);
+                       }
                        break;
                case 'M':
-                       Mflg++;
-                       maxdays = strtol (optarg, 0, 10);
+                       Mflg = true;
+                       if (   (getlong (optarg, &maxdays) == 0)
+                           || (maxdays < -1)) {
+                               fprintf (stderr,
+                                        _("%s: invalid numeric argument '%s'\n"),
+                                        Prog, optarg);
+                               usage (E_USAGE);
+                       }
                        break;
                case 'W':
-                       Wflg++;
-                       warndays = strtol (optarg, 0, 10);
+                       Wflg = true;
+                       if (   (getlong (optarg, &warndays) == 0)
+                           || (warndays < -1)) {
+                               fprintf (stderr,
+                                        _("%s: invalid numeric argument '%s'\n"),
+                                        Prog, optarg);
+                               usage (E_USAGE);
+                       }
                        break;
                default:
-                       usage ();
+                       usage (E_USAGE);
                }
        }
 
        check_flags (argc, optind);
 }
 
-
+/*
+ * check_flags - check flags and parameters consistency
+ *
+ *     It will not return if an error is encountered.
+ */
 static void check_flags (int argc, int opt_index)
 {
-
        /*
         * Make certain the flags do not conflict and that there is a user
         * name on the command line.
         */
 
        if (argc != opt_index + 1) {
-               usage ();
+               usage (E_USAGE);
        }
 
        if (lflg && (mflg || Mflg || dflg || Wflg || Iflg || Eflg)) {
                fprintf (stderr,
                         _("%s: do not include \"l\" with other flags\n"),
                         Prog);
-               usage ();
+               usage (E_USAGE);
        }
 }
 
-/* Additional check done later */
+/*
+ * check_perms - check if the caller is allowed to add a group
+ *
+ *     Non-root users are only allowed to display their aging information.
+ *     (we will later make sure that the user is only listing her aging
+ *     information)
+ *
+ *     With PAM support, the setuid bit can be set on chage to allow
+ *     non-root users to groups.
+ *     Without PAM support, only users who can write in the group databases
+ *     can add groups.
+ *
+ *     It will not return if the user is not allowed.
+ */
 static void check_perms (void)
 {
+#ifdef ACCT_TOOLS_SETUID
 #ifdef USE_PAM
        pam_handle_t *pamh = NULL;
        struct passwd *pampw;
        int retval;
-#endif
+#endif                         /* USE_PAM */
+#endif                         /* ACCT_TOOLS_SETUID */
 
        /*
         * An unprivileged user can ask for their own aging information, but
@@ -414,58 +528,66 @@ static void check_perms (void)
 
        if (!amroot && !lflg) {
                fprintf (stderr, _("%s: Permission denied.\n"), Prog);
-#ifdef WITH_AUDIT
-               audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "change age", NULL,
-                             getuid (), 0);
-#endif
-               exit (E_NOPERM);
+               fail_exit (E_NOPERM);
        }
 
+#ifdef ACCT_TOOLS_SETUID
 #ifdef USE_PAM
-       retval = PAM_SUCCESS;
-
        pampw = getpwuid (getuid ()); /* local, no need for xgetpwuid */
-       if (pampw == NULL) {
-               retval = PAM_USER_UNKNOWN;
+       if (NULL == pampw) {
+               fprintf (stderr,
+                        _("%s: Cannot determine your user name.\n"),
+                        Prog);
+               exit (E_NOPERM);
        }
 
-       if (retval == PAM_SUCCESS) {
-               retval = pam_start ("chage", pampw->pw_name, &conv, &pamh);
-       }
+       retval = pam_start ("chage", pampw->pw_name, &conv, &pamh);
 
-       if (retval == PAM_SUCCESS) {
+       if (PAM_SUCCESS == retval) {
                retval = pam_authenticate (pamh, 0);
-               if (retval != PAM_SUCCESS) {
-                       pam_end (pamh, retval);
-               }
        }
 
-       if (retval == PAM_SUCCESS) {
+       if (PAM_SUCCESS == retval) {
                retval = pam_acct_mgmt (pamh, 0);
-               if (retval != PAM_SUCCESS) {
-                       pam_end (pamh, retval);
-               }
        }
 
-       if (retval != PAM_SUCCESS) {
+       if (NULL != pamh) {
+               (void) pam_end (pamh, retval);
+       }
+       if (PAM_SUCCESS != retval) {
                fprintf (stderr, _("%s: PAM authentication failed\n"), Prog);
-               exit (E_NOPERM);
+               fail_exit (E_NOPERM);
        }
 #endif                         /* USE_PAM */
+#endif                         /* ACCT_TOOLS_SETUID */
 }
 
-static void open_files (int readonly)
+/*
+ * open_files - open the shadow database
+ *
+ *     In read-only mode, the databases are not locked and are opened
+ *     only for reading.
+ */
+static void open_files (bool readonly)
 {
        /*
-        * open the password file. This loads all of the password
+        * Lock and open the password file. This loads all of the password
         * file entries into memory. Then we get a pointer to the password
         * file entry for the requested user.
         */
-       if (pw_open (O_RDONLY) == 0) {
-               fprintf (stderr, _("%s: can't open password file\n"), Prog);
-               SYSLOG ((LOG_ERR, "failed opening %s", PASSWD_FILE));
-               closelog ();
-               exit (E_NOPERM);
+       if (!readonly) {
+               if (pw_lock () == 0) {
+                       fprintf (stderr,
+                                _("%s: cannot lock %s; try again later.\n"),
+                                Prog, pw_dbname ());
+                       fail_exit (E_NOPERM);
+               }
+               pw_locked = true;
+       }
+       if (pw_open (readonly ? O_RDONLY: O_RDWR) == 0) {
+               fprintf (stderr, _("%s: cannot open %s\n"), Prog, pw_dbname ());
+               SYSLOG ((LOG_WARN, "cannot open %s", pw_dbname ()));
+               fail_exit (E_NOPERM);
        }
 
        /*
@@ -474,31 +596,26 @@ static void open_files (int readonly)
         * does not have to exist in this case; a new entry will be created
         * for this user if one does not exist already.
         */
-       if (!readonly && (spw_lock () == 0)) {
-               fprintf (stderr,
-                        _("%s: can't lock shadow password file\n"), Prog);
-               SYSLOG ((LOG_ERR, "failed locking %s", SHADOW_FILE));
-               closelog ();
-#ifdef WITH_AUDIT
-               audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "change age", name,
-                             getuid (), 0);
-#endif
-               exit (E_NOPERM);
+       if (!readonly) {
+               if (spw_lock () == 0) {
+                       fprintf (stderr,
+                                _("%s: cannot lock %s; try again later.\n"),
+                                Prog, spw_dbname ());
+                       fail_exit (E_NOPERM);
+               }
+               spw_locked = true;
        }
        if (spw_open (readonly ? O_RDONLY: O_RDWR) == 0) {
                fprintf (stderr,
-                        _("%s: can't open shadow password file\n"), Prog);
-               spw_unlock ();
-               SYSLOG ((LOG_ERR, "failed opening %s", SHADOW_FILE));
-               closelog ();
-#ifdef WITH_AUDIT
-               audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "change age", name,
-                             getuid (), 0);
-#endif
-               exit (E_NOPERM);
+                        _("%s: cannot open %s\n"), Prog, spw_dbname ());
+               SYSLOG ((LOG_WARN, "cannot open %s", spw_dbname ()));
+               fail_exit (E_NOPERM);
        }
 }
 
+/*
+ * close_files - close and unlock the password/shadow databases
+ */
 static void close_files (void)
 {
        /*
@@ -507,15 +624,9 @@ static void close_files (void)
         */
        if (spw_close () == 0) {
                fprintf (stderr,
-                        _("%s: can't rewrite shadow password file\n"), Prog);
-               spw_unlock ();
-               SYSLOG ((LOG_ERR, "failed rewriting %s", SHADOW_FILE));
-               closelog ();
-#ifdef WITH_AUDIT
-               audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "change age",
-                             pw->pw_name, getuid (), 0);
-#endif
-               exit (E_NOPERM);
+                        _("%s: failure while writing changes to %s\n"), Prog, spw_dbname ());
+               SYSLOG ((LOG_ERR, "failure while writing changes to %s", spw_dbname ()));
+               fail_exit (E_NOPERM);
        }
 
        /*
@@ -523,17 +634,130 @@ static void close_files (void)
         * will be re-written.
         */
        if (pw_close () == 0) {
-               fprintf (stderr, _("%s: can't rewrite password file\n"), Prog);
-               spw_unlock ();
-               SYSLOG ((LOG_ERR, "failed rewriting %s", PASSWD_FILE));
-               closelog ();
-#ifdef WITH_AUDIT
-               audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "change age",
-                             pw->pw_name, getuid (), 0);
-#endif
-               exit (E_NOPERM);
+               fprintf (stderr, _("%s: failure while writing changes to %s\n"), Prog, pw_dbname ());
+               SYSLOG ((LOG_ERR, "failure while writing changes to %s", pw_dbname ()));
+               fail_exit (E_NOPERM);
+       }
+       if (spw_unlock () == 0) {
+               fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, spw_dbname ());
+               SYSLOG ((LOG_ERR, "failed to unlock %s", spw_dbname ()));
+               /* continue */
+       }
+       spw_locked = false;
+       if (pw_unlock () == 0) {
+               fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, pw_dbname ());
+               SYSLOG ((LOG_ERR, "failed to unlock %s", pw_dbname ()));
+               /* continue */
+       }
+       pw_locked = false;
+}
+
+/*
+ * update_age - update the aging information in the database
+ *
+ *     It will not return in case of error
+ */
+static void update_age (const struct spwd *sp, const struct passwd *pw)
+{
+       struct spwd spwent;
+
+       /*
+        * There was no shadow entry. The new entry will have the encrypted
+        * password transferred from the normal password file along with the
+        * aging information.
+        */
+       if (NULL == sp) {
+               struct passwd pwent = *pw;
+
+               memzero (&spwent, sizeof spwent);
+               spwent.sp_namp = xstrdup (pw->pw_name);
+               spwent.sp_pwdp = xstrdup (pw->pw_passwd);
+               spwent.sp_flag = SHADOW_SP_FLAG_UNSET;
+
+               pwent.pw_passwd = SHADOW_PASSWD_STRING; /* XXX warning: const */
+               if (pw_update (&pwent) == 0) {
+                       fprintf (stderr,
+                                _("%s: failed to prepare the new %s entry '%s'\n"), Prog, pw_dbname (), pwent.pw_name);
+                       fail_exit (E_NOPERM);
+               }
+       } else {
+               spwent.sp_namp = xstrdup (sp->sp_namp);
+               spwent.sp_pwdp = xstrdup (sp->sp_pwdp);
+               spwent.sp_flag = sp->sp_flag;
+       }
+
+       /*
+        * Copy the fields back to the shadow file entry and write the
+        * modified entry back to the shadow file. Closing the shadow and
+        * password files will commit any changes that have been made.
+        */
+       spwent.sp_max = maxdays;
+       spwent.sp_min = mindays;
+       spwent.sp_lstchg = lstchgdate;
+       spwent.sp_warn = warndays;
+       spwent.sp_inact = inactdays;
+       spwent.sp_expire = expdate;
+
+       if (spw_update (&spwent) == 0) {
+               fprintf (stderr,
+                        _("%s: failed to prepare the new %s entry '%s'\n"), Prog, spw_dbname (), spwent.sp_namp);
+               fail_exit (E_NOPERM);
+       }
+
+}
+
+/*
+ * get_defaults - get the value of the fields not set from the command line
+ */
+static void get_defaults (const struct spwd *sp)
+{
+       /*
+        * Set the fields that aren't being set from the command line from
+        * the password file.
+        */
+       if (NULL != sp) {
+               if (!Mflg) {
+                       maxdays = sp->sp_max;
+               }
+               if (!mflg) {
+                       mindays = sp->sp_min;
+               }
+               if (!dflg) {
+                       lstchgdate = sp->sp_lstchg;
+               }
+               if (!Wflg) {
+                       warndays = sp->sp_warn;
+               }
+               if (!Iflg) {
+                       inactdays = sp->sp_inact;
+               }
+               if (!Eflg) {
+                       expdate = sp->sp_expire;
+               }
+       } else {
+               /*
+                * Use default values that will not change the behavior of the
+                * account.
+                */
+               if (!Mflg) {
+                       maxdays = -1;
+               }
+               if (!mflg) {
+                       mindays = -1;
+               }
+               if (!dflg) {
+                       lstchgdate = -1;
+               }
+               if (!Wflg) {
+                       warndays = -1;
+               }
+               if (!Iflg) {
+                       inactdays = -1;
+               }
+               if (!Eflg) {
+                       expdate = -1;
+               }
        }
-       spw_unlock ();
 }
 
 /*
@@ -560,20 +784,17 @@ static void close_files (void)
 int main (int argc, char **argv)
 {
        const struct spwd *sp;
-       struct spwd spwent;
        uid_t ruid;
        gid_t rgid;
        const struct passwd *pw;
-       struct passwd pwent;
-       char name[BUFSIZ];
 
 #ifdef WITH_AUDIT
        audit_help_open ();
 #endif
        sanitize_env ();
-       setlocale (LC_ALL, "");
-       bindtextdomain (PACKAGE, LOCALEDIR);
-       textdomain (PACKAGE);
+       (void) setlocale (LC_ALL, "");
+       (void) bindtextdomain (PACKAGE, LOCALEDIR);
+       (void) textdomain (PACKAGE);
 
        ruid = getuid ();
        rgid = getgid ();
@@ -599,118 +820,55 @@ int main (int argc, char **argv)
                fprintf (stderr,
                         _("%s: the shadow password file is not present\n"),
                         Prog);
-               SYSLOG ((LOG_ERR, "can't find the shadow password file"));
+               SYSLOG ((LOG_WARN, "can't find the shadow password file"));
                closelog ();
                exit (E_SHADOW_NOTFOUND);
        }
 
        open_files (lflg);
-
-       if (!(pw = pw_locate (argv[optind]))) {
-               fprintf (stderr, _("%s: unknown user %s\n"), Prog,
-                        argv[optind]);
-               closelog ();
-               exit (E_NOPERM);
-       }
-
-       pwent = *pw;
-       STRFCPY (name, pwent.pw_name);
-
        /* Drop privileges */
-       if (lflg && (setregid (rgid, rgid) || setreuid (ruid, ruid))) {
+       if (lflg && (   (setregid (rgid, rgid) != 0)
+                    || (setreuid (ruid, ruid) != 0))) {
                fprintf (stderr, _("%s: failed to drop privileges (%s)\n"),
                         Prog, strerror (errno));
-#ifdef WITH_AUDIT
-               audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "change age", name,
-                             getuid (), 0);
-#endif
-               exit (E_NOPERM);
+               fail_exit (E_NOPERM);
        }
 
-       sp = spw_locate (argv[optind]);
-
-       /*
-        * Set the fields that aren't being set from the command line from
-        * the password file.
-        */
-       if (NULL != sp) {
-               spwent = *sp;
+       pw = pw_locate (argv[optind]);
+       if (NULL == pw) {
+               fprintf (stderr, _("%s: user '%s' does not exist in %s\n"),
+                        Prog, argv[optind], pw_dbname ());
+               closelog ();
+               fail_exit (E_NOPERM);
+       }
 
-               if (!Mflg) {
-                       maxdays = spwent.sp_max;
-               }
-               if (!mflg) {
-                       mindays = spwent.sp_min;
-               }
-               if (!dflg) {
-                       lastday = spwent.sp_lstchg;
-               }
-               if (!Wflg) {
-                       warndays = spwent.sp_warn;
-               }
-               if (!Iflg) {
-                       inactdays = spwent.sp_inact;
-               }
-               if (!Eflg) {
-                       expdays = spwent.sp_expire;
-               }
-#ifdef WITH_AUDIT
-               if (Mflg) {
-                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
-                                     "change max age", pw->pw_name, pw->pw_uid,
-                                     1);
-               }
-               if (mflg) {
-                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
-                                     "change min age", pw->pw_name, pw->pw_uid,
-                                     1);
-               }
-               if (dflg) {
-                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
-                                     "change last change date", pw->pw_name,
-                                     pw->pw_uid, 1);
-               }
-               if (Wflg) {
-                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
-                                     "change passwd warning", pw->pw_name,
-                                     pw->pw_uid, 1);
-               }
-               if (Iflg) {
-                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
-                                     "change inactive days", pw->pw_name,
-                                     pw->pw_uid, 1);
-               }
-               if (Eflg) {
-                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
-                                     "change passwd expiration", pw->pw_name,
-                                     pw->pw_uid, 1);
-               }
-#endif
+       STRFCPY (user_name, pw->pw_name);
+#ifdef WITH_TCB
+       if (shadowtcb_set_user (pw->pw_name) == SHADOWTCB_FAILURE) {
+               fail_exit (E_NOPERM);
        }
+#endif
+       user_uid = pw->pw_uid;
+
+       sp = spw_locate (argv[optind]);
+       get_defaults (sp);
 
        /*
         * Print out the expiration fields if the user has requested the
         * list option.
         */
-
        if (lflg) {
-               if (!amroot && (ruid != pwent.pw_uid)) {
-#ifdef WITH_AUDIT
-                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "change age",
-                                     pw->pw_name, pw->pw_uid, 0);
-#endif
+               if (!amroot && (ruid != user_uid)) {
                        fprintf (stderr, _("%s: Permission denied.\n"), Prog);
-                       closelog ();
-                       exit (E_NOPERM);
+                       fail_exit (E_NOPERM);
                }
 #ifdef WITH_AUDIT
-               audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "display aging info",
-                             pw->pw_name, pw->pw_uid, 1);
+               audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
+                             "display aging info",
+                             user_name, (unsigned int) user_uid, 1);
 #endif
                list_fields ();
-               spw_unlock ();
-               closelog ();
-               exit (E_SUCCESS);
+               fail_exit (E_SUCCESS);
        }
 
        /*
@@ -718,86 +876,60 @@ int main (int argc, char **argv)
         * user interactively change them.
         */
        if (!mflg && !Mflg && !dflg && !Wflg && !Iflg && !Eflg) {
-               printf (_("Changing the aging information for %s\n"), name);
+               printf (_("Changing the aging information for %s\n"),
+                       user_name);
                if (new_fields () == 0) {
                        fprintf (stderr, _("%s: error changing fields\n"),
                                 Prog);
-                       spw_unlock ();
-                       closelog ();
-#ifdef WITH_AUDIT
-                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "change age",
-                                     pw->pw_name, getuid (), 0);
-#endif
-                       exit (E_NOPERM);
+                       fail_exit (E_NOPERM);
                }
 #ifdef WITH_AUDIT
                else {
                        audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
                                      "change all aging information",
-                                     pw->pw_name, getuid (), 1);
+                                     user_name, (unsigned int) user_uid, 1);
                }
 #endif
-       }
-       /*
-        * There was no shadow entry. The new entry will have the encrypted
-        * password transferred from the normal password file along with the
-        * aging information.
-        */
-       if (NULL == sp) {
-               sp = &spwent;
-               memzero (&spwent, sizeof spwent);
-
-               spwent.sp_namp = xstrdup (pwent.pw_name);
-               spwent.sp_pwdp = xstrdup (pwent.pw_passwd);
-               spwent.sp_flag = -1;
-
-               pwent.pw_passwd = SHADOW_PASSWD_STRING; /* XXX warning: const */
-               if (pw_update (&pwent) == 0) {
-                       fprintf (stderr,
-                                _("%s: can't update password file\n"), Prog);
-                       spw_unlock ();
-                       SYSLOG ((LOG_ERR, "failed updating %s", PASSWD_FILE));
-                       closelog ();
+       } else {
 #ifdef WITH_AUDIT
-                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "change age",
-                                     pw->pw_name, getuid (), 0);
-#endif
-                       exit (E_NOPERM);
+               if (Mflg) {
+                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
+                                     "change max age",
+                                     user_name, (unsigned int) user_uid, 1);
+               }
+               if (mflg) {
+                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
+                                     "change min age",
+                                     user_name, (unsigned int) user_uid, 1);
+               }
+               if (dflg) {
+                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
+                                     "change last change date",
+                                     user_name, (unsigned int) user_uid, 1);
+               }
+               if (Wflg) {
+                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
+                                     "change passwd warning",
+                                     user_name, (unsigned int) user_uid, 1);
+               }
+               if (Iflg) {
+                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
+                                     "change inactive days",
+                                     user_name, (unsigned int) user_uid, 1);
+               }
+               if (Eflg) {
+                       audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
+                                     "change passwd expiration",
+                                     user_name, (unsigned int) user_uid, 1);
                }
-       }
-
-       /*
-        * Copy the fields back to the shadow file entry and write the
-        * modified entry back to the shadow file. Closing the shadow and
-        * password files will commit any changes that have been made.
-        */
-       spwent.sp_max = maxdays;
-       spwent.sp_min = mindays;
-       spwent.sp_lstchg = lastday;
-       spwent.sp_warn = warndays;
-       spwent.sp_inact = inactdays;
-       spwent.sp_expire = expdays;
-
-       if (spw_update (&spwent) == 0) {
-               fprintf (stderr,
-                        _("%s: can't update shadow password file\n"), Prog);
-               spw_unlock ();
-               SYSLOG ((LOG_ERR, "failed updating %s", SHADOW_FILE));
-               closelog ();
-#ifdef WITH_AUDIT
-               audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "change age",
-                             pw->pw_name, getuid (), 0);
 #endif
-               exit (E_NOPERM);
        }
 
-       close_files ();
+       update_age (sp, pw);
 
-       SYSLOG ((LOG_INFO, "changed password expiry for %s", name));
+       close_files ();
 
-#ifdef USE_PAM
-       pam_end (pamh, PAM_SUCCESS);
-#endif                         /* USE_PAM */
+       SYSLOG ((LOG_INFO, "changed password expiry for %s", user_name));
 
        closelog ();
        exit (E_SUCCESS);