]> granicus.if.org Git - linux-pam/blob - modules/pam_unix/pam_unix_passwd.c
Relevant BUGIDs: patch 476976
[linux-pam] / modules / pam_unix / pam_unix_passwd.c
1 /*
2  * Main coding by Elliot Lee <sopwith@redhat.com>, Red Hat Software. 
3  * Copyright (C) 1996.
4  * Copyright (c) Jan Rêkorajski, 1999.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, and the entire permission notice in its entirety,
11  *    including the disclaimer of warranties.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote
16  *    products derived from this software without specific prior
17  *    written permission.
18  *
19  * ALTERNATIVELY, this product may be distributed under the terms of
20  * the GNU Public License, in which case the provisions of the GPL are
21  * required INSTEAD OF the above restrictions.  (This clause is
22  * necessary due to a potential bad interaction between the GPL and
23  * the restrictions contained in a BSD-style copyright.)
24  *
25  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
26  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
29  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
30  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
33  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
35  * OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37
38 #include <security/_pam_aconf.h>
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <stdarg.h>
43 #include <string.h>
44 #include <malloc.h>
45 #include <unistd.h>
46 #include <errno.h>
47 #include <sys/types.h>
48 #include <pwd.h>
49 #include <syslog.h>
50 #include <shadow.h>
51 #include <time.h>               /* for time() */
52 #include <fcntl.h>
53 #include <ctype.h>
54 #include <sys/time.h>
55 #include <sys/stat.h>
56 #include <rpc/rpc.h>
57 #include <rpcsvc/yp_prot.h>
58 #include <rpcsvc/ypclnt.h>
59
60 #ifdef USE_CRACKLIB
61 #include <crack.h>
62 #endif
63
64 #include <security/_pam_macros.h>
65
66 /* indicate the following groups are defined */
67
68 #define PAM_SM_PASSWORD
69
70 #include <security/pam_modules.h>
71
72 #ifndef LINUX_PAM
73 #include <security/pam_appl.h>
74 #endif                          /* LINUX_PAM */
75
76 #include "yppasswd.h"
77 #include "md5.h"
78 #include "support.h"
79
80 #if !((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 1))
81 extern int getrpcport(const char *host, unsigned long prognum,
82                       unsigned long versnum, unsigned int proto);
83 #endif                          /* GNU libc 2.1 */
84
85 /*
86  * PAM framework looks for these entry-points to pass control to the
87  * password changing module.
88  */
89
90 #ifdef NEED_LCKPWDF
91 # include "./lckpwdf.-c"
92 #endif
93
94 extern char *bigcrypt(const char *key, const char *salt);
95
96 /*
97    How it works:
98    Gets in username (has to be done) from the calling program
99    Does authentication of user (only if we are not running as root)
100    Gets new password/checks for sanity
101    Sets it.
102  */
103
104 /* passwd/salt conversion macros */
105
106 #define ascii_to_bin(c) ((c)>='a'?(c-59):(c)>='A'?((c)-53):(c)-'.')
107 #define bin_to_ascii(c) ((c)>=38?((c)-38+'a'):(c)>=12?((c)-12+'A'):(c)+'.')
108
109 /* data tokens */
110
111 #define _UNIX_OLD_AUTHTOK       "-UN*X-OLD-PASS"
112 #define _UNIX_NEW_AUTHTOK       "-UN*X-NEW-PASS"
113
114 #define MAX_PASSWD_TRIES        3
115 #define PW_TMPFILE              "/etc/npasswd"
116 #define SH_TMPFILE              "/etc/nshadow"
117 #define CRACKLIB_DICTS          "/usr/share/dict/cracklib_dict"
118 #define OPW_TMPFILE             "/etc/security/nopasswd"
119 #define OLD_PASSWORDS_FILE      "/etc/security/opasswd"
120
121 /*
122  * i64c - convert an integer to a radix 64 character
123  */
124 static int i64c(int i)
125 {
126         if (i < 0)
127                 return ('.');
128         else if (i > 63)
129                 return ('z');
130         if (i == 0)
131                 return ('.');
132         if (i == 1)
133                 return ('/');
134         if (i >= 2 && i <= 11)
135                 return ('0' - 2 + i);
136         if (i >= 12 && i <= 37)
137                 return ('A' - 12 + i);
138         if (i >= 38 && i <= 63)
139                 return ('a' - 38 + i);
140         return ('\0');
141 }
142
143 static char *crypt_md5_wrapper(const char *pass_new)
144 {
145         /*
146          * Code lifted from Marek Michalkiewicz's shadow suite. (CG)
147          * removed use of static variables (AGM)
148          */
149
150         struct timeval tv;
151         MD5_CTX ctx;
152         unsigned char result[16];
153         char *cp = (char *) result;
154         unsigned char tmp[16];
155         int i;
156         char *x = NULL;
157
158         GoodMD5Init(&ctx);
159         gettimeofday(&tv, (struct timezone *) 0);
160         GoodMD5Update(&ctx, (void *) &tv, sizeof tv);
161         i = getpid();
162         GoodMD5Update(&ctx, (void *) &i, sizeof i);
163         i = clock();
164         GoodMD5Update(&ctx, (void *) &i, sizeof i);
165         GoodMD5Update(&ctx, result, sizeof result);
166         GoodMD5Final(tmp, &ctx);
167         strcpy(cp, "$1$");      /* magic for the MD5 */
168         cp += strlen(cp);
169         for (i = 0; i < 8; i++)
170                 *cp++ = i64c(tmp[i] & 077);
171         *cp = '\0';
172
173         /* no longer need cleartext */
174         x = Goodcrypt_md5(pass_new, (const char *) result);
175
176         return x;
177 }
178
179 static char *getNISserver(pam_handle_t *pamh)
180 {
181         char *master;
182         char *domainname;
183         int port, err;
184
185         if ((err = yp_get_default_domain(&domainname)) != 0) {
186                 _log_err(LOG_WARNING, pamh, "can't get local yp domain: %s\n",
187                          yperr_string(err));
188                 return NULL;
189         }
190         if ((err = yp_master(domainname, "passwd.byname", &master)) != 0) {
191                 _log_err(LOG_WARNING, pamh, "can't find the master ypserver: %s\n",
192                          yperr_string(err));
193                 return NULL;
194         }
195         port = getrpcport(master, YPPASSWDPROG, YPPASSWDPROC_UPDATE, IPPROTO_UDP);
196         if (port == 0) {
197                 _log_err(LOG_WARNING, pamh,
198                          "yppasswdd not running on NIS master host\n");
199                 return NULL;
200         }
201         if (port >= IPPORT_RESERVED) {
202                 _log_err(LOG_WARNING, pamh,
203                          "yppasswd daemon running on illegal port.\n");
204                 return NULL;
205         }
206         return master;
207 }
208
209 static int check_old_password(const char *forwho, const char *newpass)
210 {
211         static char buf[16384];
212         char *s_luser, *s_uid, *s_npas, *s_pas;
213         int retval = PAM_SUCCESS;
214         FILE *opwfile;
215
216         opwfile = fopen(OLD_PASSWORDS_FILE, "r");
217         if (opwfile == NULL)
218                 return PAM_AUTHTOK_ERR;
219
220         while (fgets(buf, 16380, opwfile)) {
221                 if (!strncmp(buf, forwho, strlen(forwho))) {
222                         buf[strlen(buf) - 1] = '\0';
223                         s_luser = strtok(buf, ":,");
224                         s_uid = strtok(NULL, ":,");
225                         s_npas = strtok(NULL, ":,");
226                         s_pas = strtok(NULL, ":,");
227                         while (s_pas != NULL) {
228                                 char *md5pass = Goodcrypt_md5(newpass, s_pas);
229                                 if (!strcmp(md5pass, s_pas)) {
230                                         _pam_delete(md5pass);
231                                         retval = PAM_AUTHTOK_ERR;
232                                         break;
233                                 }
234                                 s_pas = strtok(NULL, ":,");
235                                 _pam_delete(md5pass);
236                         }
237                         break;
238                 }
239         }
240         fclose(opwfile);
241
242         return retval;
243 }
244
245 static int save_old_password(const char *forwho, const char *oldpass,
246                              int howmany)
247 {
248     static char buf[16384];
249     static char nbuf[16384];
250     char *s_luser, *s_uid, *s_npas, *s_pas, *pass;
251     int npas;
252     FILE *pwfile, *opwfile;
253     int err = 0;
254     int oldmask;
255     int found = 0;
256     struct passwd *pwd = NULL;
257
258     if (howmany < 0) {
259         return PAM_SUCCESS;
260     }
261
262     if (oldpass == NULL) {
263         return PAM_SUCCESS;
264     }
265
266     oldmask = umask(077);
267     pwfile = fopen(OPW_TMPFILE, "w");
268     umask(oldmask);
269     if (pwfile == NULL) {
270         return PAM_AUTHTOK_ERR;
271     }
272
273     opwfile = fopen(OLD_PASSWORDS_FILE, "r");
274     if (opwfile == NULL) {
275         fclose(pwfile);
276         return PAM_AUTHTOK_ERR;
277     }
278
279     chown(OPW_TMPFILE, 0, 0);
280     chmod(OPW_TMPFILE, 0600);
281
282     while (fgets(buf, 16380, opwfile)) {
283         if (!strncmp(buf, forwho, strlen(forwho))) {
284             buf[strlen(buf) - 1] = '\0';
285             s_luser = strtok(buf, ":");
286             s_uid = strtok(NULL, ":");
287             s_npas = strtok(NULL, ":");
288             s_pas = strtok(NULL, ":");
289             npas = strtol(s_npas, NULL, 10) + 1;
290             while (npas > howmany) {
291                 s_pas = strpbrk(s_pas, ",");
292                 if (s_pas != NULL)
293                     s_pas++;
294                 npas--;
295             }
296             pass = crypt_md5_wrapper(oldpass);
297             if (s_pas == NULL)
298                 snprintf(nbuf, sizeof(nbuf), "%s:%s:%d:%s\n",
299                          s_luser, s_uid, npas, pass);
300             else
301                 snprintf(nbuf, sizeof(nbuf),"%s:%s:%d:%s,%s\n",
302                          s_luser, s_uid, npas, s_pas, pass);
303             _pam_delete(pass);
304             if (fputs(nbuf, pwfile) < 0) {
305                 err = 1;
306                 break;
307             }
308             found = 1;
309         } else if (fputs(buf, pwfile) < 0) {
310             err = 1;
311             break;
312         }
313     }
314     fclose(opwfile);
315
316     if (!found) {
317         pwd = getpwnam(forwho);
318         if (pwd == NULL) {
319             err = 1;
320         } else {
321             pass = crypt_md5_wrapper(oldpass);
322             snprintf(nbuf, sizeof(nbuf), "%s:%d:1:%s\n",
323                      forwho, pwd->pw_uid, pass);
324             _pam_delete(pass);
325             if (fputs(nbuf, pwfile) < 0) {
326                 err = 1;
327             }
328         }
329     }
330
331     if (fclose(pwfile)) {
332         D(("error writing entries to old passwords file: %s\n",
333            strerror(errno)));
334         err = 1;
335     }
336
337     if (!err) {
338         rename(OPW_TMPFILE, OLD_PASSWORDS_FILE);
339         return PAM_SUCCESS;
340     } else {
341         unlink(OPW_TMPFILE);
342         return PAM_AUTHTOK_ERR;
343     }
344 }
345
346 static int _update_passwd(pam_handle_t *pamh,
347                           const char *forwho, const char *towhat)
348 {
349     struct passwd *tmpent = NULL;
350     struct stat st;
351     FILE *pwfile, *opwfile;
352     int err = 1;
353     int oldmask;
354
355     oldmask = umask(077);
356     pwfile = fopen(PW_TMPFILE, "w");
357     umask(oldmask);
358     if (pwfile == NULL) {
359         return PAM_AUTHTOK_ERR;
360     }
361
362     opwfile = fopen("/etc/passwd", "r");
363     if (opwfile == NULL) {
364         fclose(pwfile);
365         return PAM_AUTHTOK_ERR;
366     }
367
368     if (fstat(fileno(opwfile), &st) == -1) {
369         chown(PW_TMPFILE, 0, 0);
370         chmod(PW_TMPFILE, 0644);
371     } else {
372         chown(PW_TMPFILE, st.st_uid, st.st_gid);
373         chmod(PW_TMPFILE, st.st_mode);
374     }
375     tmpent = fgetpwent(opwfile);
376     while (tmpent) {
377         if (!strcmp(tmpent->pw_name, forwho)) {
378             /* To shut gcc up */
379             union {
380                 const char *const_charp;
381                 char *charp;
382             } assigned_passwd;
383             assigned_passwd.const_charp = towhat;
384                         
385             tmpent->pw_passwd = assigned_passwd.charp;
386             err = 0;
387         }
388         if (putpwent(tmpent, pwfile)) {
389             D(("error writing entry to password file: %s\n", strerror(errno)));
390             err = 1;
391             break;
392         }
393         tmpent = fgetpwent(opwfile);
394     }
395     fclose(opwfile);
396
397     if (fclose(pwfile)) {
398         D(("error writing entries to password file: %s\n", strerror(errno)));
399         err = 1;
400     }
401
402     if (!err) {
403         rename(PW_TMPFILE, "/etc/passwd");
404         _log_err(LOG_NOTICE, pamh, "password changed for %s", forwho);
405         return PAM_SUCCESS;
406     } else {
407         unlink(PW_TMPFILE);
408         return PAM_AUTHTOK_ERR;
409     }
410 }
411
412 static int _update_shadow(const char *forwho, char *towhat)
413 {
414     struct spwd *spwdent = NULL, *stmpent = NULL;
415     struct stat st;
416     FILE *pwfile, *opwfile;
417     int err = 1;
418     int oldmask;
419
420     spwdent = getspnam(forwho);
421     if (spwdent == NULL) {
422         return PAM_USER_UNKNOWN;
423     }
424     oldmask = umask(077);
425     pwfile = fopen(SH_TMPFILE, "w");
426     umask(oldmask);
427     if (pwfile == NULL) {
428         return PAM_AUTHTOK_ERR;
429     }
430
431     opwfile = fopen("/etc/shadow", "r");
432     if (opwfile == NULL) {
433         fclose(pwfile);
434         return PAM_AUTHTOK_ERR;
435     }
436
437     if (fstat(fileno(opwfile), &st) == -1) {
438         chown(SH_TMPFILE, 0, 0);
439         chmod(SH_TMPFILE, 0600);
440     } else {
441         chown(SH_TMPFILE, st.st_uid, st.st_gid);
442         chmod(SH_TMPFILE, st.st_mode);
443     }
444     stmpent = fgetspent(opwfile);
445     while (stmpent) {
446
447         if (!strcmp(stmpent->sp_namp, forwho)) {
448             stmpent->sp_pwdp = towhat;
449             stmpent->sp_lstchg = time(NULL) / (60 * 60 * 24);
450             err = 0;
451             D(("Set password %s for %s", stmpent->sp_pwdp, forwho));
452         }
453
454         if (putspent(stmpent, pwfile)) {
455             D(("error writing entry to shadow file: %s\n", strerror(errno)));
456             err = 1;
457             break;
458         }
459
460         stmpent = fgetspent(opwfile);
461     }
462     fclose(opwfile);
463
464     if (fclose(pwfile)) {
465         D(("error writing entries to shadow file: %s\n", strerror(errno)));
466         err = 1;
467     }
468
469     if (!err) {
470         rename(SH_TMPFILE, "/etc/shadow");
471         return PAM_SUCCESS;
472     } else {
473         unlink(SH_TMPFILE);
474         return PAM_AUTHTOK_ERR;
475     }
476 }
477
478 static int _do_setpass(pam_handle_t* pamh, const char *forwho, char *fromwhat,
479                        char *towhat, unsigned int ctrl, int remember)
480 {
481         struct passwd *pwd = NULL;
482         int retval = 0;
483
484         D(("called"));
485
486         pwd = getpwnam(forwho);
487         if (pwd == NULL)
488                 return PAM_AUTHTOK_ERR;
489
490         if (on(UNIX_NIS, ctrl)) {
491                 struct timeval timeout;
492                 struct yppasswd yppwd;
493                 CLIENT *clnt;
494                 char *master;
495                 int status;
496                 int err = 0;
497
498                 /* Make RPC call to NIS server */
499                 if ((master = getNISserver(pamh)) == NULL)
500                         return PAM_TRY_AGAIN;
501
502                 /* Initialize password information */
503                 yppwd.newpw.pw_passwd = pwd->pw_passwd;
504                 yppwd.newpw.pw_name = pwd->pw_name;
505                 yppwd.newpw.pw_uid = pwd->pw_uid;
506                 yppwd.newpw.pw_gid = pwd->pw_gid;
507                 yppwd.newpw.pw_gecos = pwd->pw_gecos;
508                 yppwd.newpw.pw_dir = pwd->pw_dir;
509                 yppwd.newpw.pw_shell = pwd->pw_shell;
510                 yppwd.oldpass = fromwhat;
511                 yppwd.newpw.pw_passwd = towhat;
512
513                 D(("Set password %s for %s", yppwd.newpw.pw_passwd, forwho));
514
515                 /* The yppasswd.x file said `unix authentication required',
516                  * so I added it. This is the only reason it is in here.
517                  * My yppasswdd doesn't use it, but maybe some others out there
518                  * do.                                        --okir
519                  */
520                 clnt = clnt_create(master, YPPASSWDPROG, YPPASSWDVERS, "udp");
521                 clnt->cl_auth = authunix_create_default();
522                 memset((char *) &status, '\0', sizeof(status));
523                 timeout.tv_sec = 25;
524                 timeout.tv_usec = 0;
525                 err = clnt_call(clnt, YPPASSWDPROC_UPDATE,
526                                 (xdrproc_t) xdr_yppasswd, (char *) &yppwd,
527                                 (xdrproc_t) xdr_int, (char *) &status,
528                                 timeout);
529
530                 if (err) {
531                         clnt_perrno(err);
532                         retval = PAM_TRY_AGAIN;
533                 } else if (status) {
534                         D(("Error while changing NIS password.\n"));
535                         retval = PAM_TRY_AGAIN;
536                 }
537                 D(("The password has%s been changed on %s.",
538                    (err || status) ? " not" : "", master));
539                 _log_err(LOG_NOTICE, pamh, "password%s changed for %s on %s",
540                          (err || status) ? " not" : "", pwd->pw_name, master);
541
542                 auth_destroy(clnt->cl_auth);
543                 clnt_destroy(clnt);
544                 if ((err || status) != 0) {
545                         retval = PAM_TRY_AGAIN;
546                 }
547 #ifdef DEBUG
548                 sleep(5);
549 #endif
550                 return retval;
551         }
552         /* first, save old password */
553         if (save_old_password(forwho, fromwhat, remember)) {
554                 return PAM_AUTHTOK_ERR;
555         }
556
557 #ifdef USE_LCKPWDF
558         /*
559          * These values for the number of attempts and the sleep time
560          * are, of course, completely arbitrary.
561          *
562          * My reading of the PAM docs is that, once pam_chauthtok()
563          * has been called with PAM_UPDATE_AUTHTOK, we are obliged to
564          * take any reasonable steps to make sure the token is
565          * updated; so retrying for 1/10 sec. isn't overdoing it.
566          */
567
568         retval = lckpwdf();
569         if (retval != 0) {
570             return PAM_AUTHTOK_LOCK_BUSY;
571         }
572 #endif /* def USE_LCKPWDF */
573         
574         if (on(UNIX_SHADOW, ctrl) || (strcmp(pwd->pw_passwd, "x") == 0)) {
575                 retval = _update_shadow(forwho, towhat);
576                 if (retval == PAM_SUCCESS)
577                         retval = _update_passwd(pamh, forwho, "x");
578         } else {
579                 retval = _update_passwd(pamh, forwho, towhat);
580         }
581
582 #ifdef USE_LCKPWDF
583         ulckpwdf();
584 #endif /* def USE_LCKPWDF */
585
586         return retval;
587 }
588
589 static int _unix_verify_shadow(const char *user, unsigned int ctrl)
590 {
591         struct passwd *pwd = NULL;      /* Password and shadow password */
592         struct spwd *spwdent = NULL;    /* file entries for the user */
593         time_t curdays;
594         int retval = PAM_SUCCESS;
595
596         /* UNIX passwords area */
597         pwd = getpwnam(user);   /* Get password file entry... */
598         if (pwd == NULL)
599                 return PAM_AUTHINFO_UNAVAIL;    /* We don't need to do the rest... */
600
601         if (strcmp(pwd->pw_passwd, "x") == 0) {
602                 /* ...and shadow password file entry for this user, if shadowing
603                    is enabled */
604                 setspent();
605                 spwdent = getspnam(user);
606                 endspent();
607
608                 if (spwdent == NULL)
609                         return PAM_AUTHINFO_UNAVAIL;
610         } else {
611                 if (strcmp(pwd->pw_passwd,"*NP*") == 0) { /* NIS+ */                 
612                         uid_t save_uid;
613
614                         save_uid = geteuid();
615                         seteuid (pwd->pw_uid);
616                         spwdent = getspnam( user );
617                         seteuid (save_uid);
618
619                         if (spwdent == NULL)
620                                 return PAM_AUTHINFO_UNAVAIL;
621                 } else
622                         spwdent = NULL;
623         }
624
625         if (spwdent != NULL) {
626                 /* We have the user's information, now let's check if their account
627                    has expired (60 * 60 * 24 = number of seconds in a day) */
628
629                 if (off(UNIX__IAMROOT, ctrl)) {
630                         /* Get the current number of days since 1970 */
631                         curdays = time(NULL) / (60 * 60 * 24);
632                         if ((curdays < (spwdent->sp_lstchg + spwdent->sp_min))
633                             && (spwdent->sp_min != -1))
634                                 retval = PAM_AUTHTOK_ERR;
635                         else if ((curdays > (spwdent->sp_lstchg + spwdent->sp_max + spwdent->sp_inact))
636                                  && (spwdent->sp_max != -1) && (spwdent->sp_inact != -1)
637                                  && (spwdent->sp_lstchg != 0))
638                                 /*
639                                  * Their password change has been put off too long,
640                                  */
641                                 retval = PAM_ACCT_EXPIRED;
642                         else if ((curdays > spwdent->sp_expire) && (spwdent->sp_expire != -1)
643                                  && (spwdent->sp_lstchg != 0))
644                                 /*
645                                  * OR their account has just plain expired
646                                  */
647                                 retval = PAM_ACCT_EXPIRED;
648                 }
649         }
650         return retval;
651 }
652
653 static int _pam_unix_approve_pass(pam_handle_t * pamh
654                                   ,unsigned int ctrl
655                                   ,const char *pass_old
656                                   ,const char *pass_new)
657 {
658         const char *user;
659         const char *remark = NULL;
660         int retval = PAM_SUCCESS;
661
662         D(("&new=%p, &old=%p", pass_old, pass_new));
663         D(("new=[%s]", pass_new));
664         D(("old=[%s]", pass_old));
665
666         if (pass_new == NULL || (pass_old && !strcmp(pass_old, pass_new))) {
667                 if (on(UNIX_DEBUG, ctrl)) {
668                         _log_err(LOG_DEBUG, pamh, "bad authentication token");
669                 }
670                 _make_remark(pamh, ctrl, PAM_ERROR_MSG, pass_new == NULL ?
671                           "No password supplied" : "Password unchanged");
672                 return PAM_AUTHTOK_ERR;
673         }
674         /*
675          * if one wanted to hardwire authentication token strength
676          * checking this would be the place - AGM
677          */
678
679         retval = pam_get_item(pamh, PAM_USER, (const void **) &user);
680         if (retval != PAM_SUCCESS) {
681                 if (on(UNIX_DEBUG, ctrl)) {
682                         _log_err(LOG_ERR, pamh, "Can not get username");
683                         return PAM_AUTHTOK_ERR;
684                 }
685         }
686         if (off(UNIX__IAMROOT, ctrl)) {
687 #ifdef USE_CRACKLIB
688                 remark = FascistCheck(pass_new, CRACKLIB_DICTS);
689                 D(("called cracklib [%s]", remark));
690 #else
691                 if (strlen(pass_new) < 6)
692                         remark = "You must choose a longer password";
693                 D(("lenth check [%s]", remark));
694 #endif
695                 if (on(UNIX_REMEMBER_PASSWD, ctrl))
696                         if ((retval = check_old_password(user, pass_new)) != PAM_SUCCESS)
697                                 remark = "Password has been already used. Choose another.";
698         }
699         if (remark) {
700                 _make_remark(pamh, ctrl, PAM_ERROR_MSG, remark);
701                 retval = PAM_AUTHTOK_ERR;
702         }
703         return retval;
704 }
705
706
707 PAM_EXTERN int pam_sm_chauthtok(pam_handle_t * pamh, int flags,
708                                 int argc, const char **argv)
709 {
710         unsigned int ctrl, lctrl;
711         int retval;
712         int remember = -1;
713
714         /* <DO NOT free() THESE> */
715         const char *user;
716         char *pass_old, *pass_new;
717         /* </DO NOT free() THESE> */
718
719         D(("called."));
720
721         ctrl = _set_ctrl(pamh, flags, &remember, argc, argv);
722
723         /*
724          * First get the name of a user
725          */
726         retval = pam_get_user(pamh, &user, NULL);
727         if (retval == PAM_SUCCESS) {
728                 /*
729                  * Various libraries at various times have had bugs related to
730                  * '+' or '-' as the first character of a user name. Don't take
731                  * any chances here. Require that the username starts with an
732                  * alphanumeric character.
733                  */
734                 if (user == NULL || !isalnum(*user)) {
735                         _log_err(LOG_ERR, pamh, "bad username [%s]", user);
736                         return PAM_USER_UNKNOWN;
737                 }
738                 if (retval == PAM_SUCCESS && on(UNIX_DEBUG, ctrl))
739                         _log_err(LOG_DEBUG, pamh, "username [%s] obtained",
740                                  user);
741         } else {
742                 if (on(UNIX_DEBUG, ctrl))
743                         _log_err(LOG_DEBUG, pamh,
744                                  "password - could not identify user");
745                 return retval;
746         }
747
748         D(("Got username of %s", user));
749
750         /*
751          * This is not an AUTH module!
752          */
753         if (on(UNIX__NONULL, ctrl))
754                 set(UNIX__NULLOK, ctrl);
755
756         if (on(UNIX__PRELIM, ctrl)) {
757                 /*
758                  * obtain and verify the current password (OLDAUTHTOK) for
759                  * the user.
760                  */
761                 char *Announce;
762
763                 D(("prelim check"));
764
765                 if (_unix_blankpasswd(ctrl, user)) {
766                         return PAM_SUCCESS;
767                 } else if (off(UNIX__IAMROOT, ctrl)) {
768
769                         /* instruct user what is happening */
770 #define greeting "Changing password for "
771                         Announce = (char *) malloc(sizeof(greeting) + strlen(user));
772                         if (Announce == NULL) {
773                                 _log_err(LOG_CRIT, pamh,
774                                          "password - out of memory");
775                                 return PAM_BUF_ERR;
776                         }
777                         (void) strcpy(Announce, greeting);
778                         (void) strcpy(Announce + sizeof(greeting) - 1, user);
779 #undef greeting
780
781                         lctrl = ctrl;
782                         set(UNIX__OLD_PASSWD, lctrl);
783                         retval = _unix_read_password(pamh, lctrl
784                                                      ,Announce
785                                              ,"(current) UNIX password: "
786                                                      ,NULL
787                                                      ,_UNIX_OLD_AUTHTOK
788                                              ,(const char **) &pass_old);
789                         free(Announce);
790
791                         if (retval != PAM_SUCCESS) {
792                                 _log_err(LOG_NOTICE, pamh
793                                  ,"password - (old) token not obtained");
794                                 return retval;
795                         }
796                         /* verify that this is the password for this user */
797
798                         retval = _unix_verify_password(pamh, user, pass_old, ctrl);
799                 } else {
800                         D(("process run by root so do nothing this time around"));
801                         pass_old = NULL;
802                         retval = PAM_SUCCESS;   /* root doesn't have too */
803                 }
804
805                 if (retval != PAM_SUCCESS) {
806                         D(("Authentication failed"));
807                         pass_old = NULL;
808                         return retval;
809                 }
810                 retval = pam_set_item(pamh, PAM_OLDAUTHTOK, (const void *) pass_old);
811                 pass_old = NULL;
812                 if (retval != PAM_SUCCESS) {
813                         _log_err(LOG_CRIT, pamh,
814                                  "failed to set PAM_OLDAUTHTOK");
815                 }
816                 retval = _unix_verify_shadow(user, ctrl);
817                 if (retval == PAM_AUTHTOK_ERR) {
818                         if (off(UNIX__IAMROOT, ctrl))
819                                 _make_remark(pamh, ctrl, PAM_ERROR_MSG,
820                                             "You must wait longer to change your password");
821                         else
822                                 retval = PAM_SUCCESS;
823                 }
824         } else if (on(UNIX__UPDATE, ctrl)) {
825                 /*
826                  * tpass is used below to store the _pam_md() return; it
827                  * should be _pam_delete()'d.
828                  */
829
830                 char *tpass = NULL;
831                 int retry = 0;
832
833                 /*
834                  * obtain the proposed password
835                  */
836
837                 D(("do update"));
838
839                 /*
840                  * get the old token back. NULL was ok only if root [at this
841                  * point we assume that this has already been enforced on a
842                  * previous call to this function].
843                  */
844
845                 if (off(UNIX_NOT_SET_PASS, ctrl)) {
846                         retval = pam_get_item(pamh, PAM_OLDAUTHTOK
847                                               ,(const void **) &pass_old);
848                 } else {
849                         retval = pam_get_data(pamh, _UNIX_OLD_AUTHTOK
850                                               ,(const void **) &pass_old);
851                         if (retval == PAM_NO_MODULE_DATA) {
852                                 retval = PAM_SUCCESS;
853                                 pass_old = NULL;
854                         }
855                 }
856                 D(("pass_old [%s]", pass_old));
857
858                 if (retval != PAM_SUCCESS) {
859                         _log_err(LOG_NOTICE, pamh, "user not authenticated");
860                         return retval;
861                 }
862                 retval = _unix_verify_shadow(user, ctrl);
863                 if (retval != PAM_SUCCESS) {
864                         _log_err(LOG_NOTICE, pamh, "user not authenticated 2");
865                         return retval;
866                 }
867                 D(("get new password now"));
868
869                 lctrl = ctrl;
870
871                 if (on(UNIX_USE_AUTHTOK, lctrl)) {
872                         set(UNIX_USE_FIRST_PASS, lctrl);
873                 }
874                 retry = 0;
875                 retval = PAM_AUTHTOK_ERR;
876                 while ((retval != PAM_SUCCESS) && (retry++ < MAX_PASSWD_TRIES)) {
877                         /*
878                          * use_authtok is to force the use of a previously entered
879                          * password -- needed for pluggable password strength checking
880                          */
881
882                         retval = _unix_read_password(pamh, lctrl
883                                                      ,NULL
884                                              ,"Enter new UNIX password: "
885                                             ,"Retype new UNIX password: "
886                                                      ,_UNIX_NEW_AUTHTOK
887                                              ,(const char **) &pass_new);
888
889                         if (retval != PAM_SUCCESS) {
890                                 if (on(UNIX_DEBUG, ctrl)) {
891                                         _log_err(LOG_ALERT, pamh
892                                                  ,"password - new password not obtained");
893                                 }
894                                 pass_old = NULL;        /* tidy up */
895                                 return retval;
896                         }
897                         D(("returned to _unix_chauthtok"));
898
899                         /*
900                          * At this point we know who the user is and what they
901                          * propose as their new password. Verify that the new
902                          * password is acceptable.
903                          */
904
905                         if (pass_new[0] == '\0') {      /* "\0" password = NULL */
906                                 pass_new = NULL;
907                         }
908                         retval = _pam_unix_approve_pass(pamh, ctrl, pass_old, pass_new);
909                 }
910
911                 if (retval != PAM_SUCCESS) {
912                         _log_err(LOG_NOTICE, pamh,
913                                  "new password not acceptable");
914                         pass_new = pass_old = NULL;     /* tidy up */
915                         return retval;
916                 }
917                 /*
918                  * By reaching here we have approved the passwords and must now
919                  * rebuild the password database file.
920                  */
921
922                 /*
923                  * First we encrypt the new password.
924                  */
925
926                 if (on(UNIX_MD5_PASS, ctrl)) {
927                         tpass = crypt_md5_wrapper(pass_new);
928                 } else {
929                         /*
930                          * Salt manipulation is stolen from Rick Faith's passwd
931                          * program.  Sorry Rick :) -- alex
932                          */
933
934                         time_t tm;
935                         char salt[3];
936
937                         time(&tm);
938                         salt[0] = bin_to_ascii(tm & 0x3f);
939                         salt[1] = bin_to_ascii((tm >> 6) & 0x3f);
940                         salt[2] = '\0';
941
942                         if (off(UNIX_BIGCRYPT, ctrl) && strlen(pass_new) > 8) {
943                                 /* 
944                                  * to avoid using the _extensions_ of the bigcrypt()
945                                  * function we truncate the newly entered password
946                                  * [Problems that followed from this are fixed as per
947                                  *  Bug 521314.]
948                                  */
949                                 char *temp = malloc(9);
950
951                                 if (temp == NULL) {
952                                         _log_err(LOG_CRIT, pamh,
953                                                  "out of memory for password");
954                                         pass_new = pass_old = NULL;     /* tidy up */
955                                         return PAM_BUF_ERR;
956                                 }
957                                 /* copy first 8 bytes of password */
958                                 strncpy(temp, pass_new, 8);
959                                 temp[8] = '\0';
960
961                                 /* no longer need cleartext */
962                                 tpass = bigcrypt(temp, salt);
963
964                                 _pam_delete(temp);      /* tidy up */
965                         } else {
966                                 tpass = bigcrypt(pass_new, salt);
967                         }
968                 }
969
970                 D(("password processed"));
971
972                 /* update the password database(s) -- race conditions..? */
973
974                 retval = _do_setpass(pamh, user, pass_old, tpass, ctrl,
975                                      remember);
976
977                 _pam_delete(tpass);
978                 pass_old = pass_new = NULL;
979         } else {                /* something has broken with the module */
980                 _log_err(LOG_ALERT, pamh,
981                          "password received unknown request");
982                 retval = PAM_ABORT;
983         }
984
985         D(("retval was %d", retval));
986
987         return retval;
988 }
989
990
991 /* static module data */
992 #ifdef PAM_STATIC
993 struct pam_module _pam_unix_passwd_modstruct = {
994     "pam_unix_passwd",
995     NULL,
996     NULL,
997     NULL,
998     NULL,
999     NULL,
1000     pam_sm_chauthtok,
1001 };
1002 #endif
1003