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