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