]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/auth-pam.c
This commit was generated by cvs2svn to compensate for changes in r147341,
[FreeBSD/FreeBSD.git] / crypto / openssh / auth-pam.c
1 /*-
2  * Copyright (c) 2002 Networks Associates Technology, Inc.
3  * All rights reserved.
4  *
5  * This software was developed for the FreeBSD Project by ThinkSec AS and
6  * NAI Labs, the Security Research Division of Network Associates, Inc.
7  * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
8  * DARPA CHATS research program.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 /*
32  * Copyright (c) 2003,2004 Damien Miller <djm@mindrot.org>
33  * Copyright (c) 2003,2004 Darren Tucker <dtucker@zip.com.au>
34  *
35  * Permission to use, copy, modify, and distribute this software for any
36  * purpose with or without fee is hereby granted, provided that the above
37  * copyright notice and this permission notice appear in all copies.
38  *
39  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
40  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
41  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
42  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
43  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
44  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
45  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
46  */
47
48 /* Based on $xFreeBSD: src/crypto/openssh/auth2-pam-freebsd.c,v 1.11 2003/03/31 13:48:18 des Exp $ */
49 #include "includes.h"
50 RCSID("$Id: auth-pam.c,v 1.122 2005/05/25 06:18:10 dtucker Exp $");
51 RCSID("$FreeBSD$");
52
53 #ifdef USE_PAM
54 #if defined(HAVE_SECURITY_PAM_APPL_H)
55 #include <security/pam_appl.h>
56 #elif defined (HAVE_PAM_PAM_APPL_H)
57 #include <pam/pam_appl.h>
58 #endif
59
60 #include "auth.h"
61 #include "auth-pam.h"
62 #include "buffer.h"
63 #include "bufaux.h"
64 #include "canohost.h"
65 #include "log.h"
66 #include "monitor_wrap.h"
67 #include "msg.h"
68 #include "packet.h"
69 #include "misc.h"
70 #include "servconf.h"
71 #include "ssh2.h"
72 #include "xmalloc.h"
73 #include "auth-options.h"
74
75 extern ServerOptions options;
76 extern Buffer loginmsg;
77 extern int compat20;
78 extern u_int utmp_len;
79
80 /* so we don't silently change behaviour */
81 #ifdef USE_POSIX_THREADS
82 # error "USE_POSIX_THREADS replaced by UNSUPPORTED_POSIX_THREADS_HACK"
83 #endif
84
85 /*
86  * Formerly known as USE_POSIX_THREADS, using this is completely unsupported
87  * and generally a bad idea.  Use at own risk and do not expect support if
88  * this breaks.
89  */
90 #ifdef UNSUPPORTED_POSIX_THREADS_HACK
91 #include <pthread.h>
92 /*
93  * Avoid namespace clash when *not* using pthreads for systems *with*
94  * pthreads, which unconditionally define pthread_t via sys/types.h
95  * (e.g. Linux)
96  */
97 typedef pthread_t sp_pthread_t;
98 #else
99 typedef pid_t sp_pthread_t;
100 #endif
101
102 struct pam_ctxt {
103         sp_pthread_t     pam_thread;
104         int              pam_psock;
105         int              pam_csock;
106         int              pam_done;
107 };
108
109 static void sshpam_free_ctx(void *);
110 static struct pam_ctxt *cleanup_ctxt;
111
112 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
113 /*
114  * Simulate threads with processes.
115  */
116
117 static int sshpam_thread_status = -1;
118 static mysig_t sshpam_oldsig;
119
120 static void 
121 sshpam_sigchld_handler(int sig)
122 {
123         signal(SIGCHLD, SIG_DFL);
124         if (cleanup_ctxt == NULL)
125                 return; /* handler called after PAM cleanup, shouldn't happen */
126         if (waitpid(cleanup_ctxt->pam_thread, &sshpam_thread_status, WNOHANG)
127              <= 0) {
128                 /* PAM thread has not exitted, privsep slave must have */
129                 kill(cleanup_ctxt->pam_thread, SIGTERM);
130                 if (waitpid(cleanup_ctxt->pam_thread, &sshpam_thread_status, 0)
131                     <= 0)
132                         return; /* could not wait */
133         }
134         if (WIFSIGNALED(sshpam_thread_status) &&
135             WTERMSIG(sshpam_thread_status) == SIGTERM)
136                 return; /* terminated by pthread_cancel */
137         if (!WIFEXITED(sshpam_thread_status))
138                 fatal("PAM: authentication thread exited unexpectedly");
139         if (WEXITSTATUS(sshpam_thread_status) != 0)
140                 fatal("PAM: authentication thread exited uncleanly");
141 }
142
143 static void
144 pthread_exit(void *value __unused)
145 {
146         _exit(0);
147 }
148
149 static int
150 pthread_create(sp_pthread_t *thread, const void *attr __unused,
151     void *(*thread_start)(void *), void *arg)
152 {
153         pid_t pid;
154
155         sshpam_thread_status = -1;
156         switch ((pid = fork())) {
157         case -1:
158                 error("fork(): %s", strerror(errno));
159                 return (-1);
160         case 0:
161                 thread_start(arg);
162                 _exit(1);
163         default:
164                 *thread = pid;
165                 sshpam_oldsig = signal(SIGCHLD, sshpam_sigchld_handler);
166                 return (0);
167         }
168 }
169
170 static int
171 pthread_cancel(sp_pthread_t thread)
172 {
173         signal(SIGCHLD, sshpam_oldsig);
174         return (kill(thread, SIGTERM));
175 }
176
177 static int
178 pthread_join(sp_pthread_t thread, void **value __unused)
179 {
180         int status;
181
182         if (sshpam_thread_status != -1)
183                 return (sshpam_thread_status);
184         signal(SIGCHLD, sshpam_oldsig);
185         waitpid(thread, &status, 0);
186         return (status);
187 }
188 #endif
189
190
191 static pam_handle_t *sshpam_handle = NULL;
192 static int sshpam_err = 0;
193 static int sshpam_authenticated = 0;
194 static int sshpam_session_open = 0;
195 static int sshpam_cred_established = 0;
196 static int sshpam_account_status = -1;
197 static char **sshpam_env = NULL;
198 static Authctxt *sshpam_authctxt = NULL;
199 static const char *sshpam_password = NULL;
200 static char badpw[] = "\b\n\r\177INCORRECT";
201
202 /* Some PAM implementations don't implement this */
203 #ifndef HAVE_PAM_GETENVLIST
204 static char **
205 pam_getenvlist(pam_handle_t *pamh)
206 {
207         /*
208          * XXX - If necessary, we can still support envrionment passing
209          * for platforms without pam_getenvlist by searching for known
210          * env vars (e.g. KRB5CCNAME) from the PAM environment.
211          */
212          return NULL;
213 }
214 #endif
215
216 /*
217  * Some platforms, notably Solaris, do not enforce password complexity
218  * rules during pam_chauthtok() if the real uid of the calling process
219  * is 0, on the assumption that it's being called by "passwd" run by root.
220  * This wraps pam_chauthtok and sets/restore the real uid so PAM will do
221  * the right thing.
222  */
223 #ifdef SSHPAM_CHAUTHTOK_NEEDS_RUID
224 static int
225 sshpam_chauthtok_ruid(pam_handle_t *pamh, int flags)
226 {
227         int result;
228
229         if (sshpam_authctxt == NULL)
230                 fatal("PAM: sshpam_authctxt not initialized");
231         if (setreuid(sshpam_authctxt->pw->pw_uid, -1) == -1)
232                 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
233         result = pam_chauthtok(pamh, flags);
234         if (setreuid(0, -1) == -1)
235                 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
236         return result;
237 }
238 # define pam_chauthtok(a,b)     (sshpam_chauthtok_ruid((a), (b)))
239 #endif
240
241 void
242 sshpam_password_change_required(int reqd)
243 {
244         debug3("%s %d", __func__, reqd);
245         if (sshpam_authctxt == NULL)
246                 fatal("%s: PAM authctxt not initialized", __func__);
247         sshpam_authctxt->force_pwchange = reqd;
248         if (reqd) {
249                 no_port_forwarding_flag |= 2;
250                 no_agent_forwarding_flag |= 2;
251                 no_x11_forwarding_flag |= 2;
252         } else {
253                 no_port_forwarding_flag &= ~2;
254                 no_agent_forwarding_flag &= ~2;
255                 no_x11_forwarding_flag &= ~2;
256         }
257 }
258
259 /* Import regular and PAM environment from subprocess */
260 static void
261 import_environments(Buffer *b)
262 {
263         char *env;
264         u_int i, num_env;
265         int err;
266
267         debug3("PAM: %s entering", __func__);
268
269 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
270         /* Import variables set by do_pam_account */
271         sshpam_account_status = buffer_get_int(b);
272         sshpam_password_change_required(buffer_get_int(b));
273
274         /* Import environment from subprocess */
275         num_env = buffer_get_int(b);
276         sshpam_env = xmalloc((num_env + 1) * sizeof(*sshpam_env));
277         debug3("PAM: num env strings %d", num_env);
278         for(i = 0; i < num_env; i++)
279                 sshpam_env[i] = buffer_get_string(b, NULL);
280
281         sshpam_env[num_env] = NULL;
282
283         /* Import PAM environment from subprocess */
284         num_env = buffer_get_int(b);
285         debug("PAM: num PAM env strings %d", num_env);
286         for(i = 0; i < num_env; i++) {
287                 env = buffer_get_string(b, NULL);
288
289 #ifdef HAVE_PAM_PUTENV
290                 /* Errors are not fatal here */
291                 if ((err = pam_putenv(sshpam_handle, env)) != PAM_SUCCESS) {
292                         error("PAM: pam_putenv: %s",
293                             pam_strerror(sshpam_handle, sshpam_err));
294                 }
295 #endif
296         }
297 #endif
298 }
299
300 /*
301  * Conversation function for authentication thread.
302  */
303 static int
304 sshpam_thread_conv(int n, struct pam_message **msg,
305     struct pam_response **resp, void *data)
306 {
307         Buffer buffer;
308         struct pam_ctxt *ctxt;
309         struct pam_response *reply;
310         int i;
311
312         debug3("PAM: %s entering, %d messages", __func__, n);
313         *resp = NULL;
314
315         if (data == NULL) {
316                 error("PAM: conversation function passed a null context");
317                 return (PAM_CONV_ERR);
318         }
319         ctxt = data;
320         if (n <= 0 || n > PAM_MAX_NUM_MSG)
321                 return (PAM_CONV_ERR);
322
323         if ((reply = malloc(n * sizeof(*reply))) == NULL)
324                 return (PAM_CONV_ERR);
325         memset(reply, 0, n * sizeof(*reply));
326
327         buffer_init(&buffer);
328         for (i = 0; i < n; ++i) {
329                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
330                 case PAM_PROMPT_ECHO_OFF:
331                         buffer_put_cstring(&buffer,
332                             PAM_MSG_MEMBER(msg, i, msg));
333                         if (ssh_msg_send(ctxt->pam_csock,
334                             PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
335                                 goto fail;
336                         if (ssh_msg_recv(ctxt->pam_csock, &buffer) == -1)
337                                 goto fail;
338                         if (buffer_get_char(&buffer) != PAM_AUTHTOK)
339                                 goto fail;
340                         reply[i].resp = buffer_get_string(&buffer, NULL);
341                         break;
342                 case PAM_PROMPT_ECHO_ON:
343                         buffer_put_cstring(&buffer,
344                             PAM_MSG_MEMBER(msg, i, msg));
345                         if (ssh_msg_send(ctxt->pam_csock,
346                             PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
347                                 goto fail;
348                         if (ssh_msg_recv(ctxt->pam_csock, &buffer) == -1)
349                                 goto fail;
350                         if (buffer_get_char(&buffer) != PAM_AUTHTOK)
351                                 goto fail;
352                         reply[i].resp = buffer_get_string(&buffer, NULL);
353                         break;
354                 case PAM_ERROR_MSG:
355                         buffer_put_cstring(&buffer,
356                             PAM_MSG_MEMBER(msg, i, msg));
357                         if (ssh_msg_send(ctxt->pam_csock,
358                             PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
359                                 goto fail;
360                         break;
361                 case PAM_TEXT_INFO:
362                         buffer_put_cstring(&buffer,
363                             PAM_MSG_MEMBER(msg, i, msg));
364                         if (ssh_msg_send(ctxt->pam_csock,
365                             PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
366                                 goto fail;
367                         break;
368                 default:
369                         goto fail;
370                 }
371                 buffer_clear(&buffer);
372         }
373         buffer_free(&buffer);
374         *resp = reply;
375         return (PAM_SUCCESS);
376
377  fail:
378         for(i = 0; i < n; i++) {
379                 if (reply[i].resp != NULL)
380                         xfree(reply[i].resp);
381         }
382         xfree(reply);
383         buffer_free(&buffer);
384         return (PAM_CONV_ERR);
385 }
386
387 /*
388  * Authentication thread.
389  */
390 static void *
391 sshpam_thread(void *ctxtp)
392 {
393         struct pam_ctxt *ctxt = ctxtp;
394         Buffer buffer;
395         struct pam_conv sshpam_conv;
396         int flags = (options.permit_empty_passwd == 0 ?
397             PAM_DISALLOW_NULL_AUTHTOK : 0);
398 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
399         extern char **environ;
400         char **env_from_pam;
401         u_int i;
402         const char *pam_user;
403
404         pam_get_item(sshpam_handle, PAM_USER, (void **)&pam_user);
405         environ[0] = NULL;
406
407         if (sshpam_authctxt != NULL) {
408                 setproctitle("%s [pam]",
409                     sshpam_authctxt->valid ? pam_user : "unknown");
410         }
411 #endif
412
413         sshpam_conv.conv = sshpam_thread_conv;
414         sshpam_conv.appdata_ptr = ctxt;
415
416         if (sshpam_authctxt == NULL)
417                 fatal("%s: PAM authctxt not initialized", __func__);
418
419         buffer_init(&buffer);
420         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
421             (const void *)&sshpam_conv);
422         if (sshpam_err != PAM_SUCCESS)
423                 goto auth_fail;
424         sshpam_err = pam_authenticate(sshpam_handle, flags);
425         if (sshpam_err != PAM_SUCCESS)
426                 goto auth_fail;
427
428         if (compat20) {
429                 if (!do_pam_account())
430                         goto auth_fail;
431                 if (sshpam_authctxt->force_pwchange) {
432                         sshpam_err = pam_chauthtok(sshpam_handle,
433                             PAM_CHANGE_EXPIRED_AUTHTOK);
434                         if (sshpam_err != PAM_SUCCESS)
435                                 goto auth_fail;
436                         sshpam_password_change_required(0);
437                 }
438         }
439
440         buffer_put_cstring(&buffer, "OK");
441
442 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
443         /* Export variables set by do_pam_account */
444         buffer_put_int(&buffer, sshpam_account_status);
445         buffer_put_int(&buffer, sshpam_authctxt->force_pwchange);
446
447         /* Export any environment strings set in child */
448         for(i = 0; environ[i] != NULL; i++)
449                 ; /* Count */
450         buffer_put_int(&buffer, i);
451         for(i = 0; environ[i] != NULL; i++)
452                 buffer_put_cstring(&buffer, environ[i]);
453
454         /* Export any environment strings set by PAM in child */
455         env_from_pam = pam_getenvlist(sshpam_handle);
456         for(i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++)
457                 ; /* Count */
458         buffer_put_int(&buffer, i);
459         for(i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++)
460                 buffer_put_cstring(&buffer, env_from_pam[i]);
461 #endif /* UNSUPPORTED_POSIX_THREADS_HACK */
462
463         /* XXX - can't do much about an error here */
464         ssh_msg_send(ctxt->pam_csock, sshpam_err, &buffer);
465         buffer_free(&buffer);
466         pthread_exit(NULL);
467
468  auth_fail:
469         buffer_put_cstring(&buffer,
470             pam_strerror(sshpam_handle, sshpam_err));
471         /* XXX - can't do much about an error here */
472         ssh_msg_send(ctxt->pam_csock, PAM_AUTH_ERR, &buffer);
473         buffer_free(&buffer);
474         pthread_exit(NULL);
475
476         return (NULL); /* Avoid warning for non-pthread case */
477 }
478
479 void
480 sshpam_thread_cleanup(void)
481 {
482         struct pam_ctxt *ctxt = cleanup_ctxt;
483
484         debug3("PAM: %s entering", __func__);
485         if (ctxt != NULL && ctxt->pam_thread != 0) {
486                 pthread_cancel(ctxt->pam_thread);
487                 pthread_join(ctxt->pam_thread, NULL);
488                 close(ctxt->pam_psock);
489                 close(ctxt->pam_csock);
490                 memset(ctxt, 0, sizeof(*ctxt));
491                 cleanup_ctxt = NULL;
492         }
493 }
494
495 static int
496 sshpam_null_conv(int n, struct pam_message **msg,
497     struct pam_response **resp, void *data)
498 {
499         debug3("PAM: %s entering, %d messages", __func__, n);
500         return (PAM_CONV_ERR);
501 }
502
503 static struct pam_conv null_conv = { sshpam_null_conv, NULL };
504
505 static int
506 sshpam_store_conv(int n, struct pam_message **msg,
507     struct pam_response **resp, void *data)
508 {
509         struct pam_response *reply;
510         int i;
511         size_t len;
512
513         debug3("PAM: %s called with %d messages", __func__, n);
514         *resp = NULL;
515
516         if (n <= 0 || n > PAM_MAX_NUM_MSG)
517                 return (PAM_CONV_ERR);
518
519         if ((reply = malloc(n * sizeof(*reply))) == NULL)
520                 return (PAM_CONV_ERR);
521         memset(reply, 0, n * sizeof(*reply));
522
523         for (i = 0; i < n; ++i) {
524                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
525                 case PAM_ERROR_MSG:
526                 case PAM_TEXT_INFO:
527                         len = strlen(PAM_MSG_MEMBER(msg, i, msg));
528                         buffer_append(&loginmsg, PAM_MSG_MEMBER(msg, i, msg), len);
529                         buffer_append(&loginmsg, "\n", 1 );
530                         reply[i].resp_retcode = PAM_SUCCESS;
531                         break;
532                 default:
533                         goto fail;
534                 }
535         }
536         *resp = reply;
537         return (PAM_SUCCESS);
538
539  fail:
540         for(i = 0; i < n; i++) {
541                 if (reply[i].resp != NULL)
542                         xfree(reply[i].resp);
543         }
544         xfree(reply);
545         return (PAM_CONV_ERR);
546 }
547
548 static struct pam_conv store_conv = { sshpam_store_conv, NULL };
549
550 void
551 sshpam_cleanup(void)
552 {
553         debug("PAM: cleanup");
554         if (sshpam_handle == NULL)
555                 return;
556         pam_set_item(sshpam_handle, PAM_CONV, (const void *)&null_conv);
557         if (sshpam_cred_established) {
558                 pam_setcred(sshpam_handle, PAM_DELETE_CRED);
559                 sshpam_cred_established = 0;
560         }
561         if (sshpam_session_open) {
562                 pam_close_session(sshpam_handle, PAM_SILENT);
563                 sshpam_session_open = 0;
564         }
565         sshpam_authenticated = 0;
566         pam_end(sshpam_handle, sshpam_err);
567         sshpam_handle = NULL;
568 }
569
570 static int
571 sshpam_init(Authctxt *authctxt)
572 {
573         extern char *__progname;
574         const char *pam_rhost, *pam_user, *user = authctxt->user;
575
576         if (sshpam_handle != NULL) {
577                 /* We already have a PAM context; check if the user matches */
578                 sshpam_err = pam_get_item(sshpam_handle,
579                     PAM_USER, (void **)&pam_user);
580                 if (sshpam_err == PAM_SUCCESS && strcmp(user, pam_user) == 0)
581                         return (0);
582                 pam_end(sshpam_handle, sshpam_err);
583                 sshpam_handle = NULL;
584         }
585         debug("PAM: initializing for \"%s\"", user);
586         sshpam_err =
587             pam_start(SSHD_PAM_SERVICE, user, &store_conv, &sshpam_handle);
588         sshpam_authctxt = authctxt;
589
590         if (sshpam_err != PAM_SUCCESS) {
591                 pam_end(sshpam_handle, sshpam_err);
592                 sshpam_handle = NULL;
593                 return (-1);
594         }
595         pam_rhost = get_remote_name_or_ip(utmp_len, options.use_dns);
596         debug("PAM: setting PAM_RHOST to \"%s\"", pam_rhost);
597         sshpam_err = pam_set_item(sshpam_handle, PAM_RHOST, pam_rhost);
598         if (sshpam_err != PAM_SUCCESS) {
599                 pam_end(sshpam_handle, sshpam_err);
600                 sshpam_handle = NULL;
601                 return (-1);
602         }
603 #ifdef PAM_TTY_KLUDGE
604         /*
605          * Some silly PAM modules (e.g. pam_time) require a TTY to operate.
606          * sshd doesn't set the tty until too late in the auth process and
607          * may not even set one (for tty-less connections)
608          */
609         debug("PAM: setting PAM_TTY to \"ssh\"");
610         sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, "ssh");
611         if (sshpam_err != PAM_SUCCESS) {
612                 pam_end(sshpam_handle, sshpam_err);
613                 sshpam_handle = NULL;
614                 return (-1);
615         }
616 #endif
617         return (0);
618 }
619
620 static void *
621 sshpam_init_ctx(Authctxt *authctxt)
622 {
623         struct pam_ctxt *ctxt;
624         int socks[2];
625
626         debug3("PAM: %s entering", __func__);
627         /* Refuse to start if we don't have PAM enabled */
628         if (!options.use_pam)
629                 return NULL;
630
631         /* Initialize PAM */
632         if (sshpam_init(authctxt) == -1) {
633                 error("PAM: initialization failed");
634                 return (NULL);
635         }
636
637         ctxt = xmalloc(sizeof *ctxt);
638         memset(ctxt, 0, sizeof(*ctxt));
639
640         /* Start the authentication thread */
641         if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, socks) == -1) {
642                 error("PAM: failed create sockets: %s", strerror(errno));
643                 xfree(ctxt);
644                 return (NULL);
645         }
646         ctxt->pam_psock = socks[0];
647         ctxt->pam_csock = socks[1];
648         if (pthread_create(&ctxt->pam_thread, NULL, sshpam_thread, ctxt) == -1) {
649                 error("PAM: failed to start authentication thread: %s",
650                     strerror(errno));
651                 close(socks[0]);
652                 close(socks[1]);
653                 xfree(ctxt);
654                 return (NULL);
655         }
656         cleanup_ctxt = ctxt;
657         return (ctxt);
658 }
659
660 static int
661 sshpam_query(void *ctx, char **name, char **info,
662     u_int *num, char ***prompts, u_int **echo_on)
663 {
664         Buffer buffer;
665         struct pam_ctxt *ctxt = ctx;
666         size_t plen;
667         u_char type;
668         char *msg;
669         size_t len, mlen;
670
671         debug3("PAM: %s entering", __func__);
672         buffer_init(&buffer);
673         *name = xstrdup("");
674         *info = xstrdup("");
675         *prompts = xmalloc(sizeof(char *));
676         **prompts = NULL;
677         plen = 0;
678         *echo_on = xmalloc(sizeof(u_int));
679         while (ssh_msg_recv(ctxt->pam_psock, &buffer) == 0) {
680                 type = buffer_get_char(&buffer);
681                 msg = buffer_get_string(&buffer, NULL);
682                 mlen = strlen(msg);
683                 switch (type) {
684                 case PAM_PROMPT_ECHO_ON:
685                 case PAM_PROMPT_ECHO_OFF:
686                         *num = 1;
687                         len = plen + mlen + 1;
688                         **prompts = xrealloc(**prompts, len);
689                         strlcpy(**prompts + plen, msg, len - plen);
690                         plen += mlen;
691                         **echo_on = (type == PAM_PROMPT_ECHO_ON);
692                         xfree(msg);
693                         return (0);
694                 case PAM_ERROR_MSG:
695                 case PAM_TEXT_INFO:
696                         /* accumulate messages */
697                         len = plen + mlen + 2;
698                         **prompts = xrealloc(**prompts, len);
699                         strlcpy(**prompts + plen, msg, len - plen);
700                         plen += mlen;
701                         strlcat(**prompts + plen, "\n", len - plen);
702                         plen++;
703                         xfree(msg);
704                         break;
705                 case PAM_SUCCESS:
706                 case PAM_AUTH_ERR:
707                         if (**prompts != NULL) {
708                                 /* drain any accumulated messages */
709                                 debug("PAM: %s", **prompts);
710                                 buffer_append(&loginmsg, **prompts,
711                                     strlen(**prompts));
712                                 xfree(**prompts);
713                                 **prompts = NULL;
714                         }
715                         if (type == PAM_SUCCESS) {
716                                 if (!sshpam_authctxt->valid ||
717                                     (sshpam_authctxt->pw->pw_uid == 0 &&
718                                     options.permit_root_login != PERMIT_YES))
719                                         fatal("Internal error: PAM auth "
720                                             "succeeded when it should have "
721                                             "failed");
722                                 import_environments(&buffer);
723                                 *num = 0;
724                                 **echo_on = 0;
725                                 ctxt->pam_done = 1;
726                                 xfree(msg);
727                                 return (0);
728                         }
729                         error("PAM: %s for %s%.100s from %.100s", msg,
730                             sshpam_authctxt->valid ? "" : "illegal user ",
731                             sshpam_authctxt->user,
732                             get_remote_name_or_ip(utmp_len, options.use_dns));
733                         /* FALLTHROUGH */
734                 default:
735                         *num = 0;
736                         **echo_on = 0;
737                         xfree(msg);
738                         ctxt->pam_done = -1;
739                         return (-1);
740                 }
741         }
742         return (-1);
743 }
744
745 /* XXX - see also comment in auth-chall.c:verify_response */
746 static int
747 sshpam_respond(void *ctx, u_int num, char **resp)
748 {
749         Buffer buffer;
750         struct pam_ctxt *ctxt = ctx;
751
752         debug2("PAM: %s entering, %d responses", __func__, num);
753         switch (ctxt->pam_done) {
754         case 1:
755                 sshpam_authenticated = 1;
756                 return (0);
757         case 0:
758                 break;
759         default:
760                 return (-1);
761         }
762         if (num != 1) {
763                 error("PAM: expected one response, got %u", num);
764                 return (-1);
765         }
766         buffer_init(&buffer);
767         if (sshpam_authctxt->valid &&
768             (sshpam_authctxt->pw->pw_uid != 0 ||
769              options.permit_root_login == PERMIT_YES))
770                 buffer_put_cstring(&buffer, *resp);
771         else
772                 buffer_put_cstring(&buffer, badpw);
773         if (ssh_msg_send(ctxt->pam_psock, PAM_AUTHTOK, &buffer) == -1) {
774                 buffer_free(&buffer);
775                 return (-1);
776         }
777         buffer_free(&buffer);
778         return (1);
779 }
780
781 static void
782 sshpam_free_ctx(void *ctxtp)
783 {
784         struct pam_ctxt *ctxt = ctxtp;
785
786         debug3("PAM: %s entering", __func__);
787         sshpam_thread_cleanup();
788         xfree(ctxt);
789         /*
790          * We don't call sshpam_cleanup() here because we may need the PAM
791          * handle at a later stage, e.g. when setting up a session.  It's
792          * still on the cleanup list, so pam_end() *will* be called before
793          * the server process terminates.
794          */
795 }
796
797 KbdintDevice sshpam_device = {
798         "pam",
799         sshpam_init_ctx,
800         sshpam_query,
801         sshpam_respond,
802         sshpam_free_ctx
803 };
804
805 KbdintDevice mm_sshpam_device = {
806         "pam",
807         mm_sshpam_init_ctx,
808         mm_sshpam_query,
809         mm_sshpam_respond,
810         mm_sshpam_free_ctx
811 };
812
813 /*
814  * This replaces auth-pam.c
815  */
816 void
817 start_pam(Authctxt *authctxt)
818 {
819         if (!options.use_pam)
820                 fatal("PAM: initialisation requested when UsePAM=no");
821
822         if (sshpam_init(authctxt) == -1)
823                 fatal("PAM: initialisation failed");
824 }
825
826 void
827 finish_pam(void)
828 {
829         sshpam_cleanup();
830 }
831
832 u_int
833 do_pam_account(void)
834 {
835         debug("%s: called", __func__);
836         if (sshpam_account_status != -1)
837                 return (sshpam_account_status);
838
839         sshpam_err = pam_acct_mgmt(sshpam_handle, 0);
840         debug3("PAM: %s pam_acct_mgmt = %d (%s)", __func__, sshpam_err,
841             pam_strerror(sshpam_handle, sshpam_err));
842         
843         if (sshpam_err != PAM_SUCCESS && sshpam_err != PAM_NEW_AUTHTOK_REQD) {
844                 sshpam_account_status = 0;
845                 return (sshpam_account_status);
846         }
847
848         if (sshpam_err == PAM_NEW_AUTHTOK_REQD)
849                 sshpam_password_change_required(1);
850
851         sshpam_account_status = 1;
852         return (sshpam_account_status);
853 }
854
855 void
856 do_pam_set_tty(const char *tty)
857 {
858         if (tty != NULL) {
859                 debug("PAM: setting PAM_TTY to \"%s\"", tty);
860                 sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, tty);
861                 if (sshpam_err != PAM_SUCCESS)
862                         fatal("PAM: failed to set PAM_TTY: %s",
863                             pam_strerror(sshpam_handle, sshpam_err));
864         }
865 }
866
867 void
868 do_pam_setcred(int init)
869 {
870         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
871             (const void *)&store_conv);
872         if (sshpam_err != PAM_SUCCESS)
873                 fatal("PAM: failed to set PAM_CONV: %s",
874                     pam_strerror(sshpam_handle, sshpam_err));
875         if (init) {
876                 debug("PAM: establishing credentials");
877                 sshpam_err = pam_setcred(sshpam_handle, PAM_ESTABLISH_CRED);
878         } else {
879                 debug("PAM: reinitializing credentials");
880                 sshpam_err = pam_setcred(sshpam_handle, PAM_REINITIALIZE_CRED);
881         }
882         if (sshpam_err == PAM_SUCCESS) {
883                 sshpam_cred_established = 1;
884                 return;
885         }
886         if (sshpam_authenticated)
887                 fatal("PAM: pam_setcred(): %s",
888                     pam_strerror(sshpam_handle, sshpam_err));
889         else
890                 debug("PAM: pam_setcred(): %s",
891                     pam_strerror(sshpam_handle, sshpam_err));
892 }
893
894 static int
895 sshpam_tty_conv(int n, struct pam_message **msg,
896     struct pam_response **resp, void *data)
897 {
898         char input[PAM_MAX_MSG_SIZE];
899         struct pam_response *reply;
900         int i;
901
902         debug3("PAM: %s called with %d messages", __func__, n);
903
904         *resp = NULL;
905
906         if (n <= 0 || n > PAM_MAX_NUM_MSG || !isatty(STDIN_FILENO))
907                 return (PAM_CONV_ERR);
908
909         if ((reply = malloc(n * sizeof(*reply))) == NULL)
910                 return (PAM_CONV_ERR);
911         memset(reply, 0, n * sizeof(*reply));
912
913         for (i = 0; i < n; ++i) {
914                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
915                 case PAM_PROMPT_ECHO_OFF:
916                         reply[i].resp =
917                             read_passphrase(PAM_MSG_MEMBER(msg, i, msg),
918                             RP_ALLOW_STDIN);
919                         reply[i].resp_retcode = PAM_SUCCESS;
920                         break;
921                 case PAM_PROMPT_ECHO_ON:
922                         fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
923                         fgets(input, sizeof input, stdin);
924                         if ((reply[i].resp = strdup(input)) == NULL)
925                                 goto fail;
926                         reply[i].resp_retcode = PAM_SUCCESS;
927                         break;
928                 case PAM_ERROR_MSG:
929                 case PAM_TEXT_INFO:
930                         fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
931                         reply[i].resp_retcode = PAM_SUCCESS;
932                         break;
933                 default:
934                         goto fail;
935                 }
936         }
937         *resp = reply;
938         return (PAM_SUCCESS);
939
940  fail:
941         for(i = 0; i < n; i++) {
942                 if (reply[i].resp != NULL)
943                         xfree(reply[i].resp);
944         }
945         xfree(reply);
946         return (PAM_CONV_ERR);
947 }
948
949 static struct pam_conv tty_conv = { sshpam_tty_conv, NULL };
950
951 /*
952  * XXX this should be done in the authentication phase, but ssh1 doesn't
953  * support that
954  */
955 void
956 do_pam_chauthtok(void)
957 {
958         if (use_privsep)
959                 fatal("Password expired (unable to change with privsep)");
960         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
961             (const void *)&tty_conv);
962         if (sshpam_err != PAM_SUCCESS)
963                 fatal("PAM: failed to set PAM_CONV: %s",
964                     pam_strerror(sshpam_handle, sshpam_err));
965         debug("PAM: changing password");
966         sshpam_err = pam_chauthtok(sshpam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
967         if (sshpam_err != PAM_SUCCESS)
968                 fatal("PAM: pam_chauthtok(): %s",
969                     pam_strerror(sshpam_handle, sshpam_err));
970 }
971
972 void
973 do_pam_session(void)
974 {
975         debug3("PAM: opening session");
976         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
977             (const void *)&store_conv);
978         if (sshpam_err != PAM_SUCCESS)
979                 fatal("PAM: failed to set PAM_CONV: %s",
980                     pam_strerror(sshpam_handle, sshpam_err));
981         sshpam_err = pam_open_session(sshpam_handle, 0);
982         if (sshpam_err == PAM_SUCCESS)
983                 sshpam_session_open = 1;
984         else {
985                 sshpam_session_open = 0;
986                 disable_forwarding();
987                 error("PAM: pam_open_session(): %s",
988                     pam_strerror(sshpam_handle, sshpam_err));
989         }
990
991 }
992
993 int
994 is_pam_session_open(void)
995 {
996         return sshpam_session_open;
997 }
998
999 /*
1000  * Set a PAM environment string. We need to do this so that the session
1001  * modules can handle things like Kerberos/GSI credentials that appear
1002  * during the ssh authentication process.
1003  */
1004 int
1005 do_pam_putenv(char *name, char *value)
1006 {
1007         int ret = 1;
1008 #ifdef HAVE_PAM_PUTENV
1009         char *compound;
1010         size_t len;
1011
1012         len = strlen(name) + strlen(value) + 2;
1013         compound = xmalloc(len);
1014
1015         snprintf(compound, len, "%s=%s", name, value);
1016         ret = pam_putenv(sshpam_handle, compound);
1017         xfree(compound);
1018 #endif
1019
1020         return (ret);
1021 }
1022
1023 char **
1024 fetch_pam_child_environment(void)
1025 {
1026         return sshpam_env;
1027 }
1028
1029 char **
1030 fetch_pam_environment(void)
1031 {
1032         return (pam_getenvlist(sshpam_handle));
1033 }
1034
1035 void
1036 free_pam_environment(char **env)
1037 {
1038         char **envp;
1039
1040         if (env == NULL)
1041                 return;
1042
1043         for (envp = env; *envp; envp++)
1044                 xfree(*envp);
1045         xfree(env);
1046 }
1047
1048 /*
1049  * "Blind" conversation function for password authentication.  Assumes that
1050  * echo-off prompts are for the password and stores messages for later
1051  * display.
1052  */
1053 static int
1054 sshpam_passwd_conv(int n, struct pam_message **msg,
1055     struct pam_response **resp, void *data)
1056 {
1057         struct pam_response *reply;
1058         int i;
1059         size_t len;
1060
1061         debug3("PAM: %s called with %d messages", __func__, n);
1062
1063         *resp = NULL;
1064
1065         if (n <= 0 || n > PAM_MAX_NUM_MSG)
1066                 return (PAM_CONV_ERR);
1067
1068         if ((reply = malloc(n * sizeof(*reply))) == NULL)
1069                 return (PAM_CONV_ERR);
1070         memset(reply, 0, n * sizeof(*reply));
1071
1072         for (i = 0; i < n; ++i) {
1073                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1074                 case PAM_PROMPT_ECHO_OFF:
1075                         if (sshpam_password == NULL)
1076                                 goto fail;
1077                         if ((reply[i].resp = strdup(sshpam_password)) == NULL)
1078                                 goto fail;
1079                         reply[i].resp_retcode = PAM_SUCCESS;
1080                         break;
1081                 case PAM_ERROR_MSG:
1082                 case PAM_TEXT_INFO:
1083                         len = strlen(PAM_MSG_MEMBER(msg, i, msg));
1084                         if (len > 0) {
1085                                 buffer_append(&loginmsg,
1086                                     PAM_MSG_MEMBER(msg, i, msg), len);
1087                                 buffer_append(&loginmsg, "\n", 1);
1088                         }
1089                         if ((reply[i].resp = strdup("")) == NULL)
1090                                 goto fail;
1091                         reply[i].resp_retcode = PAM_SUCCESS;
1092                         break;
1093                 default:
1094                         goto fail;
1095                 }
1096         }
1097         *resp = reply;
1098         return (PAM_SUCCESS);
1099
1100  fail: 
1101         for(i = 0; i < n; i++) {
1102                 if (reply[i].resp != NULL)
1103                         xfree(reply[i].resp);
1104         }
1105         xfree(reply);
1106         return (PAM_CONV_ERR);
1107 }
1108
1109 static struct pam_conv passwd_conv = { sshpam_passwd_conv, NULL };
1110
1111 /*
1112  * Attempt password authentication via PAM
1113  */
1114 int
1115 sshpam_auth_passwd(Authctxt *authctxt, const char *password)
1116 {
1117         int flags = (options.permit_empty_passwd == 0 ?
1118             PAM_DISALLOW_NULL_AUTHTOK : 0);
1119
1120         if (!options.use_pam || sshpam_handle == NULL)
1121                 fatal("PAM: %s called when PAM disabled or failed to "
1122                     "initialise.", __func__);
1123
1124         sshpam_password = password;
1125         sshpam_authctxt = authctxt;
1126
1127         /*
1128          * If the user logging in is invalid, or is root but is not permitted
1129          * by PermitRootLogin, use an invalid password to prevent leaking
1130          * information via timing (eg if the PAM config has a delay on fail).
1131          */
1132         if (!authctxt->valid || (authctxt->pw->pw_uid == 0 &&
1133              options.permit_root_login != PERMIT_YES))
1134                 sshpam_password = badpw;
1135
1136         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1137             (const void *)&passwd_conv);
1138         if (sshpam_err != PAM_SUCCESS)
1139                 fatal("PAM: %s: failed to set PAM_CONV: %s", __func__,
1140                     pam_strerror(sshpam_handle, sshpam_err));
1141
1142         sshpam_err = pam_authenticate(sshpam_handle, flags);
1143         sshpam_password = NULL;
1144         if (sshpam_err == PAM_SUCCESS && authctxt->valid) {
1145                 debug("PAM: password authentication accepted for %.100s",
1146                     authctxt->user);
1147                return 1;
1148         } else {
1149                 debug("PAM: password authentication failed for %.100s: %s",
1150                     authctxt->valid ? authctxt->user : "an illegal user",
1151                     pam_strerror(sshpam_handle, sshpam_err));
1152                 return 0;
1153         }
1154 }
1155 #endif /* USE_PAM */