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