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