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