xref: /freebsd/crypto/openssh/auth-pam.c (revision ca86bcf2531c7b149c95244a67853d44323e7855)
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_AUTH_FAIL);
803 			error("PAM: %s for %s%.100s from %.100s", msg,
804 			    sshpam_authctxt->valid ? "" : "illegal user ",
805 			    sshpam_authctxt->user,
806 			    auth_get_canonical_hostname(ssh, options.use_dns));
807 			/* FALLTHROUGH */
808 		default:
809 			*num = 0;
810 			**echo_on = 0;
811 			free(msg);
812 			ctxt->pam_done = -1;
813 			return (-1);
814 		}
815 	}
816 	return (-1);
817 }
818 
819 /*
820  * Returns a junk password of identical length to that the user supplied.
821  * Used to mitigate timing attacks against crypt(3)/PAM stacks that
822  * vary processing time in proportion to password length.
823  */
824 static char *
825 fake_password(const char *wire_password)
826 {
827 	const char junk[] = "\b\n\r\177INCORRECT";
828 	char *ret = NULL;
829 	size_t i, l = wire_password != NULL ? strlen(wire_password) : 0;
830 
831 	if (l >= INT_MAX)
832 		fatal("%s: password length too long: %zu", __func__, l);
833 
834 	ret = malloc(l + 1);
835 	for (i = 0; i < l; i++)
836 		ret[i] = junk[i % (sizeof(junk) - 1)];
837 	ret[i] = '\0';
838 	return ret;
839 }
840 
841 /* XXX - see also comment in auth-chall.c:verify_response */
842 static int
843 sshpam_respond(void *ctx, u_int num, char **resp)
844 {
845 	Buffer buffer;
846 	struct pam_ctxt *ctxt = ctx;
847 	char *fake;
848 
849 	debug2("PAM: %s entering, %u responses", __func__, num);
850 	switch (ctxt->pam_done) {
851 	case 1:
852 		sshpam_authenticated = 1;
853 		return (0);
854 	case 0:
855 		break;
856 	default:
857 		return (-1);
858 	}
859 	if (num != 1) {
860 		error("PAM: expected one response, got %u", num);
861 		return (-1);
862 	}
863 	buffer_init(&buffer);
864 	if (sshpam_authctxt->valid &&
865 	    (sshpam_authctxt->pw->pw_uid != 0 ||
866 	    options.permit_root_login == PERMIT_YES))
867 		buffer_put_cstring(&buffer, *resp);
868 	else {
869 		fake = fake_password(*resp);
870 		buffer_put_cstring(&buffer, fake);
871 		free(fake);
872 	}
873 	if (ssh_msg_send(ctxt->pam_psock, PAM_AUTHTOK, &buffer) == -1) {
874 		buffer_free(&buffer);
875 		return (-1);
876 	}
877 	buffer_free(&buffer);
878 	return (1);
879 }
880 
881 static void
882 sshpam_free_ctx(void *ctxtp)
883 {
884 	struct pam_ctxt *ctxt = ctxtp;
885 
886 	debug3("PAM: %s entering", __func__);
887 	sshpam_thread_cleanup();
888 	free(ctxt);
889 	/*
890 	 * We don't call sshpam_cleanup() here because we may need the PAM
891 	 * handle at a later stage, e.g. when setting up a session.  It's
892 	 * still on the cleanup list, so pam_end() *will* be called before
893 	 * the server process terminates.
894 	 */
895 }
896 
897 KbdintDevice sshpam_device = {
898 	"pam",
899 	sshpam_init_ctx,
900 	sshpam_query,
901 	sshpam_respond,
902 	sshpam_free_ctx
903 };
904 
905 KbdintDevice mm_sshpam_device = {
906 	"pam",
907 	mm_sshpam_init_ctx,
908 	mm_sshpam_query,
909 	mm_sshpam_respond,
910 	mm_sshpam_free_ctx
911 };
912 
913 /*
914  * This replaces auth-pam.c
915  */
916 void
917 start_pam(Authctxt *authctxt)
918 {
919 	if (!options.use_pam)
920 		fatal("PAM: initialisation requested when UsePAM=no");
921 
922 	if (sshpam_init(authctxt) == -1)
923 		fatal("PAM: initialisation failed");
924 }
925 
926 void
927 finish_pam(void)
928 {
929 	sshpam_cleanup();
930 }
931 
932 u_int
933 do_pam_account(void)
934 {
935 	debug("%s: called", __func__);
936 	if (sshpam_account_status != -1)
937 		return (sshpam_account_status);
938 
939 	sshpam_err = pam_acct_mgmt(sshpam_handle, 0);
940 	debug3("PAM: %s pam_acct_mgmt = %d (%s)", __func__, sshpam_err,
941 	    pam_strerror(sshpam_handle, sshpam_err));
942 
943 	if (sshpam_err != PAM_SUCCESS && sshpam_err != PAM_NEW_AUTHTOK_REQD) {
944 		sshpam_account_status = 0;
945 		return (sshpam_account_status);
946 	}
947 
948 	if (sshpam_err == PAM_NEW_AUTHTOK_REQD)
949 		sshpam_password_change_required(1);
950 
951 	sshpam_account_status = 1;
952 	return (sshpam_account_status);
953 }
954 
955 void
956 do_pam_setcred(int init)
957 {
958 	sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
959 	    (const void *)&store_conv);
960 	if (sshpam_err != PAM_SUCCESS)
961 		fatal("PAM: failed to set PAM_CONV: %s",
962 		    pam_strerror(sshpam_handle, sshpam_err));
963 	if (init) {
964 		debug("PAM: establishing credentials");
965 		sshpam_err = pam_setcred(sshpam_handle, PAM_ESTABLISH_CRED);
966 	} else {
967 		debug("PAM: reinitializing credentials");
968 		sshpam_err = pam_setcred(sshpam_handle, PAM_REINITIALIZE_CRED);
969 	}
970 	if (sshpam_err == PAM_SUCCESS) {
971 		sshpam_cred_established = 1;
972 		return;
973 	}
974 	if (sshpam_authenticated)
975 		fatal("PAM: pam_setcred(): %s",
976 		    pam_strerror(sshpam_handle, sshpam_err));
977 	else
978 		debug("PAM: pam_setcred(): %s",
979 		    pam_strerror(sshpam_handle, sshpam_err));
980 }
981 
982 static int
983 sshpam_tty_conv(int n, sshpam_const struct pam_message **msg,
984     struct pam_response **resp, void *data)
985 {
986 	char input[PAM_MAX_MSG_SIZE];
987 	struct pam_response *reply;
988 	int i;
989 
990 	debug3("PAM: %s called with %d messages", __func__, n);
991 
992 	*resp = NULL;
993 
994 	if (n <= 0 || n > PAM_MAX_NUM_MSG || !isatty(STDIN_FILENO))
995 		return (PAM_CONV_ERR);
996 
997 	if ((reply = calloc(n, sizeof(*reply))) == NULL)
998 		return (PAM_CONV_ERR);
999 
1000 	for (i = 0; i < n; ++i) {
1001 		switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1002 		case PAM_PROMPT_ECHO_OFF:
1003 			reply[i].resp =
1004 			    read_passphrase(PAM_MSG_MEMBER(msg, i, msg),
1005 			    RP_ALLOW_STDIN);
1006 			reply[i].resp_retcode = PAM_SUCCESS;
1007 			break;
1008 		case PAM_PROMPT_ECHO_ON:
1009 			fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1010 			if (fgets(input, sizeof input, stdin) == NULL)
1011 				input[0] = '\0';
1012 			if ((reply[i].resp = strdup(input)) == NULL)
1013 				goto fail;
1014 			reply[i].resp_retcode = PAM_SUCCESS;
1015 			break;
1016 		case PAM_ERROR_MSG:
1017 		case PAM_TEXT_INFO:
1018 			fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1019 			reply[i].resp_retcode = PAM_SUCCESS;
1020 			break;
1021 		default:
1022 			goto fail;
1023 		}
1024 	}
1025 	*resp = reply;
1026 	return (PAM_SUCCESS);
1027 
1028  fail:
1029 	for(i = 0; i < n; i++) {
1030 		free(reply[i].resp);
1031 	}
1032 	free(reply);
1033 	return (PAM_CONV_ERR);
1034 }
1035 
1036 static struct pam_conv tty_conv = { sshpam_tty_conv, NULL };
1037 
1038 /*
1039  * XXX this should be done in the authentication phase, but ssh1 doesn't
1040  * support that
1041  */
1042 void
1043 do_pam_chauthtok(void)
1044 {
1045 	if (use_privsep)
1046 		fatal("Password expired (unable to change with privsep)");
1047 	sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1048 	    (const void *)&tty_conv);
1049 	if (sshpam_err != PAM_SUCCESS)
1050 		fatal("PAM: failed to set PAM_CONV: %s",
1051 		    pam_strerror(sshpam_handle, sshpam_err));
1052 	debug("PAM: changing password");
1053 	sshpam_err = pam_chauthtok(sshpam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
1054 	if (sshpam_err != PAM_SUCCESS)
1055 		fatal("PAM: pam_chauthtok(): %s",
1056 		    pam_strerror(sshpam_handle, sshpam_err));
1057 }
1058 
1059 void
1060 do_pam_session(void)
1061 {
1062 	debug3("PAM: opening session");
1063 	sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1064 	    (const void *)&store_conv);
1065 	if (sshpam_err != PAM_SUCCESS)
1066 		fatal("PAM: failed to set PAM_CONV: %s",
1067 		    pam_strerror(sshpam_handle, sshpam_err));
1068 	sshpam_err = pam_open_session(sshpam_handle, 0);
1069 	if (sshpam_err == PAM_SUCCESS)
1070 		sshpam_session_open = 1;
1071 	else {
1072 		sshpam_session_open = 0;
1073 		disable_forwarding();
1074 		error("PAM: pam_open_session(): %s",
1075 		    pam_strerror(sshpam_handle, sshpam_err));
1076 	}
1077 
1078 }
1079 
1080 int
1081 is_pam_session_open(void)
1082 {
1083 	return sshpam_session_open;
1084 }
1085 
1086 /*
1087  * Set a PAM environment string. We need to do this so that the session
1088  * modules can handle things like Kerberos/GSI credentials that appear
1089  * during the ssh authentication process.
1090  */
1091 int
1092 do_pam_putenv(char *name, char *value)
1093 {
1094 	int ret = 1;
1095 #ifdef HAVE_PAM_PUTENV
1096 	char *compound;
1097 	size_t len;
1098 
1099 	len = strlen(name) + strlen(value) + 2;
1100 	compound = xmalloc(len);
1101 
1102 	snprintf(compound, len, "%s=%s", name, value);
1103 	ret = pam_putenv(sshpam_handle, compound);
1104 	free(compound);
1105 #endif
1106 
1107 	return (ret);
1108 }
1109 
1110 char **
1111 fetch_pam_child_environment(void)
1112 {
1113 	return sshpam_env;
1114 }
1115 
1116 char **
1117 fetch_pam_environment(void)
1118 {
1119 	return (pam_getenvlist(sshpam_handle));
1120 }
1121 
1122 void
1123 free_pam_environment(char **env)
1124 {
1125 	char **envp;
1126 
1127 	if (env == NULL)
1128 		return;
1129 
1130 	for (envp = env; *envp; envp++)
1131 		free(*envp);
1132 	free(env);
1133 }
1134 
1135 /*
1136  * "Blind" conversation function for password authentication.  Assumes that
1137  * echo-off prompts are for the password and stores messages for later
1138  * display.
1139  */
1140 static int
1141 sshpam_passwd_conv(int n, sshpam_const struct pam_message **msg,
1142     struct pam_response **resp, void *data)
1143 {
1144 	struct pam_response *reply;
1145 	int i;
1146 	size_t len;
1147 
1148 	debug3("PAM: %s called with %d messages", __func__, n);
1149 
1150 	*resp = NULL;
1151 
1152 	if (n <= 0 || n > PAM_MAX_NUM_MSG)
1153 		return (PAM_CONV_ERR);
1154 
1155 	if ((reply = calloc(n, sizeof(*reply))) == NULL)
1156 		return (PAM_CONV_ERR);
1157 
1158 	for (i = 0; i < n; ++i) {
1159 		switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1160 		case PAM_PROMPT_ECHO_OFF:
1161 			if (sshpam_password == NULL)
1162 				goto fail;
1163 			if ((reply[i].resp = strdup(sshpam_password)) == NULL)
1164 				goto fail;
1165 			reply[i].resp_retcode = PAM_SUCCESS;
1166 			break;
1167 		case PAM_ERROR_MSG:
1168 		case PAM_TEXT_INFO:
1169 			len = strlen(PAM_MSG_MEMBER(msg, i, msg));
1170 			if (len > 0) {
1171 				buffer_append(&loginmsg,
1172 				    PAM_MSG_MEMBER(msg, i, msg), len);
1173 				buffer_append(&loginmsg, "\n", 1);
1174 			}
1175 			if ((reply[i].resp = strdup("")) == NULL)
1176 				goto fail;
1177 			reply[i].resp_retcode = PAM_SUCCESS;
1178 			break;
1179 		default:
1180 			goto fail;
1181 		}
1182 	}
1183 	*resp = reply;
1184 	return (PAM_SUCCESS);
1185 
1186  fail:
1187 	for(i = 0; i < n; i++) {
1188 		free(reply[i].resp);
1189 	}
1190 	free(reply);
1191 	return (PAM_CONV_ERR);
1192 }
1193 
1194 static struct pam_conv passwd_conv = { sshpam_passwd_conv, NULL };
1195 
1196 /*
1197  * Attempt password authentication via PAM
1198  */
1199 int
1200 sshpam_auth_passwd(Authctxt *authctxt, const char *password)
1201 {
1202 	int flags = (options.permit_empty_passwd == 0 ?
1203 	    PAM_DISALLOW_NULL_AUTHTOK : 0);
1204 	char *fake = NULL;
1205 
1206 	if (!options.use_pam || sshpam_handle == NULL)
1207 		fatal("PAM: %s called when PAM disabled or failed to "
1208 		    "initialise.", __func__);
1209 
1210 	sshpam_password = password;
1211 	sshpam_authctxt = authctxt;
1212 
1213 	/*
1214 	 * If the user logging in is invalid, or is root but is not permitted
1215 	 * by PermitRootLogin, use an invalid password to prevent leaking
1216 	 * information via timing (eg if the PAM config has a delay on fail).
1217 	 */
1218 	if (!authctxt->valid || (authctxt->pw->pw_uid == 0 &&
1219 	    options.permit_root_login != PERMIT_YES))
1220 		sshpam_password = fake = fake_password(password);
1221 
1222 	sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1223 	    (const void *)&passwd_conv);
1224 	if (sshpam_err != PAM_SUCCESS)
1225 		fatal("PAM: %s: failed to set PAM_CONV: %s", __func__,
1226 		    pam_strerror(sshpam_handle, sshpam_err));
1227 
1228 	sshpam_err = pam_authenticate(sshpam_handle, flags);
1229 	sshpam_password = NULL;
1230 	free(fake);
1231 	if (sshpam_err == PAM_MAXTRIES)
1232 		sshpam_set_maxtries_reached(1);
1233 	if (sshpam_err == PAM_SUCCESS && authctxt->valid) {
1234 		debug("PAM: password authentication accepted for %.100s",
1235 		    authctxt->user);
1236 		return 1;
1237 	} else {
1238 		debug("PAM: password authentication failed for %.100s: %s",
1239 		    authctxt->valid ? authctxt->user : "an illegal user",
1240 		    pam_strerror(sshpam_handle, sshpam_err));
1241 		return 0;
1242 	}
1243 }
1244 
1245 int
1246 sshpam_get_maxtries_reached(void)
1247 {
1248 	return sshpam_maxtries_reached;
1249 }
1250 
1251 void
1252 sshpam_set_maxtries_reached(int reached)
1253 {
1254 	if (reached == 0 || sshpam_maxtries_reached)
1255 		return;
1256 	sshpam_maxtries_reached = 1;
1257 	options.password_authentication = 0;
1258 	options.kbd_interactive_authentication = 0;
1259 	options.challenge_response_authentication = 0;
1260 }
1261 #endif /* USE_PAM */
1262