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