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