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