5c4f74f2d442fa3de14b829f5c91dcab2379b6af
[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-2003 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/pam_appl.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
58 #include <sys/stat.h>
59
60 extern sigset_t block_sigchld (void);
61 extern void unblock_sigchld (void);
62
63 /* blargh */
64 #undef  Bool
65 #undef  True
66 #undef  False
67 #define Bool  int
68 #define True  1
69 #define False 0
70
71 #undef countof
72 #define countof(x) (sizeof((x))/sizeof(*(x)))
73
74 /* Some time between Red Hat 4.2 and 7.0, the words were transposed 
75    in the various PAM_x_CRED macro names.  Yay!
76  */
77 #ifndef  PAM_REFRESH_CRED
78 # define PAM_REFRESH_CRED PAM_CRED_REFRESH
79 #endif
80
81 static int pam_conversation (int nmsgs,
82                              const struct pam_message **msg,
83                              struct pam_response **resp,
84                              void *closure);
85
86 struct pam_closure {
87   const char *user;
88   const char *typed_passwd;
89   Bool verbose_p;
90 };
91
92 Bool pam_passwd_valid_p (const char *typed_passwd, Bool verbose_p);
93 Bool pam_priv_init (int argc, char **argv, Bool verbose_p);
94
95 #ifdef HAVE_PAM_FAIL_DELAY
96    /* We handle delays ourself.*/
97    /* Don't set this to 0 (Linux bug workaround.) */
98 # define PAM_NO_DELAY(pamh) pam_fail_delay ((pamh), 1)
99 #else  /* !HAVE_PAM_FAIL_DELAY */
100 # define PAM_NO_DELAY(pamh) /* */
101 #endif /* !HAVE_PAM_FAIL_DELAY */
102
103
104 /* On SunOS 5.6, and on Linux with PAM 0.64, pam_strerror() takes two args.
105    On some other Linux systems with some other version of PAM (e.g.,
106    whichever Debian release comes with a 2.2.5 kernel) it takes one arg.
107    I can't tell which is more "recent" or "correct" behavior, so configure
108    figures out which is in use for us.  Shoot me!
109  */
110 #ifdef PAM_STRERROR_TWO_ARGS
111 # define PAM_STRERROR(pamh, status) pam_strerror((pamh), (status))
112 #else  /* !PAM_STRERROR_TWO_ARGS */
113 # define PAM_STRERROR(pamh, status) pam_strerror((status))
114 #endif /* !PAM_STRERROR_TWO_ARGS */
115
116
117 /* PAM sucks in that there is no way to tell whether a particular service
118    is configured at all.  That is, there is no way to tell the difference
119    between "authentication of the FOO service is not allowed" and "the
120    user typed the wrong password."
121
122    On RedHat 5.1 systems, if a service name is not known, it defaults to
123    being not allowed (because the fallback service, /etc/pam.d/other, is
124    set to `pam_deny'.)
125
126    On Solaris 2.6 systems, unknown services default to authenticating normally.
127
128    So, we could simply require that the person who installs xscreensaver
129    set up an "xscreensaver" PAM service.  However, if we went that route,
130    it would have a really awful failure mode: the failure mode would be that
131    xscreensaver was willing to *lock* the screen, but would be unwilling to
132    *unlock* the screen.  (With the non-PAM password code, the analagous
133    situation -- security not being configured properly, for example do to the
134    executable not being installed as setuid root -- the failure mode is much
135    more palettable, in that xscreensaver will refuse to *lock* the screen,
136    because it can know up front that there is no password that will work.)
137
138    Another route would be to have the service name to consult be computed at
139    compile-time (perhaps with a configure option.)  However, that doesn't
140    really solve the problem, because it means that the same executable might
141    work fine on one machine, but refuse to unlock when run on another
142    machine.
143
144    Another alternative would be to look in /etc/pam.conf or /etc/pam.d/ at
145    runtime to see what services actually exist.  But I think that's no good,
146    because who is to say that the PAM info is actually specified in those
147    files?  Opening and reading those files is not a part of the PAM client
148    API, so it's not guarenteed to work on any given system.
149
150    An alternative I tried was to specify a list of services to try, and to
151    try them all in turn ("xscreensaver", "xlock", "xdm", and "login").
152    This worked, but it was slow (and I also had to do some contortions to
153    work around bugs in Linux PAM 0.64-3.)
154
155    So what we do today is, try PAM once, and if that fails, try the usual
156    getpwent() method.  So if PAM doesn't work, it will at least make an
157    attempt at looking up passwords in /etc/passwd or /etc/shadow instead.
158
159    This all kind of blows.  I'm not sure what else to do.
160  */
161
162
163 /* On SunOS 5.6, the `pam_conv.appdata_ptr' slot seems to be ignored, and
164    the `closure' argument to pc.conv always comes in as random garbage.
165    So we get around this by using a global variable instead.  Shoot me!
166
167    (I've been told this is bug 4092227, and is fixed in Solaris 7.)
168    (I've also been told that it's fixed in Solaris 2.6 by patch 106257-05.)
169  */
170 static void *suns_pam_implementation_blows = 0;
171
172
173 /* This can be called at any time, and says whether the typed password
174    belongs to either the logged in user (real uid, not effective); or
175    to root.
176  */
177 Bool
178 pam_passwd_valid_p (const char *typed_passwd, Bool verbose_p)
179 {
180   const char *service = PAM_SERVICE_NAME;
181   pam_handle_t *pamh = 0;
182   int status = -1;
183   struct pam_conv pc;
184   struct pam_closure c;
185   char *user = 0;
186   sigset_t set;
187   struct timespec timeout;
188
189   struct passwd *p = getpwuid (getuid ());
190   if (!p) return False;
191
192   user = strdup (p->pw_name);
193
194   c.user = user;
195   c.typed_passwd = typed_passwd;
196   c.verbose_p = verbose_p;
197
198   pc.conv = &pam_conversation;
199   pc.appdata_ptr = (void *) &c;
200
201   /* On SunOS 5.6, the `appdata_ptr' slot seems to be ignored, and the
202      `closure' argument to pc.conv always comes in as random garbage. */
203   suns_pam_implementation_blows = (void *) &c;
204
205
206   /* Initialize PAM.
207    */
208   status = pam_start (service, c.user, &pc, &pamh);
209   if (verbose_p)
210     fprintf (stderr, "%s: pam_start (\"%s\", \"%s\", ...) ==> %d (%s)\n",
211              blurb(), service, c.user,
212              status, PAM_STRERROR (pamh, status));
213   if (status != PAM_SUCCESS) goto DONE;
214
215   /* #### We should set PAM_TTY to the display we're using, but we
216      don't have that handy from here.  So set it to :0.0, which is a
217      good guess (and has the bonus of counting as a "secure tty" as
218      far as PAM is concerned...)
219    */
220   {
221     char *tty = strdup (":0.0");
222     status = pam_set_item (pamh, PAM_TTY, tty);
223     if (verbose_p)
224       fprintf (stderr, "%s:   pam_set_item (p, PAM_TTY, \"%s\") ==> %d (%s)\n",
225                blurb(), tty, status, PAM_STRERROR(pamh, status));
226     free (tty);
227   }
228
229   /* Try to authenticate as the current user.
230      We must turn off our SIGCHLD handler for the duration of the call to
231      pam_authenticate(), because in some cases, the underlying PAM code
232      will do this:
233
234         1: fork a setuid subprocess to do some dirty work;
235         2: read a response from that subprocess;
236         3: waitpid(pid, ...) on that subprocess.
237
238     If we (the ignorant parent process) have a SIGCHLD handler, then there's
239     a race condition between steps 2 and 3: if the subprocess exits before
240     waitpid() was called, then our SIGCHLD handler fires, and gets notified
241     of the subprocess death; then PAM's call to waitpid() fails, because the
242     process has already been reaped.
243
244     I consider this a bug in PAM, since the caller should be able to have
245     whatever signal handlers it wants -- the PAM documentation doesn't say
246     "oh by the way, if you use PAM, you can't use SIGCHLD."
247    */
248
249   PAM_NO_DELAY(pamh);
250
251   timeout.tv_sec = 0;
252   timeout.tv_nsec = 1;
253   set = block_sigchld();
254   status = pam_authenticate (pamh, 0);
255   sigtimedwait (&set, NULL, &timeout);
256   unblock_sigchld();
257
258   if (verbose_p)
259     fprintf (stderr, "%s:   pam_authenticate (...) ==> %d (%s)\n",
260              blurb(), status, PAM_STRERROR(pamh, status));
261   if (status == PAM_SUCCESS)  /* Win! */
262     {
263       int status2;
264
265       /* We don't actually care if the account modules fail or succeed,
266        * but we need to run them anyway because certain pam modules
267        * depend on side effects of the account modules getting run.
268        */
269       status2 = pam_acct_mgmt (pamh, 0);
270
271       if (verbose_p)
272         fprintf (stderr, "%s:   pam_acct_mgmt (...) ==> %d (%s)\n",
273                  blurb(), status2, PAM_STRERROR(pamh, status2));
274
275       /* Each time we successfully authenticate, refresh credentials,
276          for Kerberos/AFS/DCE/etc.  If this fails, just ignore that
277          failure and blunder along; it shouldn't matter.
278
279          Note: this used to be PAM_REFRESH_CRED instead of
280          PAM_REINITIALIZE_CRED, but Jason Heiss <jheiss@ee.washington.edu>
281          says that the Linux PAM library ignores that one, and only refreshes
282          credentials when using PAM_REINITIALIZE_CRED.
283        */
284       status2 = pam_setcred (pamh, PAM_REINITIALIZE_CRED);
285       if (verbose_p)
286         fprintf (stderr, "%s:   pam_setcred (...) ==> %d (%s)\n",
287                  blurb(), status2, PAM_STRERROR(pamh, status2));
288       goto DONE;
289     }
290
291   /* If that didn't work, set the user to root, and try to authenticate again.
292    */
293   if (user) free (user);
294   user = strdup ("root");
295   c.user = user;
296   status = pam_set_item (pamh, PAM_USER, c.user);
297   if (verbose_p)
298     fprintf (stderr, "%s:   pam_set_item(p, PAM_USER, \"%s\") ==> %d (%s)\n",
299              blurb(), c.user, status, PAM_STRERROR(pamh, status));
300   if (status != PAM_SUCCESS) goto DONE;
301
302   PAM_NO_DELAY(pamh);
303
304   set = block_sigchld();
305   status = pam_authenticate (pamh, 0);
306   sigtimedwait(&set, NULL, &timeout);
307   unblock_sigchld();
308
309   if (verbose_p)
310     fprintf (stderr, "%s:   pam_authenticate (...) ==> %d (%s)\n",
311              blurb(), status, PAM_STRERROR(pamh, status));
312
313  DONE:
314   if (user) free (user);
315   if (pamh)
316     {
317       int status2 = pam_end (pamh, status);
318       pamh = 0;
319       if (verbose_p)
320         fprintf (stderr, "%s: pam_end (...) ==> %d (%s)\n",
321                  blurb(), status2,
322                  (status2 == PAM_SUCCESS ? "Success" : "Failure"));
323     }
324   return (status == PAM_SUCCESS ? True : False);
325 }
326
327
328 Bool 
329 pam_priv_init (int argc, char **argv, Bool verbose_p)
330 {
331   /* We have nothing to do at init-time.
332      However, we might as well do some error checking.
333      If "/etc/pam.d" exists and is a directory, but "/etc/pam.d/xlock"
334      does not exist, warn that PAM probably isn't going to work.
335
336      This is a priv-init instead of a non-priv init in case the directory
337      is unreadable or something (don't know if that actually happens.)
338    */
339   const char   dir[] = "/etc/pam.d";
340   const char  file[] = "/etc/pam.d/" PAM_SERVICE_NAME;
341   const char file2[] = "/etc/pam.conf";
342   struct stat st;
343
344 # ifndef S_ISDIR
345 #  define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
346 # endif
347
348   if (stat (dir, &st) == 0 && S_ISDIR(st.st_mode))
349     {
350       if (stat (file, &st) != 0)
351         fprintf (stderr,
352                  "%s: warning: %s does not exist.\n"
353                  "%s: password authentication via PAM is unlikely to work.\n",
354                  blurb(), file, blurb());
355     }
356   else if (stat (file2, &st) == 0)
357     {
358       FILE *f = fopen (file2, "r");
359       if (f)
360         {
361           Bool ok = False;
362           char buf[255];
363           while (fgets (buf, sizeof(buf), f))
364             if (strstr (buf, PAM_SERVICE_NAME))
365               {
366                 ok = True;
367                 break;
368               }
369           fclose (f);
370           if (!ok)
371             {
372               fprintf (stderr,
373                   "%s: warning: %s does not list the `%s' service.\n"
374                   "%s: password authentication via PAM is unlikely to work.\n",
375                        blurb(), file2, PAM_SERVICE_NAME, blurb());
376             }
377         }
378       /* else warn about file2 existing but being unreadable? */
379     }
380   else
381     {
382       fprintf (stderr,
383                "%s: warning: neither %s nor %s exist.\n"
384                "%s: password authentication via PAM is unlikely to work.\n",
385                blurb(), file2, file, blurb());
386     }
387
388   /* Return true anyway, just in case. */
389   return True;
390 }
391
392
393 /* This is the function PAM calls to have a conversation with the user.
394    Really, this function should be the thing that pops up dialog boxes
395    as needed, and prompts for various strings.
396
397    But, for now, xscreensaver uses its normal password-prompting dialog
398    first, and then this function simply returns the result that has been
399    typed.
400
401    This means that if PAM was using a retina scanner for auth, xscreensaver
402    would prompt for a password; then pam_conversation() would be called
403    with a string like "Please look into the retina scanner".  The user
404    would never see this string, and the prompted-for password would be
405    ignored.
406  */
407 static int
408 pam_conversation (int nmsgs,
409                   const struct pam_message **msg,
410                   struct pam_response **resp,
411                   void *closure)
412 {
413   int replies = 0;
414   struct pam_response *reply = 0;
415   struct pam_closure *c = (struct pam_closure *) closure;
416
417   /* On SunOS 5.6, the `closure' argument always comes in as random garbage. */
418   c = (struct pam_closure *) suns_pam_implementation_blows;
419
420
421   reply = (struct pam_response *) calloc (nmsgs, sizeof (*reply));
422   if (!reply) return PAM_CONV_ERR;
423         
424   for (replies = 0; replies < nmsgs; replies++)
425     {
426       switch (msg[replies]->msg_style)
427         {
428         case PAM_PROMPT_ECHO_ON:
429           reply[replies].resp_retcode = PAM_SUCCESS;
430           reply[replies].resp = strdup (c->user);          /* freed by PAM */
431           if (c->verbose_p)
432             fprintf (stderr, "%s:     PAM ECHO_ON(\"%s\") ==> \"%s\"\n",
433                      blurb(), msg[replies]->msg,
434                      reply[replies].resp);
435           break;
436         case PAM_PROMPT_ECHO_OFF:
437           reply[replies].resp_retcode = PAM_SUCCESS;
438           reply[replies].resp = strdup (c->typed_passwd);   /* freed by PAM */
439           if (c->verbose_p)
440             fprintf (stderr, "%s:     PAM ECHO_OFF(\"%s\") ==> password\n",
441                      blurb(), msg[replies]->msg);
442           break;
443         case PAM_TEXT_INFO:
444           /* ignore it... */
445           reply[replies].resp_retcode = PAM_SUCCESS;
446           reply[replies].resp = 0;
447           if (c->verbose_p)
448             fprintf (stderr, "%s:     PAM TEXT_INFO(\"%s\") ==> ignored\n",
449                      blurb(), msg[replies]->msg);
450           break;
451         case PAM_ERROR_MSG:
452           /* ignore it... */
453           reply[replies].resp_retcode = PAM_SUCCESS;
454           reply[replies].resp = 0;
455           if (c->verbose_p)
456             fprintf (stderr, "%s:     PAM ERROR_MSG(\"%s\") ==> ignored\n",
457                      blurb(), msg[replies]->msg);
458           break;
459         default:
460           /* Must be an error of some sort... */
461           free (reply);
462           if (c->verbose_p)
463             fprintf (stderr, "%s:     PAM unknown %d(\"%s\") ==> ignored\n",
464                      blurb(), msg[replies]->msg_style, msg[replies]->msg);
465           return PAM_CONV_ERR;
466         }
467     }
468   *resp = reply;
469   return PAM_SUCCESS;
470 }
471
472 #endif /* NO_LOCKING -- whole file */