]> granicus.if.org Git - linux-pam/blob - modules/pam_unix/passverify.c
doc: fix module type written in MODULE TYPES PROVIDED
[linux-pam] / modules / pam_unix / passverify.c
1 /*
2  * Copyright information at end of file.
3  */
4 #include "config.h"
5 #include <security/_pam_macros.h>
6 #include <security/pam_modules.h>
7 #include "support.h"
8 #include <stdio.h>
9 #include <string.h>
10 #include <sys/types.h>
11 #include <unistd.h>
12 #include <pwd.h>
13 #include <shadow.h>
14 #include <syslog.h>
15 #include <stdarg.h>
16 #include <signal.h>
17 #include <errno.h>
18 #include <time.h>
19 #include <sys/time.h>
20 #include <sys/stat.h>
21 #include <fcntl.h>
22 #ifdef HAVE_LIBXCRYPT
23 #include <xcrypt.h>
24 #elif defined(HAVE_CRYPT_H)
25 #include <crypt.h>
26 #endif
27
28 #include "md5.h"
29 #include "bigcrypt.h"
30 #include "passverify.h"
31
32 #ifdef WITH_SELINUX
33 #include <selinux/selinux.h>
34 #define SELINUX_ENABLED (is_selinux_enabled()>0)
35 #else
36 #define SELINUX_ENABLED 0
37 #endif
38
39 #ifdef HELPER_COMPILE
40 #define pam_modutil_getpwnam(h,n) getpwnam(n)
41 #define pam_modutil_getspnam(h,n) getspnam(n)
42 #define pam_syslog(h,a,b,c) helper_log_err(a,b,c)
43 #else
44 #include <security/pam_modutil.h>
45 #include <security/pam_ext.h>
46 #endif
47
48 #if defined(USE_LCKPWDF) && !defined(HAVE_LCKPWDF)
49 # include "./lckpwdf.-c"
50 #endif
51
52 static void
53 strip_hpux_aging(char *hash)
54 {
55         static const char valid[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
56                 "abcdefghijklmnopqrstuvwxyz"
57                 "0123456789./";
58         if ((*hash != '$') && (strlen(hash) > 13)) {
59                 for (hash += 13; *hash != '\0'; hash++) {
60                         if (strchr(valid, *hash) == NULL) {
61                                 *hash = '\0';
62                                 break;
63                         }
64                 }
65         }
66 }
67
68 PAMH_ARG_DECL(int verify_pwd_hash,
69         const char *p, char *hash, unsigned int nullok)
70 {
71         size_t hash_len;
72         char *pp = NULL;
73         int retval;
74         D(("called"));
75
76         strip_hpux_aging(hash);
77         hash_len = strlen(hash);
78         if (!hash_len) {
79                 /* the stored password is NULL */
80                 if (nullok) { /* this means we've succeeded */
81                         D(("user has empty password - access granted"));
82                         retval = PAM_SUCCESS;
83                 } else {
84                         D(("user has empty password - access denied"));
85                         retval = PAM_AUTH_ERR;
86                 }
87         } else if (!p || *hash == '*' || *hash == '!') {
88                 retval = PAM_AUTH_ERR;
89         } else {
90                 if (!strncmp(hash, "$1$", 3)) {
91                         pp = Goodcrypt_md5(p, hash);
92                         if (pp && strcmp(pp, hash) != 0) {
93                                 _pam_delete(pp);
94                                 pp = Brokencrypt_md5(p, hash);
95                         }
96                 } else if (*hash != '$' && hash_len >= 13) {
97                         pp = bigcrypt(p, hash);
98                         if (pp && hash_len == 13 && strlen(pp) > hash_len) {
99                                 _pam_overwrite(pp + hash_len);
100                         }
101                 } else {
102                         /*
103                          * Ok, we don't know the crypt algorithm, but maybe
104                          * libcrypt knows about it? We should try it.
105                          */
106 #if defined(CRYPT_CHECKSALT_AVAILABLE) && CRYPT_CHECKSALT_AVAILABLE
107                         /* Get the status of the hash from checksalt */
108                         int retval_checksalt = crypt_checksalt(hash);
109
110                         /*
111                          * Check for hashing methods that are disabled by
112                          * libcrypt configuration and/or system preset.
113                          */
114                         if (retval_checksalt == CRYPT_SALT_METHOD_DISABLED) {
115                                 /*
116                                  * pam_syslog() needs a pam handle,
117                                  * but that's not available here.
118                                  */
119                                 pam_syslog(pamh, LOG_ERR,
120                                   "The support for password hash \"%.6s\" "
121                                   "has been disabled in libcrypt "
122                                   "configuration.",
123                                   hash);
124                         }
125                         /*
126                          * Check for malformed hashes, like descrypt hashes
127                          * starting with "$2...", which might have been
128                          * generated by unsafe base64 encoding functions
129                          * as used in glibc <= 2.16.
130                          * Such hashes are likely to be rejected by many
131                          * recent implementations of libcrypt.
132                          */
133                         if (retval_checksalt == CRYPT_SALT_INVALID) {
134                                 pam_syslog(pamh, LOG_ERR,
135                                   "The password hash \"%.6s\" is unknown to "
136                                   "libcrypt.",
137                                   hash);
138                         }
139 #else
140 #ifndef HELPER_COMPILE
141                         (void)pamh;
142 #endif
143 #endif
144 #ifdef HAVE_CRYPT_R
145                         struct crypt_data *cdata;
146                         cdata = malloc(sizeof(*cdata));
147                         if (cdata != NULL) {
148                                 cdata->initialized = 0;
149                                 pp = x_strdup(crypt_r(p, hash, cdata));
150                                 memset(cdata, '\0', sizeof(*cdata));
151                                 free(cdata);
152                         }
153 #else
154                         pp = x_strdup(crypt(p, hash));
155 #endif
156                 }
157                 p = NULL;               /* no longer needed here */
158
159                 /* the moment of truth -- do we agree with the password? */
160                 D(("comparing state of pp[%s] and hash[%s]", pp, hash));
161
162                 if (pp && strcmp(pp, hash) == 0) {
163                         retval = PAM_SUCCESS;
164                 } else {
165                         retval = PAM_AUTH_ERR;
166                 }
167         }
168
169         if (pp)
170                 _pam_delete(pp);
171         D(("done [%d].", retval));
172
173         return retval;
174 }
175
176 int
177 is_pwd_shadowed(const struct passwd *pwd)
178 {
179         if (pwd != NULL) {
180                 if (strcmp(pwd->pw_passwd, "x") == 0) {
181                         return 1;
182                 }
183                 if ((pwd->pw_passwd[0] == '#') &&
184                     (pwd->pw_passwd[1] == '#') &&
185                     (strcmp(pwd->pw_name, pwd->pw_passwd + 2) == 0)) {
186                         return 1;
187                 }
188         }
189         return 0;
190 }
191
192 PAMH_ARG_DECL(int get_account_info,
193         const char *name, struct passwd **pwd, struct spwd **spwdent)
194 {
195         /* UNIX passwords area */
196         *pwd = pam_modutil_getpwnam(pamh, name);        /* Get password file entry... */
197         *spwdent = NULL;
198
199         if (*pwd != NULL) {
200                 if (strcmp((*pwd)->pw_passwd, "*NP*") == 0)
201                 { /* NIS+ */
202 #ifdef HELPER_COMPILE
203                         uid_t save_euid, save_uid;
204
205                         save_euid = geteuid();
206                         save_uid = getuid();
207                         if (save_uid == (*pwd)->pw_uid)
208                                 setreuid(save_euid, save_uid);
209                         else  {
210                                 setreuid(0, -1);
211                                 if (setreuid(-1, (*pwd)->pw_uid) == -1) {
212                                         setreuid(-1, 0);
213                                         setreuid(0, -1);
214                                         if(setreuid(-1, (*pwd)->pw_uid) == -1)
215                                                 return PAM_CRED_INSUFFICIENT;
216                                 }
217                         }
218
219                         *spwdent = pam_modutil_getspnam(pamh, name);
220                         if (save_uid == (*pwd)->pw_uid)
221                                 setreuid(save_uid, save_euid);
222                         else {
223                                 setreuid(-1, 0);
224                                 setreuid(save_uid, -1);
225                                 setreuid(-1, save_euid);
226                         }
227
228                         if (*spwdent == NULL || (*spwdent)->sp_pwdp == NULL)
229                                 return PAM_AUTHINFO_UNAVAIL;
230 #else
231                         /* we must run helper for NIS+ passwords */
232                         return PAM_UNIX_RUN_HELPER;
233 #endif
234                 } else if (is_pwd_shadowed(*pwd)) {
235                         /*
236                          * ...and shadow password file entry for this user,
237                          * if shadowing is enabled
238                          */
239 #ifndef HELPER_COMPILE
240                         if (geteuid() || SELINUX_ENABLED)
241                                 return PAM_UNIX_RUN_HELPER;
242 #endif
243                         *spwdent = pam_modutil_getspnam(pamh, name);
244                         if (*spwdent == NULL || (*spwdent)->sp_pwdp == NULL)
245                                 return PAM_AUTHINFO_UNAVAIL;
246                 }
247         } else {
248                 return PAM_USER_UNKNOWN;
249         }
250         return PAM_SUCCESS;
251 }
252
253 PAMH_ARG_DECL(int get_pwd_hash,
254         const char *name, struct passwd **pwd, char **hash)
255 {
256         int retval;
257         struct spwd *spwdent = NULL;
258
259         retval = get_account_info(PAMH_ARG(name, pwd, &spwdent));
260         if (retval != PAM_SUCCESS) {
261                 return retval;
262         }
263
264         if (spwdent)
265                 *hash = x_strdup(spwdent->sp_pwdp);
266         else
267                 *hash = x_strdup((*pwd)->pw_passwd);
268         if (*hash == NULL)
269                 return PAM_BUF_ERR;
270
271         return PAM_SUCCESS;
272 }
273
274 PAMH_ARG_DECL(int check_shadow_expiry,
275         struct spwd *spent, int *daysleft)
276 {
277         long int curdays;
278         *daysleft = -1;
279         curdays = (long int)(time(NULL) / (60 * 60 * 24));
280         D(("today is %d, last change %d", curdays, spent->sp_lstchg));
281         if ((curdays >= spent->sp_expire) && (spent->sp_expire != -1)) {
282                 D(("account expired"));
283                 return PAM_ACCT_EXPIRED;
284         }
285 #if defined(CRYPT_CHECKSALT_AVAILABLE) && CRYPT_CHECKSALT_AVAILABLE
286         if (spent->sp_lstchg == 0 ||
287             crypt_checksalt(spent->sp_pwdp) == CRYPT_SALT_METHOD_LEGACY ||
288             crypt_checksalt(spent->sp_pwdp) == CRYPT_SALT_TOO_CHEAP) {
289 #else
290         if (spent->sp_lstchg == 0) {
291 #endif
292                 D(("need a new password"));
293                 *daysleft = 0;
294                 return PAM_NEW_AUTHTOK_REQD;
295         }
296         if (curdays < spent->sp_lstchg) {
297                 pam_syslog(pamh, LOG_DEBUG,
298                          "account %s has password changed in future",
299                          spent->sp_namp);
300                 return PAM_SUCCESS;
301         }
302         if ((curdays - spent->sp_lstchg > spent->sp_max)
303             && (curdays - spent->sp_lstchg > spent->sp_inact)
304             && (curdays - spent->sp_lstchg > spent->sp_max + spent->sp_inact)
305             && (spent->sp_max != -1) && (spent->sp_inact != -1)) {
306                 *daysleft = (int)((spent->sp_lstchg + spent->sp_max) - curdays);
307                 D(("authtok expired"));
308                 return PAM_AUTHTOK_EXPIRED;
309         }
310         if ((curdays - spent->sp_lstchg > spent->sp_max) && (spent->sp_max != -1)) {
311                 D(("need a new password 2"));
312                 return PAM_NEW_AUTHTOK_REQD;
313         }
314         if ((curdays - spent->sp_lstchg > spent->sp_max - spent->sp_warn)
315             && (spent->sp_max != -1) && (spent->sp_warn != -1)) {
316                 *daysleft = (int)((spent->sp_lstchg + spent->sp_max) - curdays);
317                 D(("warn before expiry"));
318         }
319         if ((curdays - spent->sp_lstchg < spent->sp_min)
320             && (spent->sp_min != -1)) {
321                 /*
322                  * The last password change was too recent. This error will be ignored
323                  * if no password change is attempted.
324                  */
325                 D(("password change too recent"));
326                 return PAM_AUTHTOK_ERR;
327         }
328         return PAM_SUCCESS;
329 }
330
331 /* passwd/salt conversion macros */
332
333 #define PW_TMPFILE              "/etc/npasswd"
334 #define SH_TMPFILE              "/etc/nshadow"
335 #define OPW_TMPFILE             "/etc/security/nopasswd"
336
337 /*
338  * i64c - convert an integer to a radix 64 character
339  */
340 static int
341 i64c(int i)
342 {
343         if (i < 0)
344                 return ('.');
345         else if (i > 63)
346                 return ('z');
347         if (i == 0)
348                 return ('.');
349         if (i == 1)
350                 return ('/');
351         if (i >= 2 && i <= 11)
352                 return ('0' - 2 + i);
353         if (i >= 12 && i <= 37)
354                 return ('A' - 12 + i);
355         if (i >= 38 && i <= 63)
356                 return ('a' - 38 + i);
357         return ('\0');
358 }
359
360 /* <where> must point to a buffer of at least <length>+1 length */
361 static void
362 crypt_make_salt(char *where, int length)
363 {
364         struct timeval tv;
365         MD5_CTX ctx;
366         unsigned char tmp[16];
367         unsigned char *src = (unsigned char *)where;
368         int i;
369 #ifdef PAM_PATH_RANDOMDEV
370         int fd;
371         int rv;
372
373         if ((rv = fd = open(PAM_PATH_RANDOMDEV, O_RDONLY)) != -1) {
374                 while ((rv = read(fd, where, length)) != length && errno == EINTR);
375                 close (fd);
376         }
377         if (rv != length) {
378 #endif
379         /*
380          * Code lifted from Marek Michalkiewicz's shadow suite. (CG)
381          * removed use of static variables (AGM)
382          *
383          * will work correctly only for length <= 16 */
384         src = tmp;
385         GoodMD5Init(&ctx);
386         gettimeofday(&tv, (struct timezone *) 0);
387         GoodMD5Update(&ctx, (void *) &tv, sizeof tv);
388         i = getpid();
389         GoodMD5Update(&ctx, (void *) &i, sizeof i);
390         i = clock();
391         GoodMD5Update(&ctx, (void *) &i, sizeof i);
392         GoodMD5Update(&ctx, src, length);
393         GoodMD5Final(tmp, &ctx);
394 #ifdef PAM_PATH_RANDOMDEV
395         }
396 #endif
397         for (i = 0; i < length; i++)
398                 *where++ = i64c(src[i] & 077);
399         *where = '\0';
400 }
401
402 char *
403 crypt_md5_wrapper(const char *pass_new)
404 {
405         unsigned char result[16];
406         char *cp = (char *) result;
407
408         cp = stpcpy(cp, "$1$");      /* magic for the MD5 */
409         crypt_make_salt(cp, 8);
410
411         /* no longer need cleartext */
412         cp = Goodcrypt_md5(pass_new, (const char *) result);
413         pass_new = NULL;
414
415         return cp;
416 }
417
418 PAMH_ARG_DECL(char * create_password_hash,
419         const char *password, unsigned long long ctrl, int rounds)
420 {
421         const char *algoid;
422 #if defined(CRYPT_GENSALT_OUTPUT_SIZE) && CRYPT_GENSALT_OUTPUT_SIZE > 64
423         /* Strings returned by crypt_gensalt_rn will be no longer than this. */
424         char salt[CRYPT_GENSALT_OUTPUT_SIZE];
425 #else
426         char salt[64]; /* contains rounds number + max 16 bytes of salt + algo id */
427 #endif
428         char *sp;
429 #ifdef HAVE_CRYPT_R
430         struct crypt_data *cdata = NULL;
431 #endif
432
433         if (on(UNIX_MD5_PASS, ctrl)) {
434                 /* algoid = "$1" */
435                 return crypt_md5_wrapper(password);
436         } else if (on(UNIX_YESCRYPT_PASS, ctrl)) {
437                 algoid = "$y$";
438         } else if (on(UNIX_GOST_YESCRYPT_PASS, ctrl)) {
439                 algoid = "$gy$";
440         } else if (on(UNIX_BLOWFISH_PASS, ctrl)) {
441                 algoid = "$2b$";
442         } else if (on(UNIX_SHA256_PASS, ctrl)) {
443                 algoid = "$5$";
444         } else if (on(UNIX_SHA512_PASS, ctrl)) {
445                 algoid = "$6$";
446         } else { /* must be crypt/bigcrypt */
447                 char tmppass[9];
448                 char *crypted;
449
450                 crypt_make_salt(salt, 2);
451                 if (off(UNIX_BIGCRYPT, ctrl) && strlen(password) > 8) {
452                         strncpy(tmppass, password, sizeof(tmppass)-1);
453                         tmppass[sizeof(tmppass)-1] = '\0';
454                         password = tmppass;
455                 }
456                 crypted = bigcrypt(password, salt);
457                 memset(tmppass, '\0', sizeof(tmppass));
458                 password = NULL;
459                 return crypted;
460         }
461
462 #if defined(CRYPT_GENSALT_IMPLEMENTS_AUTO_ENTROPY) && CRYPT_GENSALT_IMPLEMENTS_AUTO_ENTROPY
463         /*
464          * Any version of libcrypt supporting auto entropy is
465          * guaranteed to have crypt_gensalt_rn().
466          */
467         sp = crypt_gensalt_rn(algoid, rounds, NULL, 0, salt, sizeof(salt));
468 #else
469 #ifdef HAVE_CRYPT_GENSALT_R
470         if (on(UNIX_BLOWFISH_PASS, ctrl)) {
471                 char entropy[17];
472                 crypt_make_salt(entropy, sizeof(entropy) - 1);
473                 sp = crypt_gensalt_r (algoid, rounds,
474                                       entropy, sizeof(entropy),
475                                       salt, sizeof(salt));
476         } else {
477 #endif
478                 sp = stpcpy(salt, algoid);
479                 if (on(UNIX_ALGO_ROUNDS, ctrl)) {
480                         sp += snprintf(sp, sizeof(salt) - (16 + 1 + (sp - salt)), "rounds=%u$", rounds);
481                 }
482                 crypt_make_salt(sp, 16);
483 #ifdef HAVE_CRYPT_GENSALT_R
484         }
485 #endif
486 #endif /* CRYPT_GENSALT_IMPLEMENTS_AUTO_ENTROPY */
487 #ifdef HAVE_CRYPT_R
488         sp = NULL;
489         cdata = malloc(sizeof(*cdata));
490         if (cdata != NULL) {
491                 cdata->initialized = 0;
492                 sp = crypt_r(password, salt, cdata);
493         }
494 #else
495         sp = crypt(password, salt);
496 #endif
497         if (!sp || strncmp(algoid, sp, strlen(algoid)) != 0) {
498                 /* libxcrypt/libc doesn't know the algorithm, use MD5 */
499                 pam_syslog(pamh, LOG_ERR,
500                            "Algo %s not supported by the crypto backend, "
501                            "falling back to MD5\n",
502                            on(UNIX_YESCRYPT_PASS, ctrl) ? "yescrypt" :
503                            on(UNIX_GOST_YESCRYPT_PASS, ctrl) ? "gost_yescrypt" :
504                            on(UNIX_BLOWFISH_PASS, ctrl) ? "blowfish" :
505                            on(UNIX_SHA256_PASS, ctrl) ? "sha256" :
506                            on(UNIX_SHA512_PASS, ctrl) ? "sha512" : algoid);
507                 if(sp) {
508                    memset(sp, '\0', strlen(sp));
509                 }
510 #ifdef HAVE_CRYPT_R
511                 free(cdata);
512 #endif
513                 return crypt_md5_wrapper(password);
514         }
515         sp = x_strdup(sp);
516 #ifdef HAVE_CRYPT_R
517         free(cdata);
518 #endif
519         return sp;
520 }
521
522 #ifdef WITH_SELINUX
523 int
524 unix_selinux_confined(void)
525 {
526     static int confined = -1;
527     int fd;
528     char tempfile[]="/etc/.pwdXXXXXX";
529
530     if (confined != -1)
531         return confined;
532
533     /* cannot be confined without SELinux enabled */
534     if (!SELINUX_ENABLED){
535         confined = 0;
536         return confined;
537     }
538
539     /* let's try opening shadow read only */
540     if ((fd=open("/etc/shadow", O_RDONLY)) != -1) {
541         close(fd);
542         confined = 0;
543         return confined;
544     }
545
546     if (errno == EACCES) {
547         confined = 1;
548         return confined;
549     }
550
551     /* shadow opening failed because of other reasons let's try
552        creating a file in /etc */
553     if ((fd=mkstemp(tempfile)) != -1) {
554         unlink(tempfile);
555         close(fd);
556         confined = 0;
557         return confined;
558     }
559
560     confined = 1;
561     return confined;
562 }
563
564 #else
565 int
566 unix_selinux_confined(void)
567 {
568     return 0;
569 }
570 #endif
571
572 #ifdef USE_LCKPWDF
573 int
574 lock_pwdf(void)
575 {
576         int i;
577         int retval;
578
579 #ifndef HELPER_COMPILE
580         if (unix_selinux_confined()) {
581                 return PAM_SUCCESS;
582         }
583 #endif
584         /* These values for the number of attempts and the sleep time
585            are, of course, completely arbitrary.
586            My reading of the PAM docs is that, once pam_chauthtok() has been
587            called with PAM_UPDATE_AUTHTOK, we are obliged to take any
588            reasonable steps to make sure the token is updated; so retrying
589            for 1/10 sec. isn't overdoing it. */
590         i=0;
591         while((retval = lckpwdf()) != 0 && i < 100) {
592                 usleep(1000);
593                 i++;
594         }
595         if(retval != 0) {
596                 return PAM_AUTHTOK_LOCK_BUSY;
597         }
598         return PAM_SUCCESS;
599 }
600
601 void
602 unlock_pwdf(void)
603 {
604 #ifndef HELPER_COMPILE
605         if (unix_selinux_confined()) {
606                 return;
607         }
608 #endif
609         ulckpwdf();
610 }
611 #else
612 int
613 lock_pwdf(void)
614 {
615         return PAM_SUCCESS;
616 }
617
618 void
619 unlock_pwdf(void)
620 {
621         return;
622 }
623 #endif
624
625 #ifdef HELPER_COMPILE
626 int
627 save_old_password(const char *forwho, const char *oldpass,
628                   int howmany)
629 #else
630 int
631 save_old_password(pam_handle_t *pamh, const char *forwho, const char *oldpass,
632                   int howmany)
633 #endif
634 {
635     static char buf[16384];
636     static char nbuf[16384];
637     char *s_luser, *s_uid, *s_npas, *s_pas, *pass;
638     int npas;
639     FILE *pwfile, *opwfile;
640     int err = 0;
641     int oldmask;
642     int found = 0;
643     struct passwd *pwd = NULL;
644     struct stat st;
645     size_t len = strlen(forwho);
646 #ifdef WITH_SELINUX
647     security_context_t prev_context=NULL;
648 #endif
649
650     if (howmany < 0) {
651         return PAM_SUCCESS;
652     }
653
654     if (oldpass == NULL) {
655         return PAM_SUCCESS;
656     }
657
658     oldmask = umask(077);
659
660 #ifdef WITH_SELINUX
661     if (SELINUX_ENABLED) {
662       security_context_t passwd_context=NULL;
663       if (getfilecon("/etc/passwd",&passwd_context)<0) {
664         return PAM_AUTHTOK_ERR;
665       };
666       if (getfscreatecon(&prev_context)<0) {
667         freecon(passwd_context);
668         return PAM_AUTHTOK_ERR;
669       }
670       if (setfscreatecon(passwd_context)) {
671         freecon(passwd_context);
672         freecon(prev_context);
673         return PAM_AUTHTOK_ERR;
674       }
675       freecon(passwd_context);
676     }
677 #endif
678     pwfile = fopen(OPW_TMPFILE, "w");
679     umask(oldmask);
680     if (pwfile == NULL) {
681       err = 1;
682       goto done;
683     }
684
685     opwfile = fopen(OLD_PASSWORDS_FILE, "r");
686     if (opwfile == NULL) {
687         fclose(pwfile);
688       err = 1;
689       goto done;
690     }
691
692     if (fstat(fileno(opwfile), &st) == -1) {
693         fclose(opwfile);
694         fclose(pwfile);
695         err = 1;
696         goto done;
697     }
698
699     if (fchown(fileno(pwfile), st.st_uid, st.st_gid) == -1) {
700         fclose(opwfile);
701         fclose(pwfile);
702         err = 1;
703         goto done;
704     }
705     if (fchmod(fileno(pwfile), st.st_mode) == -1) {
706         fclose(opwfile);
707         fclose(pwfile);
708         err = 1;
709         goto done;
710     }
711
712     while (fgets(buf, 16380, opwfile)) {
713         if (!strncmp(buf, forwho, len) && strchr(":,\n", buf[len]) != NULL) {
714             char *sptr = NULL;
715             found = 1;
716             if (howmany == 0)
717                 continue;
718             buf[strlen(buf) - 1] = '\0';
719             s_luser = strtok_r(buf, ":", &sptr);
720             if (s_luser == NULL) {
721                 found = 0;
722                 continue;
723             }
724             s_uid = strtok_r(NULL, ":", &sptr);
725             if (s_uid == NULL) {
726                 found = 0;
727                 continue;
728             }
729             s_npas = strtok_r(NULL, ":", &sptr);
730             if (s_npas == NULL) {
731                 found = 0;
732                 continue;
733             }
734             s_pas = strtok_r(NULL, ":", &sptr);
735             npas = strtol(s_npas, NULL, 10) + 1;
736             while (npas > howmany && s_pas != NULL) {
737                 s_pas = strpbrk(s_pas, ",");
738                 if (s_pas != NULL)
739                     s_pas++;
740                 npas--;
741             }
742             pass = crypt_md5_wrapper(oldpass);
743             if (s_pas == NULL)
744                 snprintf(nbuf, sizeof(nbuf), "%s:%s:%d:%s\n",
745                          s_luser, s_uid, npas, pass);
746             else
747                 snprintf(nbuf, sizeof(nbuf),"%s:%s:%d:%s,%s\n",
748                          s_luser, s_uid, npas, s_pas, pass);
749             _pam_delete(pass);
750             if (fputs(nbuf, pwfile) < 0) {
751                 err = 1;
752                 break;
753             }
754         } else if (fputs(buf, pwfile) < 0) {
755             err = 1;
756             break;
757         }
758     }
759     fclose(opwfile);
760
761     if (!found) {
762         pwd = pam_modutil_getpwnam(pamh, forwho);
763         if (pwd == NULL) {
764             err = 1;
765         } else {
766             pass = crypt_md5_wrapper(oldpass);
767             snprintf(nbuf, sizeof(nbuf), "%s:%lu:1:%s\n",
768                      forwho, (unsigned long)pwd->pw_uid, pass);
769             _pam_delete(pass);
770             if (fputs(nbuf, pwfile) < 0) {
771                 err = 1;
772             }
773         }
774     }
775
776     if (fflush(pwfile) || fsync(fileno(pwfile))) {
777         D(("fflush or fsync error writing entries to old passwords file: %m"));
778         err = 1;
779     }
780
781     if (fclose(pwfile)) {
782         D(("fclose error writing entries to old passwords file: %m"));
783         err = 1;
784     }
785
786 done:
787     if (!err) {
788         if (rename(OPW_TMPFILE, OLD_PASSWORDS_FILE))
789             err = 1;
790     }
791 #ifdef WITH_SELINUX
792     if (SELINUX_ENABLED) {
793       if (setfscreatecon(prev_context)) {
794         err = 1;
795       }
796       if (prev_context)
797         freecon(prev_context);
798       prev_context=NULL;
799     }
800 #endif
801     if (!err) {
802         return PAM_SUCCESS;
803     } else {
804         unlink(OPW_TMPFILE);
805         return PAM_AUTHTOK_ERR;
806     }
807 }
808
809 PAMH_ARG_DECL(int unix_update_passwd,
810         const char *forwho, const char *towhat)
811 {
812     struct passwd *tmpent = NULL;
813     struct stat st;
814     FILE *pwfile, *opwfile;
815     int err = 1;
816     int oldmask;
817 #ifdef WITH_SELINUX
818     security_context_t prev_context=NULL;
819 #endif
820
821     oldmask = umask(077);
822 #ifdef WITH_SELINUX
823     if (SELINUX_ENABLED) {
824       security_context_t passwd_context=NULL;
825       if (getfilecon("/etc/passwd",&passwd_context)<0) {
826         return PAM_AUTHTOK_ERR;
827       };
828       if (getfscreatecon(&prev_context)<0) {
829         freecon(passwd_context);
830         return PAM_AUTHTOK_ERR;
831       }
832       if (setfscreatecon(passwd_context)) {
833         freecon(passwd_context);
834         freecon(prev_context);
835         return PAM_AUTHTOK_ERR;
836       }
837       freecon(passwd_context);
838     }
839 #endif
840     pwfile = fopen(PW_TMPFILE, "w");
841     umask(oldmask);
842     if (pwfile == NULL) {
843       err = 1;
844       goto done;
845     }
846
847     opwfile = fopen("/etc/passwd", "r");
848     if (opwfile == NULL) {
849         fclose(pwfile);
850         err = 1;
851         goto done;
852     }
853
854     if (fstat(fileno(opwfile), &st) == -1) {
855         fclose(opwfile);
856         fclose(pwfile);
857         err = 1;
858         goto done;
859     }
860
861     if (fchown(fileno(pwfile), st.st_uid, st.st_gid) == -1) {
862         fclose(opwfile);
863         fclose(pwfile);
864         err = 1;
865         goto done;
866     }
867     if (fchmod(fileno(pwfile), st.st_mode) == -1) {
868         fclose(opwfile);
869         fclose(pwfile);
870         err = 1;
871         goto done;
872     }
873
874     tmpent = fgetpwent(opwfile);
875     while (tmpent) {
876         if (!strcmp(tmpent->pw_name, forwho)) {
877             /* To shut gcc up */
878             union {
879                 const char *const_charp;
880                 char *charp;
881             } assigned_passwd;
882             assigned_passwd.const_charp = towhat;
883
884             tmpent->pw_passwd = assigned_passwd.charp;
885             err = 0;
886         }
887         if (putpwent(tmpent, pwfile)) {
888             D(("error writing entry to password file: %m"));
889             err = 1;
890             break;
891         }
892         tmpent = fgetpwent(opwfile);
893     }
894     fclose(opwfile);
895
896     if (fflush(pwfile) || fsync(fileno(pwfile))) {
897         D(("fflush or fsync error writing entries to password file: %m"));
898         err = 1;
899     }
900
901     if (fclose(pwfile)) {
902         D(("fclose error writing entries to password file: %m"));
903         err = 1;
904     }
905
906 done:
907     if (!err) {
908         if (!rename(PW_TMPFILE, "/etc/passwd"))
909             pam_syslog(pamh,
910                 LOG_NOTICE, "password changed for %s", forwho);
911         else
912             err = 1;
913     }
914 #ifdef WITH_SELINUX
915     if (SELINUX_ENABLED) {
916       if (setfscreatecon(prev_context)) {
917         err = 1;
918       }
919       if (prev_context)
920         freecon(prev_context);
921       prev_context=NULL;
922     }
923 #endif
924     if (!err) {
925         return PAM_SUCCESS;
926     } else {
927         unlink(PW_TMPFILE);
928         return PAM_AUTHTOK_ERR;
929     }
930 }
931
932 PAMH_ARG_DECL(int unix_update_shadow,
933         const char *forwho, char *towhat)
934 {
935     struct spwd spwdent, *stmpent = NULL;
936     struct stat st;
937     FILE *pwfile, *opwfile;
938     int err = 0;
939     int oldmask;
940     int wroteentry = 0;
941 #ifdef WITH_SELINUX
942     security_context_t prev_context=NULL;
943 #endif
944
945     oldmask = umask(077);
946
947 #ifdef WITH_SELINUX
948     if (SELINUX_ENABLED) {
949       security_context_t shadow_context=NULL;
950       if (getfilecon("/etc/shadow",&shadow_context)<0) {
951         return PAM_AUTHTOK_ERR;
952       };
953       if (getfscreatecon(&prev_context)<0) {
954         freecon(shadow_context);
955         return PAM_AUTHTOK_ERR;
956       }
957       if (setfscreatecon(shadow_context)) {
958         freecon(shadow_context);
959         freecon(prev_context);
960         return PAM_AUTHTOK_ERR;
961       }
962       freecon(shadow_context);
963     }
964 #endif
965     pwfile = fopen(SH_TMPFILE, "w");
966     umask(oldmask);
967     if (pwfile == NULL) {
968         err = 1;
969         goto done;
970     }
971
972     opwfile = fopen("/etc/shadow", "r");
973     if (opwfile == NULL) {
974         fclose(pwfile);
975         err = 1;
976         goto done;
977     }
978
979     if (fstat(fileno(opwfile), &st) == -1) {
980         fclose(opwfile);
981         fclose(pwfile);
982         err = 1;
983         goto done;
984     }
985
986     if (fchown(fileno(pwfile), st.st_uid, st.st_gid) == -1) {
987         fclose(opwfile);
988         fclose(pwfile);
989         err = 1;
990         goto done;
991     }
992     if (fchmod(fileno(pwfile), st.st_mode) == -1) {
993         fclose(opwfile);
994         fclose(pwfile);
995         err = 1;
996         goto done;
997     }
998
999     stmpent = fgetspent(opwfile);
1000     while (stmpent) {
1001
1002         if (!strcmp(stmpent->sp_namp, forwho)) {
1003             stmpent->sp_pwdp = towhat;
1004             stmpent->sp_lstchg = time(NULL) / (60 * 60 * 24);
1005             if (stmpent->sp_lstchg == 0)
1006                 stmpent->sp_lstchg = -1; /* Don't request passwort change
1007                                             only because time isn't set yet. */
1008             wroteentry = 1;
1009             D(("Set password %s for %s", stmpent->sp_pwdp, forwho));
1010         }
1011
1012         if (putspent(stmpent, pwfile)) {
1013             D(("error writing entry to shadow file: %m"));
1014             err = 1;
1015             break;
1016         }
1017
1018         stmpent = fgetspent(opwfile);
1019     }
1020
1021     fclose(opwfile);
1022
1023     if (!wroteentry && !err) {
1024         spwdent.sp_namp = (char *)forwho;
1025         spwdent.sp_pwdp = towhat;
1026         spwdent.sp_lstchg = time(NULL) / (60 * 60 * 24);
1027         if (spwdent.sp_lstchg == 0)
1028             spwdent.sp_lstchg = -1; /* Don't request passwort change
1029                                        only because time isn't set yet. */
1030         spwdent.sp_min = spwdent.sp_max = spwdent.sp_warn = spwdent.sp_inact =
1031             spwdent.sp_expire = -1;
1032         spwdent.sp_flag = (unsigned long)-1l;
1033         if (putspent(&spwdent, pwfile)) {
1034             D(("error writing entry to shadow file: %m"));
1035             err = 1;
1036         }
1037     }
1038
1039     if (fflush(pwfile) || fsync(fileno(pwfile))) {
1040         D(("fflush or fsync error writing entries to shadow file: %m"));
1041         err = 1;
1042     }
1043
1044     if (fclose(pwfile)) {
1045         D(("fclose error writing entries to shadow file: %m"));
1046         err = 1;
1047     }
1048
1049  done:
1050     if (!err) {
1051         if (!rename(SH_TMPFILE, "/etc/shadow"))
1052             pam_syslog(pamh,
1053                 LOG_NOTICE, "password changed for %s", forwho);
1054         else
1055             err = 1;
1056     }
1057
1058 #ifdef WITH_SELINUX
1059     if (SELINUX_ENABLED) {
1060       if (setfscreatecon(prev_context)) {
1061         err = 1;
1062       }
1063       if (prev_context)
1064         freecon(prev_context);
1065       prev_context=NULL;
1066     }
1067 #endif
1068
1069     if (!err) {
1070         return PAM_SUCCESS;
1071     } else {
1072         unlink(SH_TMPFILE);
1073         return PAM_AUTHTOK_ERR;
1074     }
1075 }
1076
1077 #ifdef HELPER_COMPILE
1078
1079 int
1080 helper_verify_password(const char *name, const char *p, int nullok)
1081 {
1082         struct passwd *pwd = NULL;
1083         char *salt = NULL;
1084         int retval;
1085
1086         retval = get_pwd_hash(name, &pwd, &salt);
1087
1088         if (pwd == NULL || salt == NULL) {
1089                 helper_log_err(LOG_NOTICE, "check pass; user unknown");
1090                 retval = PAM_USER_UNKNOWN;
1091         } else {
1092                 retval = verify_pwd_hash(p, salt, nullok);
1093         }
1094
1095         if (salt) {
1096                 _pam_overwrite(salt);
1097                 _pam_drop(salt);
1098         }
1099
1100         p = NULL;               /* no longer needed here */
1101
1102         return retval;
1103 }
1104
1105 void
1106 helper_log_err(int err, const char *format, ...)
1107 {
1108         va_list args;
1109
1110         va_start(args, format);
1111         openlog(HELPER_COMPILE, LOG_CONS | LOG_PID, LOG_AUTHPRIV);
1112         vsyslog(err, format, args);
1113         va_end(args);
1114         closelog();
1115 }
1116
1117 static void
1118 su_sighandler(int sig)
1119 {
1120 #ifndef SA_RESETHAND
1121         /* emulate the behaviour of the SA_RESETHAND flag */
1122         if ( sig == SIGILL || sig == SIGTRAP || sig == SIGBUS || sig = SIGSERV ) {
1123                 struct sigaction sa;
1124                 memset(&sa, '\0', sizeof(sa));
1125                 sa.sa_handler = SIG_DFL;
1126                 sigaction(sig, &sa, NULL);
1127         }
1128 #endif
1129         if (sig > 0) {
1130                 _exit(sig);
1131         }
1132 }
1133
1134 void
1135 setup_signals(void)
1136 {
1137         struct sigaction action;        /* posix signal structure */
1138
1139         /*
1140          * Setup signal handlers
1141          */
1142         (void) memset((void *) &action, 0, sizeof(action));
1143         action.sa_handler = su_sighandler;
1144 #ifdef SA_RESETHAND
1145         action.sa_flags = SA_RESETHAND;
1146 #endif
1147         (void) sigaction(SIGILL, &action, NULL);
1148         (void) sigaction(SIGTRAP, &action, NULL);
1149         (void) sigaction(SIGBUS, &action, NULL);
1150         (void) sigaction(SIGSEGV, &action, NULL);
1151         action.sa_handler = SIG_IGN;
1152         action.sa_flags = 0;
1153         (void) sigaction(SIGTERM, &action, NULL);
1154         (void) sigaction(SIGHUP, &action, NULL);
1155         (void) sigaction(SIGINT, &action, NULL);
1156         (void) sigaction(SIGQUIT, &action, NULL);
1157 }
1158
1159 char *
1160 getuidname(uid_t uid)
1161 {
1162         struct passwd *pw;
1163         static char username[256];
1164
1165         pw = getpwuid(uid);
1166         if (pw == NULL)
1167                 return NULL;
1168
1169         strncpy(username, pw->pw_name, sizeof(username));
1170         username[sizeof(username) - 1] = '\0';
1171
1172         return username;
1173 }
1174
1175 int
1176 read_passwords(int fd, int npass, char **passwords)
1177 {
1178         /* The passwords array must contain npass preallocated
1179          * buffers of length MAXPASS + 1
1180          */
1181         int rbytes = 0;
1182         int offset = 0;
1183         int i = 0;
1184         char *pptr;
1185         while (npass > 0) {
1186                 rbytes = read(fd, passwords[i]+offset, MAXPASS+1-offset);
1187
1188                 if (rbytes < 0) {
1189                         if (errno == EINTR) continue;
1190                         break;
1191                 }
1192                 if (rbytes == 0)
1193                         break;
1194
1195                 while (npass > 0 && (pptr=memchr(passwords[i]+offset, '\0', rbytes))
1196                         != NULL) {
1197                         rbytes -= pptr - (passwords[i]+offset) + 1;
1198                         i++;
1199                         offset = 0;
1200                         npass--;
1201                         if (rbytes > 0) {
1202                                 if (npass > 0)
1203                                         memcpy(passwords[i], pptr+1, rbytes);
1204                                 memset(pptr+1, '\0', rbytes);
1205                         }
1206                 }
1207                 offset += rbytes;
1208         }
1209
1210         /* clear up */
1211         if (offset > 0 && npass > 0) {
1212                 memset(passwords[i], '\0', offset);
1213         }
1214
1215         return i;
1216 }
1217
1218 #endif
1219 /* ****************************************************************** *
1220  * Copyright (c) Jan RÄ™korajski 1999.
1221  * Copyright (c) Andrew G. Morgan 1996-8.
1222  * Copyright (c) Alex O. Yuriev, 1996.
1223  * Copyright (c) Cristian Gafton 1996.
1224  * Copyright (c) Red Hat, Inc. 1996, 2007, 2008.
1225  *
1226  * Redistribution and use in source and binary forms, with or without
1227  * modification, are permitted provided that the following conditions
1228  * are met:
1229  * 1. Redistributions of source code must retain the above copyright
1230  *    notice, and the entire permission notice in its entirety,
1231  *    including the disclaimer of warranties.
1232  * 2. Redistributions in binary form must reproduce the above copyright
1233  *    notice, this list of conditions and the following disclaimer in the
1234  *    documentation and/or other materials provided with the distribution.
1235  * 3. The name of the author may not be used to endorse or promote
1236  *    products derived from this software without specific prior
1237  *    written permission.
1238  *
1239  * ALTERNATIVELY, this product may be distributed under the terms of
1240  * the GNU Public License, in which case the provisions of the GPL are
1241  * required INSTEAD OF the above restrictions.  (This clause is
1242  * necessary due to a potential bad interaction between the GPL and
1243  * the restrictions contained in a BSD-style copyright.)
1244  *
1245  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
1246  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1247  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1248  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
1249  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
1250  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1251  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1252  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
1253  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
1254  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
1255  * OF THE POSSIBILITY OF SUCH DAMAGE.
1256  */