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