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