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