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