From http://www.jwz.org/xscreensaver/xscreensaver-5.35.tar.gz
[xscreensaver] / driver / passwd-pam.c
1 /* passwd-pam.c --- verifying typed passwords with PAM
2  * (Pluggable Authentication Modules.)
3  * written by Bill Nottingham <notting@redhat.com> (and jwz) for
4  * xscreensaver, Copyright (c) 1993-2016 Jamie Zawinski <jwz@jwz.org>
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation.  No representations are made about the suitability of this
11  * software for any purpose.  It is provided "as is" without express or 
12  * implied warranty.
13  *
14  * Some PAM resources:
15  *
16  *    PAM home page:
17  *    http://www.us.kernel.org/pub/linux/libs/pam/
18  *
19  *    PAM FAQ:
20  *    http://www.us.kernel.org/pub/linux/libs/pam/FAQ
21  *
22  *    PAM Application Developers' Guide:
23  *    http://www.us.kernel.org/pub/linux/libs/pam/Linux-PAM-html/Linux-PAM_ADG.html
24  *
25  *    PAM Mailing list archives:
26  *    http://www.linuxhq.com/lnxlists/linux-pam/
27  *
28  *    Compatibility notes, especially between Linux and Solaris:
29  *    http://www.contrib.andrew.cmu.edu/u/shadow/pam.html
30  *
31  *    The Open Group's PAM API documentation:
32  *    http://www.opengroup.org/onlinepubs/8329799/pam_start.htm
33  */
34
35 #ifdef HAVE_CONFIG_H
36 # include "config.h"
37 #endif
38
39 #ifndef NO_LOCKING  /* whole file */
40
41 #include <stdlib.h>
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
45
46 extern char *blurb(void);
47
48
49 #include <stdio.h>
50 #include <string.h>
51 #include <sys/types.h>
52 #include <pwd.h>
53 #include <grp.h>
54 #include <security/pam_appl.h>
55 #include <signal.h>
56 #include <errno.h>
57 #include <X11/Intrinsic.h>
58
59 #include <sys/stat.h>
60
61 #include "auth.h"
62
63 extern sigset_t block_sigchld (void);
64 extern void unblock_sigchld (void);
65
66 /* blargh */
67 #undef  Bool
68 #undef  True
69 #undef  False
70 #define Bool  int
71 #define True  1
72 #define False 0
73
74 #undef countof
75 #define countof(x) (sizeof((x))/sizeof(*(x)))
76
77 /* Some time between Red Hat 4.2 and 7.0, the words were transposed 
78    in the various PAM_x_CRED macro names.  Yay!
79  */
80 #if !defined(PAM_REFRESH_CRED) && defined(PAM_CRED_REFRESH)
81 # define PAM_REFRESH_CRED PAM_CRED_REFRESH
82 #endif
83 #if !defined(PAM_REINITIALIZE_CRED) && defined(PAM_CRED_REINITIALIZE)
84 # define PAM_REINITIALIZE_CRED PAM_CRED_REINITIALIZE
85 #endif
86
87 static int pam_conversation (int nmsgs,
88                              const struct pam_message **msg,
89                              struct pam_response **resp,
90                              void *closure);
91
92 void pam_try_unlock(saver_info *si, Bool verbose_p,
93                Bool (*valid_p)(const char *typed_passwd, Bool verbose_p));
94
95 Bool pam_priv_init (int argc, char **argv, Bool verbose_p);
96
97 #ifdef HAVE_PAM_FAIL_DELAY
98    /* We handle delays ourself.*/
99    /* Don't set this to 0 (Linux bug workaround.) */
100 # define PAM_NO_DELAY(pamh) pam_fail_delay ((pamh), 1)
101 #else  /* !HAVE_PAM_FAIL_DELAY */
102 # define PAM_NO_DELAY(pamh) /* */
103 #endif /* !HAVE_PAM_FAIL_DELAY */
104
105
106 /* On SunOS 5.6, and on Linux with PAM 0.64, pam_strerror() takes two args.
107    On some other Linux systems with some other version of PAM (e.g.,
108    whichever Debian release comes with a 2.2.5 kernel) it takes one arg.
109    I can't tell which is more "recent" or "correct" behavior, so configure
110    figures out which is in use for us.  Shoot me!
111  */
112 #ifdef PAM_STRERROR_TWO_ARGS
113 # define PAM_STRERROR(pamh, status) pam_strerror((pamh), (status))
114 #else  /* !PAM_STRERROR_TWO_ARGS */
115 # define PAM_STRERROR(pamh, status) pam_strerror((status))
116 #endif /* !PAM_STRERROR_TWO_ARGS */
117
118
119 /* PAM sucks in that there is no way to tell whether a particular service
120    is configured at all.  That is, there is no way to tell the difference
121    between "authentication of the FOO service is not allowed" and "the
122    user typed the wrong password."
123
124    On RedHat 5.1 systems, if a service name is not known, it defaults to
125    being not allowed (because the fallback service, /etc/pam.d/other, is
126    set to `pam_deny'.)
127
128    On Solaris 2.6 systems, unknown services default to authenticating normally.
129
130    So, we could simply require that the person who installs xscreensaver
131    set up an "xscreensaver" PAM service.  However, if we went that route,
132    it would have a really awful failure mode: the failure mode would be that
133    xscreensaver was willing to *lock* the screen, but would be unwilling to
134    *unlock* the screen.  (With the non-PAM password code, the analagous
135    situation -- security not being configured properly, for example do to the
136    executable not being installed as setuid root -- the failure mode is much
137    more palettable, in that xscreensaver will refuse to *lock* the screen,
138    because it can know up front that there is no password that will work.)
139
140    Another route would be to have the service name to consult be computed at
141    compile-time (perhaps with a configure option.)  However, that doesn't
142    really solve the problem, because it means that the same executable might
143    work fine on one machine, but refuse to unlock when run on another
144    machine.
145
146    Another alternative would be to look in /etc/pam.conf or /etc/pam.d/ at
147    runtime to see what services actually exist.  But I think that's no good,
148    because who is to say that the PAM info is actually specified in those
149    files?  Opening and reading those files is not a part of the PAM client
150    API, so it's not guarenteed to work on any given system.
151
152    An alternative I tried was to specify a list of services to try, and to
153    try them all in turn ("xscreensaver", "xlock", "xdm", and "login").
154    This worked, but it was slow (and I also had to do some contortions to
155    work around bugs in Linux PAM 0.64-3.)
156
157    So what we do today is, try PAM once, and if that fails, try the usual
158    getpwent() method.  So if PAM doesn't work, it will at least make an
159    attempt at looking up passwords in /etc/passwd or /etc/shadow instead.
160
161    This all kind of blows.  I'm not sure what else to do.
162  */
163
164
165 /* On SunOS 5.6, the `pam_conv.appdata_ptr' slot seems to be ignored, and
166    the `closure' argument to pc.conv always comes in as random garbage.
167    So we get around this by using a global variable instead.  Shoot me!
168
169    (I've been told this is bug 4092227, and is fixed in Solaris 7.)
170    (I've also been told that it's fixed in Solaris 2.6 by patch 106257-05.)
171  */
172 static void *suns_pam_implementation_blows = 0;
173
174
175 /**
176  * This function is the PAM conversation driver. It conducts a full
177  * authentication round by invoking the GUI with various prompts.
178  */
179 void
180 pam_try_unlock(saver_info *si, Bool verbose_p,
181                Bool (*valid_p)(const char *typed_passwd, Bool verbose_p))
182 {
183   const char *service = PAM_SERVICE_NAME;
184   pam_handle_t *pamh = 0;
185   int status = -1;
186   struct pam_conv pc;
187   sigset_t set;
188   struct timespec timeout;
189
190   pc.conv = &pam_conversation;
191   pc.appdata_ptr = (void *) si;
192
193   /* On SunOS 5.6, the `appdata_ptr' slot seems to be ignored, and the
194      `closure' argument to pc.conv always comes in as random garbage. */
195   suns_pam_implementation_blows = (void *) si;
196
197
198   /* Initialize PAM.
199    */
200   status = pam_start (service, si->user, &pc, &pamh);
201   if (verbose_p)
202     fprintf (stderr, "%s: pam_start (\"%s\", \"%s\", ...) ==> %d (%s)\n",
203              blurb(), service, si->user,
204              status, PAM_STRERROR (pamh, status));
205   if (status != PAM_SUCCESS) goto DONE;
206
207   /* #### We should set PAM_TTY to the display we're using, but we
208      don't have that handy from here.  So set it to :0.0, which is a
209      good guess (and has the bonus of counting as a "secure tty" as
210      far as PAM is concerned...)
211    */
212   {
213     char *tty = strdup (":0.0");
214     status = pam_set_item (pamh, PAM_TTY, tty);
215     if (verbose_p)
216       fprintf (stderr, "%s:   pam_set_item (p, PAM_TTY, \"%s\") ==> %d (%s)\n",
217                blurb(), tty, status, PAM_STRERROR(pamh, status));
218     free (tty);
219   }
220
221   /* Try to authenticate as the current user.
222      We must turn off our SIGCHLD handler for the duration of the call to
223      pam_authenticate(), because in some cases, the underlying PAM code
224      will do this:
225
226         1: fork a setuid subprocess to do some dirty work;
227         2: read a response from that subprocess;
228         3: waitpid(pid, ...) on that subprocess.
229
230     If we (the ignorant parent process) have a SIGCHLD handler, then there's
231     a race condition between steps 2 and 3: if the subprocess exits before
232     waitpid() was called, then our SIGCHLD handler fires, and gets notified
233     of the subprocess death; then PAM's call to waitpid() fails, because the
234     process has already been reaped.
235
236     I consider this a bug in PAM, since the caller should be able to have
237     whatever signal handlers it wants -- the PAM documentation doesn't say
238     "oh by the way, if you use PAM, you can't use SIGCHLD."
239    */
240
241   PAM_NO_DELAY(pamh);
242
243   if (verbose_p)
244     fprintf (stderr, "%s:   pam_authenticate (...) ...\n", blurb());
245
246   timeout.tv_sec = 0;
247   timeout.tv_nsec = 1;
248   set = block_sigchld();
249   status = pam_authenticate (pamh, 0);
250 # ifdef HAVE_SIGTIMEDWAIT
251   sigtimedwait (&set, NULL, &timeout);
252   /* #### What is the portable thing to do if we don't have it? */
253 # endif /* HAVE_SIGTIMEDWAIT */
254   unblock_sigchld();
255
256   if (verbose_p)
257     fprintf (stderr, "%s:   pam_authenticate (...) ==> %d (%s)\n",
258              blurb(), status, PAM_STRERROR(pamh, status));
259
260   if (status == PAM_SUCCESS)  /* Win! */
261     {
262       int status2;
263
264       /* On most systems, it doesn't matter whether the account modules
265          are run, or whether they fail or succeed.
266
267          On some systems, the account modules fail, because they were
268          never configured properly, but it's necessary to run them anyway
269          because certain PAM modules depend on side effects of the account
270          modules having been run.
271
272          And on still other systems, the account modules are actually
273          used, and failures in them should be considered to be true!
274
275          So:
276          - We run the account modules on all systems.
277          - Whether we ignore them is a configure option.
278
279          It's all kind of a mess.
280        */
281       status2 = pam_acct_mgmt (pamh, 0);
282
283       if (verbose_p)
284         fprintf (stderr, "%s:   pam_acct_mgmt (...) ==> %d (%s)\n",
285                  blurb(), status2, PAM_STRERROR(pamh, status2));
286
287       /* HPUX for some reason likes to make PAM defines different from
288        * everyone else's. */
289 #ifdef PAM_AUTHTOKEN_REQD
290       if (status2 == PAM_AUTHTOKEN_REQD)
291 #else
292       if (status2 == PAM_NEW_AUTHTOK_REQD)
293 #endif
294         {
295           status2 = pam_chauthtok (pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
296           if (verbose_p)
297             fprintf (stderr, "%s: pam_chauthtok (...) ==> %d (%s)\n",
298                      blurb(), status2, PAM_STRERROR(pamh, status2));
299         }
300
301       /* If 'configure' requested that we believe the results of PAM
302          account module failures, then obey that status code.
303          Otherwise ignore it.
304        */
305 #ifdef PAM_CHECK_ACCOUNT_TYPE
306        status = status2;
307 #endif
308
309       /* Each time we successfully authenticate, refresh credentials,
310          for Kerberos/AFS/DCE/etc.  If this fails, just ignore that
311          failure and blunder along; it shouldn't matter.
312        */
313
314 #if defined(__linux__)
315       /* Apparently the Linux PAM library ignores PAM_REFRESH_CRED and only
316          refreshes credentials when using PAM_REINITIALIZE_CRED. */
317       status2 = pam_setcred (pamh, PAM_REINITIALIZE_CRED);
318 #else
319       /* But Solaris requires PAM_REFRESH_CRED or extra prompts appear. */
320       status2 = pam_setcred (pamh, PAM_REFRESH_CRED);
321 #endif
322
323       if (verbose_p)
324         fprintf (stderr, "%s:   pam_setcred (...) ==> %d (%s)\n",
325                  blurb(), status2, PAM_STRERROR(pamh, status2));
326     }
327
328  DONE:
329   if (pamh)
330     {
331       int status2 = pam_end (pamh, status);
332       pamh = 0;
333       if (verbose_p)
334         fprintf (stderr, "%s: pam_end (...) ==> %d (%s)\n",
335                  blurb(), status2,
336                  (status2 == PAM_SUCCESS ? "Success" : "Failure"));
337     }
338
339   if (status == PAM_SUCCESS)
340     si->unlock_state = ul_success;           /* yay */
341   else if (si->unlock_state == ul_cancel ||
342            si->unlock_state == ul_time)
343     ;                                        /* more specific failures ok */
344   else
345     si->unlock_state = ul_fail;              /* generic failure */
346 }
347
348
349 Bool 
350 pam_priv_init (int argc, char **argv, Bool verbose_p)
351 {
352   /* We have nothing to do at init-time.
353      However, we might as well do some error checking.
354      If "/etc/pam.d" exists and is a directory, but "/etc/pam.d/xlock"
355      does not exist, warn that PAM probably isn't going to work.
356
357      This is a priv-init instead of a non-priv init in case the directory
358      is unreadable or something (don't know if that actually happens.)
359    */
360   const char   dir[] = "/etc/pam.d";
361   const char  file[] = "/etc/pam.d/" PAM_SERVICE_NAME;
362   const char file2[] = "/etc/pam.conf";
363   struct stat st;
364
365 # ifndef S_ISDIR
366 #  define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
367 # endif
368
369   if (stat (dir, &st) == 0 && S_ISDIR(st.st_mode))
370     {
371       if (stat (file, &st) != 0)
372         fprintf (stderr,
373                  "%s: warning: %s does not exist.\n"
374                  "%s: password authentication via PAM is unlikely to work.\n",
375                  blurb(), file, blurb());
376     }
377   else if (stat (file2, &st) == 0)
378     {
379       FILE *f = fopen (file2, "r");
380       if (f)
381         {
382           Bool ok = False;
383           char buf[255];
384           while (fgets (buf, sizeof(buf), f))
385             if (strstr (buf, PAM_SERVICE_NAME))
386               {
387                 ok = True;
388                 break;
389               }
390           fclose (f);
391           if (!ok)
392             {
393               fprintf (stderr,
394                   "%s: warning: %s does not list the `%s' service.\n"
395                   "%s: password authentication via PAM is unlikely to work.\n",
396                        blurb(), file2, PAM_SERVICE_NAME, blurb());
397             }
398         }
399       /* else warn about file2 existing but being unreadable? */
400     }
401   else
402     {
403       fprintf (stderr,
404                "%s: warning: neither %s nor %s exist.\n"
405                "%s: password authentication via PAM is unlikely to work.\n",
406                blurb(), file2, file, blurb());
407     }
408
409   /* Return true anyway, just in case. */
410   return True;
411 }
412
413
414 static int
415 pam_conversation (int nmsgs,
416                   const struct pam_message **msg,
417                   struct pam_response **resp,
418                   void *vsaver_info)
419 {
420   int i, ret = -1;
421   struct auth_message *messages = 0;
422   struct auth_response *authresp = 0;
423   struct pam_response *pam_responses;
424   saver_info *si = (saver_info *) vsaver_info;
425   Bool verbose_p;
426
427   /* On SunOS 5.6, the `closure' argument always comes in as random garbage. */
428   si = (saver_info *) suns_pam_implementation_blows;
429
430   verbose_p = si->prefs.verbose_p;
431
432   /* Converting the PAM prompts into the XScreenSaver native format.
433    * It was a design goal to collapse (INFO,PROMPT) pairs from PAM
434    * into a single call to the unlock_cb function. The unlock_cb function
435    * does that, but only if it is passed several prompts at a time. Most PAM
436    * modules only send a single prompt at a time, but because there is no way
437    * of telling whether there will be more prompts to follow, we can only ever
438    * pass along whatever was passed in here.
439    */
440
441   messages = calloc(nmsgs, sizeof(struct auth_message));
442   pam_responses = calloc(nmsgs, sizeof(*pam_responses));
443   
444   if (!pam_responses || !messages)
445     goto end;
446
447   if (verbose_p)
448     fprintf (stderr, "%s:     pam_conversation (", blurb());
449
450   for (i = 0; i < nmsgs; ++i)
451     {
452       if (verbose_p && i > 0) fprintf (stderr, ", ");
453
454       messages[i].msg = msg[i]->msg;
455
456       switch (msg[i]->msg_style) {
457       case PAM_PROMPT_ECHO_OFF: messages[i].type = AUTH_MSGTYPE_PROMPT_NOECHO;
458         if (verbose_p) fprintf (stderr, "ECHO_OFF");
459         break;
460       case PAM_PROMPT_ECHO_ON:  messages[i].type = AUTH_MSGTYPE_PROMPT_ECHO;
461         if (verbose_p) fprintf (stderr, "ECHO_ON");
462         break;
463       case PAM_ERROR_MSG:       messages[i].type = AUTH_MSGTYPE_ERROR;
464         if (verbose_p) fprintf (stderr, "ERROR_MSG");
465         break;
466       case PAM_TEXT_INFO:       messages[i].type = AUTH_MSGTYPE_INFO;
467         if (verbose_p) fprintf (stderr, "TEXT_INFO");
468         break;
469       default:                  messages[i].type = AUTH_MSGTYPE_PROMPT_ECHO;
470         if (verbose_p) fprintf (stderr, "PROMPT_ECHO");
471         break;
472       }
473
474       if (verbose_p) 
475         fprintf (stderr, "=\"%s\"", msg[i]->msg ? msg[i]->msg : "(null)");
476     }
477
478   if (verbose_p)
479     fprintf (stderr, ") ...\n");
480
481   ret = si->unlock_cb(nmsgs, messages, &authresp, si);
482
483   /* #### If the user times out, or hits ESC or Cancel, we return PAM_CONV_ERR,
484           and PAM logs this as an authentication failure.  It would be nice if
485           there was some way to indicate that this was a "cancel" rather than
486           a "fail", so that it wouldn't show up in syslog, but I think the
487           only options are PAM_SUCCESS and PAM_CONV_ERR.  (I think that
488           PAM_ABORT means "internal error", not "cancel".)  Bleh.
489    */
490
491   if (ret == 0)
492     {
493       for (i = 0; i < nmsgs; ++i)
494         pam_responses[i].resp = authresp[i].response;
495     }
496
497 end:
498   if (messages)
499     free(messages);
500
501   if (authresp)
502     free(authresp);
503
504   if (verbose_p)
505     fprintf (stderr, "%s:     pam_conversation (...) ==> %s\n", blurb(),
506              (ret == 0 ? "PAM_SUCCESS" : "PAM_CONV_ERR"));
507
508   if (ret == 0)
509     {
510       *resp = pam_responses;
511       return PAM_SUCCESS;
512     }
513
514   /* Failure only */
515     if (pam_responses)
516       free(pam_responses);
517
518     return PAM_CONV_ERR;
519 }
520
521 #endif /* NO_LOCKING -- whole file */