? autom4te-2.53.cache
Index: Makefile.in
===================================================================
RCS file: /var/cvs/openssh/Makefile.in,v
retrieving revision 1.223
diff -u -r1.223 Makefile.in
--- Makefile.in	9 Jan 2003 01:22:59 -0000	1.223
+++ Makefile.in	10 Jan 2003 01:16:55 -0000
@@ -65,7 +65,7 @@
 
 SSHOBJS= ssh.o sshconnect.o sshconnect1.o sshconnect2.o sshtty.o readconf.o clientloop.o
 
-SSHDOBJS= sshd.o auth.o auth1.o auth2.o auth2-hostbased.o auth2-kbdint.o auth2-none.o auth2-passwd.o auth2-pubkey.o auth-chall.o auth2-chall.o auth-rhosts.o auth-options.o auth-krb4.o auth-krb5.o auth-pam.o auth2-pam.o auth-passwd.o auth-rsa.o auth-rh-rsa.o auth-sia.o sshpty.o sshlogin.o loginrec.o servconf.o serverloop.o md5crypt.o session.o groupaccess.o auth-skey.o auth-bsdauth.o monitor_mm.o monitor.o
+SSHDOBJS= sshd.o auth.o auth1.o auth2.o auth2-hostbased.o auth2-kbdint.o auth2-none.o auth2-passwd.o auth2-pubkey.o auth-chall.o auth2-chall.o auth-rhosts.o auth-options.o auth-krb4.o auth-krb5.o auth-pam.o auth-passwd.o auth-rsa.o auth-rh-rsa.o auth-sia.o sshpty.o sshlogin.o loginrec.o servconf.o serverloop.o md5crypt.o session.o groupaccess.o auth-skey.o auth-bsdauth.o monitor_mm.o monitor.o
 
 MANPAGES	= scp.1.out ssh-add.1.out ssh-agent.1.out ssh-keygen.1.out ssh-keyscan.1.out ssh.1.out sshd.8.out sftp-server.8.out sftp.1.out ssh-rand-helper.8.out ssh-keysign.8.out sshd_config.5.out ssh_config.5.out
 MANPAGES_IN	= scp.1 ssh-add.1 ssh-agent.1 ssh-keygen.1 ssh-keyscan.1 ssh.1 sshd.8 sftp-server.8 sftp.1 ssh-rand-helper.8 ssh-keysign.8 sshd_config.5 ssh_config.5
Index: auth-pam.c
===================================================================
RCS file: /var/cvs/openssh/auth-pam.c,v
retrieving revision 1.54
diff -u -r1.54 auth-pam.c
--- auth-pam.c	28 Jul 2002 20:24:08 -0000	1.54
+++ auth-pam.c	10 Jan 2003 01:16:56 -0000
@@ -1,5 +1,11 @@
-/*
- * Copyright (c) 2000 Damien Miller.  All rights reserved.
+/*-
+ * Copyright (c) 2002 Networks Associates Technology, Inc.
+ * All rights reserved.
+ *
+ * This software was developed for the FreeBSD Project by ThinkSec AS and
+ * NAI Labs, the Security Research Division of Network Associates, Inc.
+ * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
+ * DARPA CHATS research program.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -10,454 +16,597 @@
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
 
 #include "includes.h"
+RCSID("$FreeBSD: src/crypto/openssh/auth2-pam-freebsd.c,v 1.8 2002/12/21 15:09:58 des Exp $");
 
 #ifdef USE_PAM
-#include "xmalloc.h"
-#include "log.h"
+#include <security/pam_appl.h>
+
 #include "auth.h"
-#include "auth-options.h"
 #include "auth-pam.h"
-#include "servconf.h"
+#include "buffer.h"
+#include "bufaux.h"
 #include "canohost.h"
+#include "log.h"
+#include "monitor_wrap.h"
+#include "msg.h"
+#include "packet.h"
 #include "readpass.h"
+#include "servconf.h"
+#include "ssh2.h"
+#include "xmalloc.h"
 
-extern char *__progname;
+#define __unused
 
-extern int use_privsep;
+#ifdef USE_POSIX_THREADS
+#include <pthread.h>
+/*
+ * Avoid namespace clash when *not* using pthreads for systems *with* 
+ * pthreads, which unconditionally define pthread_t via sys/types.h 
+ * (e.g. Linux)
+ */
+typedef pthread_t sp_pthread_t; 
+#else
+/*
+ * Simulate threads with processes.
+ */
+typedef pid_t sp_pthread_t;
 
-RCSID("$Id: auth-pam.c,v 1.54 2002/07/28 20:24:08 stevesk Exp $");
+static void
+pthread_exit(void *value __unused)
+{
+	_exit(0);
+}
 
-#define NEW_AUTHTOK_MSG \
-	"Warning: Your password has expired, please change it now."
-#define NEW_AUTHTOK_MSG_PRIVSEP \
-	"Your password has expired, the session cannot proceed."
+static int
+pthread_create(sp_pthread_t *thread, const void *attr __unused,
+    void *(*thread_start)(void *), void *arg)
+{
+	pid_t pid;
+
+	switch ((pid = fork())) {
+	case -1:
+		error("fork(): %s", strerror(errno));
+		return (-1);
+	case 0:
+		thread_start(arg);
+		_exit(1);
+	default:
+		*thread = pid;
+		return (0);
+	}
+}
 
-static int do_pam_conversation(int num_msg, const struct pam_message **msg,
-	struct pam_response **resp, void *appdata_ptr);
+static int
+pthread_cancel(sp_pthread_t thread)
+{
+	return (kill(thread, SIGTERM));
+}
 
-/* module-local variables */
-static struct pam_conv conv = {
-	(int (*)())do_pam_conversation,
-	NULL
-};
-static char *__pam_msg = NULL;
-static pam_handle_t *__pamh = NULL;
-static const char *__pampasswd = NULL;
-
-/* states for do_pam_conversation() */
-enum { INITIAL_LOGIN, OTHER } pamstate = INITIAL_LOGIN;
-/* remember whether pam_acct_mgmt() returned PAM_NEW_AUTHTOK_REQD */
-static int password_change_required = 0;
-/* remember whether the last pam_authenticate() succeeded or not */
-static int was_authenticated = 0;
-
-/* Remember what has been initialised */
-static int session_opened = 0;
-static int creds_set = 0;
-
-/* accessor which allows us to switch conversation structs according to
- * the authentication method being used */
-void do_pam_set_conv(struct pam_conv *conv)
-{
-	pam_set_item(__pamh, PAM_CONV, conv);
-}
-
-/* start an authentication run */
-int do_pam_authenticate(int flags)
-{
-	int retval = pam_authenticate(__pamh, flags);
-	was_authenticated = (retval == PAM_SUCCESS);
-	return retval;
+static int
+pthread_join(sp_pthread_t thread, void **value __unused)
+{
+	int status;
+
+	waitpid(thread, &status, 0);
+	return (status);
 }
+#endif
+
+
+static pam_handle_t *sshpam_handle;
+static int sshpam_err;
+static int sshpam_authenticated;
+static int sshpam_new_authtok_reqd;
+static int sshpam_session_open;
+static int sshpam_cred_established;
+
+struct pam_ctxt {
+	sp_pthread_t	 pam_thread;
+	int		 pam_psock;
+	int		 pam_csock;
+	int		 pam_done;
+};
+
+static void sshpam_free_ctx(void *);
 
 /*
- * PAM conversation function.
- * There are two states this can run in.
- *
- * INITIAL_LOGIN mode simply feeds the password from the client into
- * PAM in response to PAM_PROMPT_ECHO_OFF, and collects output
- * messages with into __pam_msg.  This is used during initial
- * authentication to bypass the normal PAM password prompt.
- *
- * OTHER mode handles PAM_PROMPT_ECHO_OFF with read_passphrase()
- * and outputs messages to stderr. This mode is used if pam_chauthtok()
- * is called to update expired passwords.
+ * Conversation function for authentication thread.
  */
-static int do_pam_conversation(int num_msg, const struct pam_message **msg,
-	struct pam_response **resp, void *appdata_ptr)
+static int
+sshpam_thread_conv(int n,
+	 const struct pam_message **msg,
+	 struct pam_response **resp,
+	 void *data)
 {
-	struct pam_response *reply;
-	int count;
-	char buf[1024];
-
-	/* PAM will free this later */
-	reply = xmalloc(num_msg * sizeof(*reply));
-
-	for (count = 0; count < num_msg; count++) {
-		if (pamstate == INITIAL_LOGIN) {
-			/*
-			 * We can't use stdio yet, queue messages for 
-			 * printing later
-			 */
-			switch(PAM_MSG_MEMBER(msg, count, msg_style)) {
-			case PAM_PROMPT_ECHO_ON:
-				xfree(reply);
-				return PAM_CONV_ERR;
-			case PAM_PROMPT_ECHO_OFF:
-				if (__pampasswd == NULL) {
-					xfree(reply);
-					return PAM_CONV_ERR;
-				}
-				reply[count].resp = xstrdup(__pampasswd);
-				reply[count].resp_retcode = PAM_SUCCESS;
-				break;
-			case PAM_ERROR_MSG:
-			case PAM_TEXT_INFO:
-				if (PAM_MSG_MEMBER(msg, count, msg) != NULL) {
-					message_cat(&__pam_msg, 
-					    PAM_MSG_MEMBER(msg, count, msg));
-				}
-				reply[count].resp = xstrdup("");
-				reply[count].resp_retcode = PAM_SUCCESS;
-				break;
-			default:
-				xfree(reply);
-				return PAM_CONV_ERR;
-			}
-		} else {
-			/*
-			 * stdio is connected, so interact directly
-			 */
-			switch(PAM_MSG_MEMBER(msg, count, msg_style)) {
-			case PAM_PROMPT_ECHO_ON:
-				fputs(PAM_MSG_MEMBER(msg, count, msg), stderr);
-				fgets(buf, sizeof(buf), stdin);
-				reply[count].resp = xstrdup(buf);
-				reply[count].resp_retcode = PAM_SUCCESS;
-				break;
-			case PAM_PROMPT_ECHO_OFF:
-				reply[count].resp = 
-				    read_passphrase(PAM_MSG_MEMBER(msg, count,
-					msg), RP_ALLOW_STDIN);
-				reply[count].resp_retcode = PAM_SUCCESS;
-				break;
-			case PAM_ERROR_MSG:
-			case PAM_TEXT_INFO:
-				if (PAM_MSG_MEMBER(msg, count, msg) != NULL)
-					fprintf(stderr, "%s\n", 
-					    PAM_MSG_MEMBER(msg, count, msg));
-				reply[count].resp = xstrdup("");
-				reply[count].resp_retcode = PAM_SUCCESS;
-				break;
-			default:
-				xfree(reply);
-				return PAM_CONV_ERR;
-			}
+	Buffer buffer;
+	struct pam_ctxt *ctxt;
+	int i;
+
+	ctxt = data;
+	if (n <= 0 || n > PAM_MAX_NUM_MSG)
+		return (PAM_CONV_ERR);
+	*resp = xmalloc(n * sizeof **resp);
+	buffer_init(&buffer);
+	for (i = 0; i < n; ++i) {
+		resp[i]->resp_retcode = 0;
+		resp[i]->resp = NULL;
+		switch (msg[i]->msg_style) {
+		case PAM_PROMPT_ECHO_OFF:
+			buffer_put_cstring(&buffer, msg[i]->msg);
+			ssh_msg_send(ctxt->pam_csock, msg[i]->msg_style, &buffer);
+			ssh_msg_recv(ctxt->pam_csock, &buffer);
+			if (buffer_get_char(&buffer) != PAM_AUTHTOK)
+				goto fail;
+			resp[i]->resp = buffer_get_string(&buffer, NULL);
+			break;
+		case PAM_PROMPT_ECHO_ON:
+			buffer_put_cstring(&buffer, msg[i]->msg);
+			ssh_msg_send(ctxt->pam_csock, msg[i]->msg_style, &buffer);
+			ssh_msg_recv(ctxt->pam_csock, &buffer);
+			if (buffer_get_char(&buffer) != PAM_AUTHTOK)
+				goto fail;
+			resp[i]->resp = buffer_get_string(&buffer, NULL);
+			break;
+		case PAM_ERROR_MSG:
+			buffer_put_cstring(&buffer, msg[i]->msg);
+			ssh_msg_send(ctxt->pam_csock, msg[i]->msg_style, &buffer);
+			break;
+		case PAM_TEXT_INFO:
+			buffer_put_cstring(&buffer, msg[i]->msg);
+			ssh_msg_send(ctxt->pam_csock, msg[i]->msg_style, &buffer);
+			break;
+		default:
+			goto fail;
 		}
+		buffer_clear(&buffer);
 	}
-
-	*resp = reply;
-
-	return PAM_SUCCESS;
+	buffer_free(&buffer);
+	return (PAM_SUCCESS);
+ fail:
+	while (i)
+		xfree(resp[--i]);
+	xfree(*resp);
+	*resp = NULL;
+	buffer_free(&buffer);
+	return (PAM_CONV_ERR);
 }
 
-/* Called at exit to cleanly shutdown PAM */
-void do_pam_cleanup_proc(void *context)
+/*
+ * Authentication thread.
+ */
+static void *
+sshpam_thread(void *ctxtp)
 {
-	int pam_retval = PAM_SUCCESS;
-
-	if (__pamh && session_opened) {
-		pam_retval = pam_close_session(__pamh, 0);
-		if (pam_retval != PAM_SUCCESS)
-			log("Cannot close PAM session[%d]: %.200s",
-			    pam_retval, PAM_STRERROR(__pamh, pam_retval));
+	struct pam_ctxt *ctxt = ctxtp;
+	Buffer buffer;
+	struct pam_conv sshpam_conv = { sshpam_thread_conv, ctxt };
+
+	buffer_init(&buffer);
+	sshpam_err = pam_set_item(sshpam_handle,
+	    PAM_CONV, (const void *)&sshpam_conv);
+	if (sshpam_err != PAM_SUCCESS)
+		goto auth_fail;
+	sshpam_err = pam_authenticate(sshpam_handle, 0);
+	if (sshpam_err != PAM_SUCCESS)
+		goto auth_fail;
+	sshpam_err = pam_acct_mgmt(sshpam_handle, 0);
+	if (sshpam_err != PAM_SUCCESS)
+		goto auth_fail;
+	buffer_put_cstring(&buffer, "OK");
+	ssh_msg_send(ctxt->pam_csock, PAM_SUCCESS, &buffer);
+	buffer_free(&buffer);
+	pthread_exit(NULL);
+ auth_fail:
+	buffer_put_cstring(&buffer,
+	    pam_strerror(sshpam_handle, sshpam_err));
+	ssh_msg_send(ctxt->pam_csock, PAM_AUTH_ERR, &buffer);
+	buffer_free(&buffer);
+	pthread_exit(NULL);
+	return (NULL); /* Avoid warning for non-pthread case */
+}
+
+static void
+sshpam_thread_cleanup(void *ctxtp)
+{
+	struct pam_ctxt *ctxt = ctxtp;
+
+	pthread_cancel(ctxt->pam_thread);
+	pthread_join(ctxt->pam_thread, NULL);
+	close(ctxt->pam_psock);
+	close(ctxt->pam_csock);
+}
+
+static void
+sshpam_cleanup(void *arg)
+{
+	(void)arg;
+	debug("PAM: cleanup");
+	if (sshpam_cred_established) {
+		pam_setcred(sshpam_handle, PAM_DELETE_CRED);
+		sshpam_cred_established = 0;
 	}
-
-	if (__pamh && creds_set) {
-		pam_retval = pam_setcred(__pamh, PAM_DELETE_CRED);
-		if (pam_retval != PAM_SUCCESS)
-			debug("Cannot delete credentials[%d]: %.200s", 
-			    pam_retval, PAM_STRERROR(__pamh, pam_retval));
-	}
-
-	if (__pamh) {
-		pam_retval = pam_end(__pamh, pam_retval);
-		if (pam_retval != PAM_SUCCESS)
-			log("Cannot release PAM authentication[%d]: %.200s",
-			    pam_retval, PAM_STRERROR(__pamh, pam_retval));
+	if (sshpam_session_open) {
+		pam_close_session(sshpam_handle, PAM_SILENT);
+		sshpam_session_open = 0;
 	}
+	sshpam_authenticated = sshpam_new_authtok_reqd = 0;
+	pam_end(sshpam_handle, sshpam_err);
+	sshpam_handle = NULL;
 }
 
-/* Attempt password authentation using PAM */
-int auth_pam_password(Authctxt *authctxt, const char *password)
+static int
+sshpam_init(const char *user)
 {
 	extern ServerOptions options;
-	int pam_retval;
-	struct passwd *pw = authctxt->pw;
-
-	do_pam_set_conv(&conv);
+	extern u_int utmp_len;
+	const char *pam_rhost, *pam_user;
+	struct pam_conv fake_conv = { NULL, NULL };
 
-	/* deny if no user. */
-	if (pw == NULL)
-		return 0;
-	if (pw->pw_uid == 0 && options.permit_root_login == PERMIT_NO_PASSWD)
-		return 0;
-	if (*password == '\0' && options.permit_empty_passwd == 0)
-		return 0;
-
-	__pampasswd = password;
-
-	pamstate = INITIAL_LOGIN;
-	pam_retval = do_pam_authenticate(
-	    options.permit_empty_passwd == 0 ? PAM_DISALLOW_NULL_AUTHTOK : 0);
-	if (pam_retval == PAM_SUCCESS) {
-		debug("PAM Password authentication accepted for "
-		    "user \"%.100s\"", pw->pw_name);
-		return 1;
-	} else {
-		debug("PAM Password authentication for \"%.100s\" "
-		    "failed[%d]: %s", pw->pw_name, pam_retval, 
-		    PAM_STRERROR(__pamh, pam_retval));
-		return 0;
+	if (sshpam_handle != NULL) {
+		/* We already have a PAM context; check if the user matches */
+		sshpam_err = pam_get_item(sshpam_handle,
+		    PAM_USER, (const void **)&pam_user);
+		if (sshpam_err == PAM_SUCCESS && strcmp(user, pam_user) == 0)
+			return (0);
+		fatal_remove_cleanup(sshpam_cleanup, NULL);
+		pam_end(sshpam_handle, sshpam_err);
+		sshpam_handle = NULL;
+	}
+	debug("PAM: initializing for \"%s\"", user);
+	
+	/*
+	 * NB - Linux PAM dies ("memory buffer error") unless we supply
+	 * it a conversation function here. It gets changed to a real one
+	 * before use anyway.
+	 */
+	sshpam_err = pam_start("sshd", user, &fake_conv, &sshpam_handle);
+	if (sshpam_err != PAM_SUCCESS) {
+		error("PAM initialisation failed[%d]: %.200s",
+                    sshpam_err, PAM_STRERROR(sshpam_handle, sshpam_err));
+		return (-1);
 	}
+	pam_rhost = get_remote_name_or_ip(utmp_len,
+	    options.verify_reverse_mapping);
+	debug("PAM: setting PAM_RHOST to \"%s\"", pam_rhost);
+	sshpam_err = pam_set_item(sshpam_handle, PAM_RHOST, pam_rhost);
+	if (sshpam_err != PAM_SUCCESS) {
+		pam_end(sshpam_handle, sshpam_err);
+		sshpam_handle = NULL;
+		return (-1);
+	}
+	fatal_add_cleanup(sshpam_cleanup, NULL);
+	return (0);
 }
 
-/* Do account management using PAM */
-int do_pam_account(char *username, char *remote_user)
+static void *
+sshpam_init_ctx(Authctxt *authctxt)
 {
-	int pam_retval;
+	struct pam_ctxt *ctxt;
+	int socks[2];
 
-	do_pam_set_conv(&conv);
+	/* Initialize PAM */
+	if (sshpam_init(authctxt->user) == -1) {
+		error("PAM: initialization failed");
+		return (NULL);
+	}
 
-	if (remote_user) {
-		debug("PAM setting ruser to \"%.200s\"", remote_user);
-		pam_retval = pam_set_item(__pamh, PAM_RUSER, remote_user);
-		if (pam_retval != PAM_SUCCESS)
-			fatal("PAM set ruser failed[%d]: %.200s", pam_retval, 
-			    PAM_STRERROR(__pamh, pam_retval));
+	ctxt = xmalloc(sizeof *ctxt);
+	ctxt->pam_done = 0;
+
+	/* Start the authentication thread */
+	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, socks) == -1) {
+		error("PAM: failed create sockets: %s", strerror(errno));
+		xfree(ctxt);
+		return (NULL);
+	}
+	ctxt->pam_psock = socks[0];
+	ctxt->pam_csock = socks[1];
+	if (pthread_create(&ctxt->pam_thread, NULL, 
+	    sshpam_thread, ctxt) == -1) {
+		error("PAM: failed to start authentication thread: %s",
+		    strerror(errno));
+		close(socks[0]);
+		close(socks[1]);
+		xfree(ctxt);
+		return (NULL);
 	}
+	fatal_add_cleanup(sshpam_thread_cleanup, ctxt);
+	return (ctxt);
+}
 
-	pam_retval = pam_acct_mgmt(__pamh, 0);
-	debug2("pam_acct_mgmt() = %d", pam_retval);
-	switch (pam_retval) {
-		case PAM_SUCCESS:
-			/* This is what we want */
-			break;
-#if 0
-		case PAM_NEW_AUTHTOK_REQD:
-			message_cat(&__pam_msg, use_privsep ?
-			    NEW_AUTHTOK_MSG_PRIVSEP : NEW_AUTHTOK_MSG);
-			/* flag that password change is necessary */
-			password_change_required = 1;
-			/* disallow other functionality for now */
-			no_port_forwarding_flag |= 2;
-			no_agent_forwarding_flag |= 2;
-			no_x11_forwarding_flag |= 2;
+static int
+sshpam_query(void *ctx, char **name, char **info,
+    u_int *num, char ***prompts, u_int **echo_on)
+{
+	Buffer buffer;
+	struct pam_ctxt *ctxt = ctx;
+	size_t plen;
+	u_char type;
+	char *msg;
+
+	buffer_init(&buffer);
+	*name = xstrdup("");
+	*info = xstrdup("");
+	*prompts = xmalloc(sizeof(char *));
+	**prompts = NULL;
+	plen = 0;
+	*echo_on = xmalloc(sizeof(u_int));
+	while (ssh_msg_recv(ctxt->pam_psock, &buffer) == 0) {
+		type = buffer_get_char(&buffer);
+		msg = buffer_get_string(&buffer, NULL);
+		switch (type) {
+		case PAM_PROMPT_ECHO_ON:
+		case PAM_PROMPT_ECHO_OFF:
+			*num = 1;
+			**prompts = xrealloc(**prompts, plen + strlen(msg) + 1);
+			plen += sprintf(**prompts + plen, "%s", msg);
+			**echo_on = (type == PAM_PROMPT_ECHO_ON);
+			xfree(msg);
+			return (0);
+		case PAM_ERROR_MSG:
+		case PAM_TEXT_INFO:
+			/* accumulate messages */
+			**prompts = xrealloc(**prompts, plen + strlen(msg) + 1);
+			plen += sprintf(**prompts + plen, "%s", msg);
+			xfree(msg);
 			break;
+		case PAM_SUCCESS:
+		case PAM_AUTH_ERR:
+			if (**prompts != NULL) {
+				/* drain any accumulated messages */
+#if 0 /* XXX - not compatible with privsep */
+				packet_start(SSH2_MSG_USERAUTH_BANNER);
+				packet_put_cstring(**prompts);
+				packet_put_cstring("");
+				packet_send();
+				packet_write_wait();
 #endif
+				xfree(**prompts);
+				**prompts = NULL;
+			}
+			if (type == PAM_SUCCESS) {
+				*num = 0;
+				**echo_on = 0;
+				ctxt->pam_done = 1;
+				xfree(msg);
+				return (0);
+			}
+			error("PAM: %s", msg);
 		default:
-			log("PAM rejected by account configuration[%d]: "
-			    "%.200s", pam_retval, PAM_STRERROR(__pamh, 
-			    pam_retval));
-			return(0);
+			*num = 0;
+			**echo_on = 0;
+			xfree(msg);
+			ctxt->pam_done = -1;
+			return (-1);
+		}
 	}
-
-	return(1);
+	return (-1);
 }
 
-/* Do PAM-specific session initialisation */
-void do_pam_session(char *username, const char *ttyname)
+static int
+sshpam_respond(void *ctx, u_int num, char **resp)
 {
-	int pam_retval;
+	Buffer buffer;
+	struct pam_ctxt *ctxt = ctx;
 
-	do_pam_set_conv(&conv);
-
-	if (ttyname != NULL) {
-		debug("PAM setting tty to \"%.200s\"", ttyname);
-		pam_retval = pam_set_item(__pamh, PAM_TTY, ttyname);
-		if (pam_retval != PAM_SUCCESS)
-			fatal("PAM set tty failed[%d]: %.200s",
-			    pam_retval, PAM_STRERROR(__pamh, pam_retval));
+	debug2("PAM: %s", __func__);
+	switch (ctxt->pam_done) {
+	case 1:
+		sshpam_authenticated = 1;
+		return (0);
+	case 0:
+		break;
+	default:
+		return (-1);
 	}
-
-	pam_retval = pam_open_session(__pamh, 0);
-	if (pam_retval != PAM_SUCCESS)
-		fatal("PAM session setup failed[%d]: %.200s",
-		    pam_retval, PAM_STRERROR(__pamh, pam_retval));
-
-	session_opened = 1;
+	if (num != 1) {
+		error("PAM: expected one response, got %u", num);
+		return (-1);
+	}
+	buffer_init(&buffer);
+	buffer_put_cstring(&buffer, *resp);
+	ssh_msg_send(ctxt->pam_psock, PAM_AUTHTOK, &buffer);
+	buffer_free(&buffer);
+	return (1);
 }
 
-/* Set PAM credentials */
-void do_pam_setcred(int init)
+static void
+sshpam_free_ctx(void *ctxtp)
 {
-	int pam_retval;
-
-	if (__pamh == NULL)
-		return;
-
-	do_pam_set_conv(&conv);
+	struct pam_ctxt *ctxt = ctxtp;
 
-	debug("PAM establishing creds");
-	pam_retval = pam_setcred(__pamh, 
-	    init ? PAM_ESTABLISH_CRED : PAM_REINITIALIZE_CRED);
-	if (pam_retval != PAM_SUCCESS) {
-		if (was_authenticated)
-			fatal("PAM setcred failed[%d]: %.200s",
-			    pam_retval, PAM_STRERROR(__pamh, pam_retval));
-		else
-			debug("PAM setcred failed[%d]: %.200s",
-			    pam_retval, PAM_STRERROR(__pamh, pam_retval));
-	} else
-		creds_set = 1;
+	fatal_remove_cleanup(sshpam_thread_cleanup, ctxt);
+	sshpam_thread_cleanup(ctxtp);
+	xfree(ctxt);
+	/*
+	 * We don't call pam_cleanup() here because we may need the PAM
+	 * handle at a later stage, e.g. when setting up a session.  It's
+	 * still on the cleanup list, so pam_end() *will* be called before
+	 * the server process terminates.
+	 */
 }
 
-/* accessor function for file scope static variable */
-int is_pam_password_change_required(void)
-{
-	return password_change_required;
-}
+KbdintDevice sshpam_device = {
+	"pam",
+	sshpam_init_ctx,
+	sshpam_query,
+	sshpam_respond,
+	sshpam_free_ctx
+};
+
+KbdintDevice mm_sshpam_device = {
+	"pam",
+	mm_pam_init_ctx,
+	mm_pam_query,
+	mm_pam_respond,
+	mm_pam_free_ctx
+};
 
 /*
- * Have user change authentication token if pam_acct_mgmt() indicated
- * it was expired.  This needs to be called after an interactive
- * session is established and the user's pty is connected to
- * stdin/stdout/stderr.
+ * This replaces auth-pam.c
  */
-void do_pam_chauthtok(void)
+void
+start_pam(const char *user)
 {
-	int pam_retval;
-
-	do_pam_set_conv(&conv);
-
-	if (password_change_required) {
-		if (use_privsep)
-			fatal("Password changing is currently unsupported"
-			    " with privilege separation");
-		pamstate = OTHER;
-		pam_retval = pam_chauthtok(__pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
-		if (pam_retval != PAM_SUCCESS)
-			fatal("PAM pam_chauthtok failed[%d]: %.200s",
-			    pam_retval, PAM_STRERROR(__pamh, pam_retval));
-#if 0
-		/* XXX: This would need to be done in the parent process,
-		 * but there's currently no way to pass such request. */
-		no_port_forwarding_flag &= ~2;
-		no_agent_forwarding_flag &= ~2;
-		no_x11_forwarding_flag &= ~2;
-		if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
-			channel_permit_all_opens();
-#endif
-	}
+	if (sshpam_init(user) == -1)
+		fatal("PAM: initialisation failed");
 }
 
-/* Cleanly shutdown PAM */
-void finish_pam(void)
+void
+finish_pam(void)
 {
-	do_pam_cleanup_proc(NULL);
-	fatal_remove_cleanup(&do_pam_cleanup_proc, NULL);
+	fatal_remove_cleanup(sshpam_cleanup, NULL);
+	sshpam_cleanup(NULL);
 }
 
-/* Start PAM authentication for specified account */
-void start_pam(const char *user)
+void
+do_pam_session(const char *user, const char *tty)
 {
-	int pam_retval;
-	extern ServerOptions options;
-	extern u_int utmp_len;
-	const char *rhost;
-
-	debug("Starting up PAM with username \"%.200s\"", user);
-
-	pam_retval = pam_start(SSHD_PAM_SERVICE, user, &conv, &__pamh);
-
-	if (pam_retval != PAM_SUCCESS)
-		fatal("PAM initialisation failed[%d]: %.200s",
-		    pam_retval, PAM_STRERROR(__pamh, pam_retval));
-
-	rhost = get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping);
-	debug("PAM setting rhost to \"%.200s\"", rhost);
-
-	pam_retval = pam_set_item(__pamh, PAM_RHOST, rhost);
-	if (pam_retval != PAM_SUCCESS)
-		fatal("PAM set rhost failed[%d]: %.200s", pam_retval,
-		    PAM_STRERROR(__pamh, pam_retval));
-#ifdef PAM_TTY_KLUDGE
-	/*
-	 * Some PAM modules (e.g. pam_time) require a TTY to operate,
-	 * and will fail in various stupid ways if they don't get one.
-	 * sshd doesn't set the tty until too late in the auth process and may
-	 * not even need one (for tty-less connections)
-	 * Kludge: Set a fake PAM_TTY
-	 */
-	pam_retval = pam_set_item(__pamh, PAM_TTY, "NODEVssh");
-	if (pam_retval != PAM_SUCCESS)
-		fatal("PAM set tty failed[%d]: %.200s",
-		    pam_retval, PAM_STRERROR(__pamh, pam_retval));
-#endif /* PAM_TTY_KLUDGE */
+	debug("PAM: setting PAM_TTY to \"%s\"", tty);
+	sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, tty);
+	if (sshpam_err != PAM_SUCCESS)
+		fatal("PAM: failed to set PAM_TTY: %s",
+		    pam_strerror(sshpam_handle, sshpam_err));
+	sshpam_err = pam_open_session(sshpam_handle, 0);
+	if (sshpam_err != PAM_SUCCESS)
+		fatal("PAM: pam_open_session(): %s",
+		    pam_strerror(sshpam_handle, sshpam_err));
+	sshpam_session_open = 1;
+}
 
-	fatal_add_cleanup(&do_pam_cleanup_proc, NULL);
+void
+do_pam_setcred(int init)
+{
+	if (init) {
+		debug("PAM: establishing credentials");
+		sshpam_err = pam_setcred(sshpam_handle, PAM_ESTABLISH_CRED);
+	} else {
+		debug("PAM: reinitializing credentials");
+		sshpam_err = pam_setcred(sshpam_handle, PAM_REINITIALIZE_CRED);
+	}
+	if (sshpam_err == PAM_SUCCESS) {
+		sshpam_cred_established = 1;
+		return;
+	}
+	if (sshpam_authenticated)
+		fatal("PAM: pam_setcred(): %s",
+		    pam_strerror(sshpam_handle, sshpam_err));
+	else
+		debug("PAM: pam_setcred(): %s",
+		    pam_strerror(sshpam_handle, sshpam_err));
 }
 
-/* Return list of PAM environment strings */
-char **fetch_pam_environment(void)
+int
+is_pam_password_change_required(void)
 {
-#ifdef HAVE_PAM_GETENVLIST
-	return(pam_getenvlist(__pamh));
-#else /* HAVE_PAM_GETENVLIST */
-	return(NULL);
-#endif /* HAVE_PAM_GETENVLIST */
+	return (sshpam_new_authtok_reqd);
 }
 
-void free_pam_environment(char **env)
+static int
+pam_chauthtok_conv(int n,
+	 const struct pam_message **msg,
+	 struct pam_response **resp,
+	 void *data)
 {
+	char input[PAM_MAX_MSG_SIZE];
 	int i;
 
-	if (env != NULL) {
-		for (i = 0; env[i] != NULL; i++)
-			xfree(env[i]);
+	if (n <= 0 || n > PAM_MAX_NUM_MSG)
+		return (PAM_CONV_ERR);
+	*resp = xmalloc(n * sizeof **resp);
+	for (i = 0; i < n; ++i) {
+		switch (msg[i]->msg_style) {
+		case PAM_PROMPT_ECHO_OFF:
+			resp[i]->resp =
+			    read_passphrase(msg[i]->msg, RP_ALLOW_STDIN);
+			resp[i]->resp_retcode = PAM_SUCCESS;
+			break;
+		case PAM_PROMPT_ECHO_ON:
+			fputs(msg[i]->msg, stderr);
+			fgets(input, sizeof input, stdin);
+			resp[i]->resp = xstrdup(input);
+			resp[i]->resp_retcode = PAM_SUCCESS;
+			break;
+		case PAM_ERROR_MSG:
+		case PAM_TEXT_INFO:
+			fputs(msg[i]->msg, stderr);
+			resp[i]->resp_retcode = PAM_SUCCESS;
+			break;
+		default:
+			goto fail;
+		}
 	}
+	return (PAM_SUCCESS);
+ fail:
+	while (i)
+		xfree(resp[--i]);
+	xfree(*resp);
+	*resp = NULL;
+	return (PAM_CONV_ERR);
 }
 
-/* Print any messages that have been generated during authentication */
-/* or account checking to stderr */
-void print_pam_messages(void)
+/*
+ * XXX this should be done in the authentication phase, but ssh1 doesn't
+ * support that
+ */
+void
+do_pam_chauthtok(void)
 {
-	if (__pam_msg != NULL)
-		fputs(__pam_msg, stderr);
+	struct pam_conv pam_conv = { pam_chauthtok_conv, NULL };
+
+	if (use_privsep)
+		fatal("PAM: chauthtok not supprted with privsep");
+	sshpam_err = pam_set_item(sshpam_handle,
+	    PAM_CONV, (const void *)&pam_conv);
+	if (sshpam_err != PAM_SUCCESS)
+		fatal("PAM: failed to set PAM_CONV: %s",
+		    pam_strerror(sshpam_handle, sshpam_err));
+	debug("PAM: changing password");
+	sshpam_err = pam_chauthtok(sshpam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
+	if (sshpam_err != PAM_SUCCESS)
+		fatal("PAM: pam_chauthtok(): %s",
+		    pam_strerror(sshpam_handle, sshpam_err));
 }
 
-/* Append a message to buffer */
-void message_cat(char **p, const char *a)
+void
+print_pam_messages(void)
 {
-	char *cp;
-	size_t new_len;
-
-	new_len = strlen(a);
+	/* XXX */
+}
 
-	if (*p) {
-		size_t len = strlen(*p);
+char **
+fetch_pam_environment(void)
+{
+#ifdef HAVE_PAM_GETENVLIST
+	debug("PAM: retrieving environment");
+	return (pam_getenvlist(sshpam_handle));
+#else
+	return (NULL);
+#endif
+}
 
-		*p = xrealloc(*p, new_len + len + 2);
-		cp = *p + len;
-	} else
-		*p = cp = xmalloc(new_len + 2);
+void
+free_pam_environment(char **env)
+{
+	char **envp;
 
-	memcpy(cp, a, new_len);
-	cp[new_len] = '\n';
-	cp[new_len + 1] = '\0';
+	for (envp = env; *envp; envp++)
+		xfree(*envp);
+	xfree(env);
 }
 
 #endif /* USE_PAM */
Index: auth-pam.h
===================================================================
RCS file: /var/cvs/openssh/auth-pam.h,v
retrieving revision 1.16
diff -u -r1.16 auth-pam.h
--- auth-pam.h	23 Jul 2002 00:44:07 -0000	1.16
+++ auth-pam.h	10 Jan 2003 01:16:56 -0000
@@ -1,4 +1,5 @@
 /* $Id: auth-pam.h,v 1.16 2002/07/23 00:44:07 stevesk Exp $ */
+/* $FreeBSD: src/crypto/openssh/auth-pam.h,v 1.6 2002/12/14 13:52:39 des Exp $ */
 
 /*
  * Copyright (c) 2000 Damien Miller.  All rights reserved.
@@ -37,8 +38,8 @@
 char **fetch_pam_environment(void);
 void free_pam_environment(char **env);
 int do_pam_authenticate(int flags);
-int do_pam_account(char *username, char *remote_user);
-void do_pam_session(char *username, const char *ttyname);
+int do_pam_account(const char *username, const char *remote_user);
+void do_pam_session(const char *username, const char *ttyname);
 void do_pam_setcred(int init);
 void print_pam_messages(void);
 int is_pam_password_change_required(void);
Index: auth-passwd.c
===================================================================
RCS file: /var/cvs/openssh/auth-passwd.c,v
retrieving revision 1.48
diff -u -r1.48 auth-passwd.c
--- auth-passwd.c	25 Sep 2002 23:14:16 -0000	1.48
+++ auth-passwd.c	10 Jan 2003 01:16:56 -0000
@@ -43,7 +43,7 @@
 #include "servconf.h"
 #include "auth.h"
 
-#if !defined(USE_PAM) && !defined(HAVE_OSF_SIA)
+#if !defined(HAVE_OSF_SIA)
 /* Don't need any of these headers for the PAM or SIA cases */
 # ifdef HAVE_CRYPT_H
 #  include <crypt.h>
@@ -78,7 +78,7 @@
 #  include <sys/cygwin.h>
 #  define is_winnt       (GetVersion() < 0x80000000)
 # endif
-#endif /* !USE_PAM && !HAVE_OSF_SIA */
+#endif /* !HAVE_OSF_SIA */
 
 extern ServerOptions options;
 #ifdef WITH_AIXAUTHENTICATE
@@ -92,11 +92,7 @@
 int
 auth_password(Authctxt *authctxt, const char *password)
 {
-#if defined(USE_PAM)
-	if (*password == '\0' && options.permit_empty_passwd == 0)
-		return 0;
-	return auth_pam_password(authctxt, password);
-#elif defined(HAVE_OSF_SIA)
+#if defined(HAVE_OSF_SIA)
 	if (*password == '\0' && options.permit_empty_passwd == 0)
 		return 0;
 	return auth_sia_password(authctxt, password);
@@ -231,5 +227,5 @@
 
 	/* Authentication is accepted if the encrypted passwords are identical. */
 	return (strcmp(encrypted_password, pw_password) == 0);
-#endif /* !USE_PAM && !HAVE_OSF_SIA */
+#endif /* !HAVE_OSF_SIA */
 }
Index: auth.h
===================================================================
RCS file: /var/cvs/openssh/auth.h,v
retrieving revision 1.44
diff -u -r1.44 auth.h
--- auth.h	27 Sep 2002 03:26:01 -0000	1.44
+++ auth.h	10 Jan 2003 01:16:57 -0000
@@ -133,7 +133,6 @@
 #endif /* KRB5 */
 
 #include "auth-pam.h"
-#include "auth2-pam.h"
 
 Authctxt *do_authentication(void);
 Authctxt *do_authentication2(void);
Index: auth1.c
===================================================================
RCS file: /var/cvs/openssh/auth1.c,v
retrieving revision 1.77
diff -u -r1.77 auth1.c
--- auth1.c	23 Dec 2002 02:06:20 -0000	1.77
+++ auth1.c	10 Jan 2003 01:16:57 -0000
@@ -334,11 +334,6 @@
 		    !auth_root_allowed(get_authname(type)))
 			authenticated = 0;
 #endif
-#ifdef USE_PAM
-		if (!use_privsep && authenticated && 
-		    !do_pam_account(pw->pw_name, client_user))
-			authenticated = 0;
-#endif
 
 		/* Log before sending the reply */
 		auth_log(authctxt, authenticated, get_authname(type), info);
Index: auth2-chall.c
===================================================================
RCS file: /var/cvs/openssh/auth2-chall.c,v
retrieving revision 1.20
diff -u -r1.20 auth2-chall.c
--- auth2-chall.c	4 Jul 2002 00:14:18 -0000	1.20
+++ auth2-chall.c	10 Jan 2003 01:16:58 -0000
@@ -45,6 +45,9 @@
 extern KbdintDevice skey_device;
 #endif
 #endif
+#ifdef USE_PAM
+extern KbdintDevice sshpam_device;
+#endif
 
 KbdintDevice *devices[] = {
 #ifdef BSD_AUTH
@@ -54,6 +57,9 @@
 	&skey_device,
 #endif
 #endif
+#ifdef USE_PAM
+	&sshpam_device,
+#endif
 	NULL
 };
 
@@ -323,15 +329,22 @@
 #ifdef BSD_AUTH
 	extern KbdintDevice mm_bsdauth_device;
 #endif
+#ifdef USE_PAM
+	extern KbdintDevice mm_sshpam_device;
+#endif
 #ifdef SKEY
 	extern KbdintDevice mm_skey_device;
 #endif
-	/* As long as SSHv1 has devices[0] hard coded this is fine */
+	int n = 0;
+
 #ifdef BSD_AUTH
-	devices[0] = &mm_bsdauth_device;
+	devices[n++] = &mm_bsdauth_device;
 #else
+#ifdef USE_PAM
+	devices[n++] = &mm_sshpam_device;
+#endif
 #ifdef SKEY
-	devices[0] = &mm_skey_device;
+	devices[n++] = &mm_skey_device;
 #endif
 #endif
 }
Index: auth2-kbdint.c
===================================================================
RCS file: /var/cvs/openssh/auth2-kbdint.c,v
retrieving revision 1.1
diff -u -r1.1 auth2-kbdint.c
--- auth2-kbdint.c	6 Jun 2002 20:27:56 -0000	1.1
+++ auth2-kbdint.c	10 Jan 2003 01:16:58 -0000
@@ -49,10 +49,6 @@
 	if (options.challenge_response_authentication)
 		authenticated = auth2_challenge(authctxt, devs);
 
-#ifdef USE_PAM
-	if (authenticated == 0 && options.pam_authentication_via_kbd_int)
-		authenticated = auth2_pam(authctxt);
-#endif
 	xfree(devs);
 	xfree(lang);
 #ifdef HAVE_CYGWIN
Index: auth2-pam.c
===================================================================
RCS file: auth2-pam.c
diff -N auth2-pam.c
--- auth2-pam.c	8 Jan 2003 01:37:03 -0000	1.15
+++ /dev/null	1 Jan 1970 00:00:00 -0000
@@ -1,165 +0,0 @@
-#include "includes.h"
-RCSID("$Id: auth2-pam.c,v 1.15 2003/01/08 01:37:03 djm Exp $");
-
-#ifdef USE_PAM
-#include <security/pam_appl.h>
-
-#include "ssh.h"
-#include "ssh2.h"
-#include "auth.h"
-#include "auth-pam.h"
-#include "packet.h"
-#include "xmalloc.h"
-#include "dispatch.h"
-#include "log.h"
-
-static int do_pam_conversation_kbd_int(int num_msg, 
-    const struct pam_message **msg, struct pam_response **resp, 
-    void *appdata_ptr);
-void input_userauth_info_response_pam(int type, u_int32_t seqnr, void *ctxt);
-
-struct {
-	int finished, num_received, num_expected;
-	int *prompts;
-	struct pam_response *responses;
-} context_pam2 = {0, 0, 0, NULL};
-
-static struct pam_conv conv2 = {
-	do_pam_conversation_kbd_int,
-	NULL,
-};
-
-int
-auth2_pam(Authctxt *authctxt)
-{
-	int retval = -1;
-
-	if (authctxt->user == NULL)
-		fatal("auth2_pam: internal error: no user");
-
-	conv2.appdata_ptr = authctxt;
-	do_pam_set_conv(&conv2);
-
-	dispatch_set(SSH2_MSG_USERAUTH_INFO_RESPONSE,
-	    &input_userauth_info_response_pam);
-	retval = (do_pam_authenticate(0) == PAM_SUCCESS);
-	dispatch_set(SSH2_MSG_USERAUTH_INFO_RESPONSE, NULL);
-
-	return retval;
-}
-
-static int
-do_pam_conversation_kbd_int(int num_msg, const struct pam_message **msg,
-    struct pam_response **resp, void *appdata_ptr)
-{
-	int i, j, done;
-	char *text;
-
-	context_pam2.finished = 0;
-	context_pam2.num_received = 0;
-	context_pam2.num_expected = 0;
-	context_pam2.prompts = xmalloc(sizeof(int) * num_msg);
-	context_pam2.responses = xmalloc(sizeof(struct pam_response) * num_msg);
-	memset(context_pam2.responses, 0, sizeof(struct pam_response) * num_msg);
-
-	text = NULL;
-	for (i = 0, context_pam2.num_expected = 0; i < num_msg; i++) {
-		int style = PAM_MSG_MEMBER(msg, i, msg_style);
-		switch (style) {
-		case PAM_PROMPT_ECHO_ON:
-		case PAM_PROMPT_ECHO_OFF:
-			context_pam2.num_expected++;
-			break;
-		case PAM_TEXT_INFO:
-		case PAM_ERROR_MSG:
-		default:
-			/* Capture all these messages to be sent at once */
-			message_cat(&text, PAM_MSG_MEMBER(msg, i, msg));
-			break;
-		}
-	}
-
-	if (context_pam2.num_expected == 0)
-		return PAM_SUCCESS;
-
-	packet_start(SSH2_MSG_USERAUTH_INFO_REQUEST);
-	packet_put_cstring("");	/* Name */
-	packet_put_cstring("");	/* Instructions */
-	packet_put_cstring("");	/* Language */
-	packet_put_int(context_pam2.num_expected);
-	
-	for (i = 0, j = 0; i < num_msg; i++) {
-		int style = PAM_MSG_MEMBER(msg, i, msg_style);
-		
-		/* Skip messages which don't need a reply */
-		if (style != PAM_PROMPT_ECHO_ON && style != PAM_PROMPT_ECHO_OFF)
-			continue;
-		
-		context_pam2.prompts[j++] = i;
-		if (text) {
-			message_cat(&text, PAM_MSG_MEMBER(msg, i, msg));
-			packet_put_cstring(text);
-			text = NULL;
-		} else
-			packet_put_cstring(PAM_MSG_MEMBER(msg, i, msg));
-		packet_put_char(style == PAM_PROMPT_ECHO_ON);
-	}
-	packet_send();
-	packet_write_wait();
-
-	/*
-	 * Grabbing control of execution and spinning until we get what
-	 * we want is probably rude, but it seems to work properly, and
-	 * the client *should* be in lock-step with us, so the loop should
-	 * only be traversed once.
-	 */
-	while(context_pam2.finished == 0) {
-		done = 1;
-		dispatch_run(DISPATCH_BLOCK, &done, appdata_ptr);
-		if (context_pam2.finished == 0)
-			debug("extra packet during conversation");
-	}
-
-	if (context_pam2.num_received == context_pam2.num_expected) {
-		*resp = context_pam2.responses;
-		return PAM_SUCCESS;
-	} else
-		return PAM_CONV_ERR;
-}
-
-void
-input_userauth_info_response_pam(int type, u_int32_t seqnr, void *ctxt)
-{
-	Authctxt *authctxt = ctxt;
-	unsigned int nresp = 0, rlen = 0, i = 0;
-	char *resp;
-
-	if (authctxt == NULL)
-		fatal("input_userauth_info_response_pam: no authentication context");
-
-	nresp = packet_get_int();	/* Number of responses. */
-	debug("got %d responses", nresp);
-
-
-	if (nresp != context_pam2.num_expected)
-		fatal("%s: Received incorrect number of responses "
-		    "(expected %d, received %u)", __func__, 
-		    context_pam2.num_expected, nresp);
-
-	if (nresp > 100)
-		fatal("%s: too many replies", __func__);
-
-	for (i = 0; i < nresp; i++) {
-		int j = context_pam2.prompts[i];
-
-		resp = packet_get_string(&rlen);
-		context_pam2.responses[j].resp_retcode = PAM_SUCCESS;
-		context_pam2.responses[j].resp = resp;
-		context_pam2.num_received++;
-	}
-
-	context_pam2.finished = 1;
-
-	packet_check_eom();
-}
-#endif
Index: auth2-pam.h
===================================================================
RCS file: auth2-pam.h
diff -N auth2-pam.h
--- auth2-pam.h	9 Feb 2001 01:55:36 -0000	1.2
+++ /dev/null	1 Jan 1970 00:00:00 -0000
@@ -1,8 +0,0 @@
-/* $Id: auth2-pam.h,v 1.2 2001/02/09 01:55:36 djm Exp $ */
-
-#include "includes.h"
-#ifdef USE_PAM
-
-int	auth2_pam(Authctxt *authctxt);
-
-#endif /* USE_PAM */
Index: auth2.c
===================================================================
RCS file: /var/cvs/openssh/auth2.c,v
retrieving revision 1.111
diff -u -r1.111 auth2.c
--- auth2.c	26 Sep 2002 00:38:49 -0000	1.111
+++ auth2.c	10 Jan 2003 01:16:58 -0000
@@ -85,10 +85,6 @@
 	/* challenge-response is implemented via keyboard interactive */
 	if (options.challenge_response_authentication)
 		options.kbd_interactive_authentication = 1;
-	if (options.pam_authentication_via_kbd_int)
-		options.kbd_interactive_authentication = 1;
-	if (use_privsep)
-		options.pam_authentication_via_kbd_int = 0;
 
 	dispatch_init(&dispatch_protocol_error);
 	dispatch_set(SSH2_MSG_SERVICE_REQUEST, &input_service_request);
@@ -209,12 +205,6 @@
 	    authenticated && authctxt->pw->pw_uid == 0 &&
 	    !auth_root_allowed(method))
 		authenticated = 0;
-
-#ifdef USE_PAM
-	if (!use_privsep && authenticated && authctxt->user && 
-	    !do_pam_account(authctxt->user, NULL))
-		authenticated = 0;
-#endif /* USE_PAM */
 
 #ifdef _UNICOS
 	if (authenticated && cray_access_denied(authctxt->user)) {
Index: configure.ac
===================================================================
RCS file: /var/cvs/openssh/configure.ac,v
retrieving revision 1.98
diff -u -r1.98 configure.ac
--- configure.ac	9 Jan 2003 22:53:12 -0000	1.98
+++ configure.ac	10 Jan 2003 01:17:01 -0000
@@ -892,8 +892,8 @@
 )
 
 # Some Linux systems (Slackware) need crypt() from libcrypt, *not* the 
-# version in OpenSSL. Skip this for PAM
-if test "x$PAM_MSG" = "xno" -a "x$check_for_libcrypt_later" = "x1"; then
+# version in OpenSSL.
+if test "x$check_for_libcrypt_later" = "x1"; then
 	AC_CHECK_LIB(crypt, crypt, LIBS="$LIBS -lcrypt")
 fi
 
@@ -1696,7 +1696,11 @@
 		ac_cv_have_getopt_optreset, [
 	AC_TRY_LINK(
 		[
+#if HAVE_GETOPT_H
 #include <getopt.h>
+#elif HAVE_UNISTD_H
+#include <unistd.h>
+#endif
 		],
 		[ extern int optreset; optreset = 0; ],
 		[ ac_cv_have_getopt_optreset="yes" ],
Index: monitor.c
===================================================================
RCS file: /var/cvs/openssh/monitor.c,v
retrieving revision 1.33
diff -u -r1.33 monitor.c
--- monitor.c	9 Nov 2002 15:47:49 -0000	1.33
+++ monitor.c	10 Jan 2003 01:17:03 -0000
@@ -118,6 +118,10 @@
 
 #ifdef USE_PAM
 int mm_answer_pam_start(int, Buffer *);
+int mm_answer_pam_init_ctx(int, Buffer *);
+int mm_answer_pam_query(int, Buffer *);
+int mm_answer_pam_respond(int, Buffer *);
+int mm_answer_pam_free_ctx(int, Buffer *);
 #endif
 
 #ifdef KRB4
@@ -163,6 +167,10 @@
     {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
 #ifdef USE_PAM
     {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
+    {MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx},
+    {MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query},
+    {MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond},
+    {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
 #endif
 #ifdef BSD_AUTH
     {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
@@ -205,6 +213,10 @@
 #endif
 #ifdef USE_PAM
     {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
+    {MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx},
+    {MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query},
+    {MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond},
+    {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
 #endif
 #ifdef KRB4
     {MONITOR_REQ_KRB4, MON_ONCE|MON_AUTH, mm_answer_krb4},
@@ -285,10 +297,6 @@
 			if (authctxt->pw->pw_uid == 0 &&
 			    !auth_root_allowed(auth_method))
 				authenticated = 0;
-#ifdef USE_PAM
-			if (!do_pam_account(authctxt->pw->pw_name, NULL))
-				authenticated = 0;
-#endif
 		}
 
 		if (ent->flags & MON_AUTHDECIDE) {
@@ -746,6 +754,102 @@
 	xfree(user);
 
 	return (0);
+}
+
+static void *sshpam_ctxt, *sshpam_authok;
+extern KbdintDevice sshpam_device;
+
+int
+mm_answer_pam_init_ctx(int socket, Buffer *m)
+{
+
+	debug3("%s", __func__);
+	authctxt->user = buffer_get_string(m, NULL);
+	sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
+	sshpam_authok = NULL;
+	buffer_clear(m);
+	if (sshpam_ctxt != NULL) {
+		monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
+		buffer_put_int(m, 1);
+	} else {
+		buffer_put_int(m, 0);
+	}
+	mm_request_send(socket, MONITOR_ANS_PAM_INIT_CTX, m);
+	return (0);
+}
+
+int
+mm_answer_pam_query(int socket, Buffer *m)
+{
+	char *name, *info, **prompts;
+	u_int num, *echo_on;
+	int i, ret;
+
+	debug3("%s", __func__);
+	sshpam_authok = NULL;
+	ret = (sshpam_device.query)(sshpam_ctxt, &name, &info, 
+	    &num, &prompts, &echo_on);
+	if (num > 1 || name == NULL || info == NULL)
+		ret = -1;
+	buffer_clear(m);
+	buffer_put_int(m, ret);
+	buffer_put_cstring(m, name);
+	xfree(name);
+	buffer_put_cstring(m, info);
+	xfree(info);
+	buffer_put_int(m, num);
+	for (i = 0; i < num; ++i) {
+		buffer_put_cstring(m, prompts[i]);
+		xfree(prompts[i]);
+		buffer_put_int(m, echo_on[i]);
+	}
+	if (prompts != NULL)
+		xfree(prompts);
+	if (echo_on != NULL)
+		xfree(echo_on);
+	mm_request_send(socket, MONITOR_ANS_PAM_QUERY, m);
+	return (0);
+}
+
+int
+mm_answer_pam_respond(int socket, Buffer *m)
+{
+	char **resp;
+	u_int num;
+	int i, ret;
+
+	debug3("%s", __func__);
+	sshpam_authok = NULL;
+	num = buffer_get_int(m);
+	if (num > 0) {
+		resp = xmalloc(num * sizeof(char *));
+		for (i = 0; i < num; ++i)
+			resp[i] = buffer_get_string(m, NULL);
+		ret = (sshpam_device.respond)(sshpam_ctxt, num, resp);
+		for (i = 0; i < num; ++i)
+			xfree(resp[i]);
+		xfree(resp);
+	} else {
+		ret = (sshpam_device.respond)(sshpam_ctxt, num, NULL);
+	}
+	buffer_clear(m);
+	buffer_put_int(m, ret);
+	mm_request_send(socket, MONITOR_ANS_PAM_RESPOND, m);
+	auth_method = "keyboard-interactive/pam";
+	if (ret == 0)
+		sshpam_authok = sshpam_ctxt;
+	return (0);
+}
+
+int
+mm_answer_pam_free_ctx(int socket, Buffer *m)
+{
+
+	debug3("%s", __func__);
+	(sshpam_device.free_ctx)(sshpam_ctxt);
+	buffer_clear(m);
+	mm_request_send(socket, MONITOR_ANS_PAM_FREE_CTX, m);
+	return (sshpam_authok == sshpam_ctxt);
 }
 #endif
 
Index: monitor.h
===================================================================
RCS file: /var/cvs/openssh/monitor.h,v
retrieving revision 1.10
diff -u -r1.10 monitor.h
--- monitor.h	27 Sep 2002 03:26:02 -0000	1.10
+++ monitor.h	10 Jan 2003 01:17:03 -0000
@@ -52,6 +52,10 @@
 	MONITOR_REQ_KRB4, MONITOR_ANS_KRB4,
  	MONITOR_REQ_KRB5, MONITOR_ANS_KRB5,
 	MONITOR_REQ_PAM_START,
+	MONITOR_REQ_PAM_INIT_CTX, MONITOR_ANS_PAM_INIT_CTX,
+	MONITOR_REQ_PAM_QUERY, MONITOR_ANS_PAM_QUERY,
+	MONITOR_REQ_PAM_RESPOND, MONITOR_ANS_PAM_RESPOND,
+	MONITOR_REQ_PAM_FREE_CTX, MONITOR_ANS_PAM_FREE_CTX,
 	MONITOR_REQ_TERM
 };
 
Index: monitor_wrap.c
===================================================================
RCS file: /var/cvs/openssh/monitor_wrap.c,v
retrieving revision 1.21
diff -u -r1.21 monitor_wrap.c
--- monitor_wrap.c	23 Dec 2002 02:06:20 -0000	1.21
+++ monitor_wrap.c	10 Jan 2003 01:17:04 -0000
@@ -663,6 +663,88 @@
 
 	buffer_free(&m);
 }
+
+void *
+mm_pam_init_ctx(Authctxt *authctxt)
+{
+	Buffer m;
+	int success;
+
+	debug3("%s", __func__);
+	buffer_init(&m);
+	buffer_put_cstring(&m, authctxt->user);
+	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m);
+	debug3("%s: waiting for MONITOR_ANS_PAM_INIT_CTX", __func__);
+	mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m);
+	success = buffer_get_int(&m);
+	if (success == 0) {
+		debug3("%s: pam_init_ctx failed", __func__);
+		buffer_free(&m);
+		return (NULL);
+	}
+	buffer_free(&m);
+	return (authctxt);
+}
+
+int
+mm_pam_query(void *ctx, char **name, char **info,
+    u_int *num, char ***prompts, u_int **echo_on)
+{
+	Buffer m;
+	int i, ret;
+
+	debug3("%s", __func__);
+	buffer_init(&m);
+	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_QUERY, &m);
+	debug3("%s: waiting for MONITOR_ANS_PAM_QUERY", __func__);
+	mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_QUERY, &m);
+	ret = buffer_get_int(&m);
+	debug3("%s: pam_query returned %d", __func__, ret);
+	*name = buffer_get_string(&m, NULL);
+	*info = buffer_get_string(&m, NULL);
+	*num = buffer_get_int(&m);
+	*prompts = xmalloc((*num + 1) * sizeof(char *));
+	*echo_on = xmalloc((*num + 1) * sizeof(u_int));
+	for (i = 0; i < *num; ++i) {
+		(*prompts)[i] = buffer_get_string(&m, NULL);
+		(*echo_on)[i] = buffer_get_int(&m);
+	}
+	buffer_free(&m);
+	return (ret);
+}
+
+int
+mm_pam_respond(void *ctx, u_int num, char **resp)
+{
+	Buffer m;
+	int i, ret;
+
+	debug3("%s", __func__);
+	buffer_init(&m);
+	buffer_put_int(&m, num);
+	for (i = 0; i < num; ++i)
+		buffer_put_cstring(&m, resp[i]);
+	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_RESPOND, &m);
+	debug3("%s: waiting for MONITOR_ANS_PAM_RESPOND", __func__);
+	mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_RESPOND, &m);
+	ret = buffer_get_int(&m);
+	debug3("%s: pam_respond returned %d", __func__, ret);
+	buffer_free(&m);
+	return (ret);
+}
+
+void
+mm_pam_free_ctx(void *ctxtp)
+{
+	Buffer m;
+
+	debug3("%s", __func__);
+	buffer_init(&m);
+	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_FREE_CTX, &m);
+	debug3("%s: waiting for MONITOR_ANS_PAM_FREE_CTX", __func__);
+	mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_FREE_CTX, &m);
+	buffer_free(&m);
+}
 #endif /* USE_PAM */
 
 /* Request process termination */
Index: monitor_wrap.h
===================================================================
RCS file: /var/cvs/openssh/monitor_wrap.h,v
retrieving revision 1.9
diff -u -r1.9 monitor_wrap.h
--- monitor_wrap.h	27 Sep 2002 03:26:04 -0000	1.9
+++ monitor_wrap.h	10 Jan 2003 01:17:04 -0000
@@ -57,6 +57,10 @@
 
 #ifdef USE_PAM
 void mm_start_pam(char *);
+void *mm_pam_init_ctx(struct Authctxt *);
+int mm_pam_query(void *, char **, char **, u_int *, char ***, u_int **);
+int mm_pam_respond(void *, u_int, char **);
+void mm_pam_free_ctx(void *);
 #endif
 
 void mm_terminate(void);
Index: servconf.c
===================================================================
RCS file: /var/cvs/openssh/servconf.c,v
retrieving revision 1.97
diff -u -r1.97 servconf.c
--- servconf.c	5 Sep 2002 04:35:15 -0000	1.97
+++ servconf.c	10 Jan 2003 01:17:05 -0000
@@ -55,10 +55,6 @@
 {
 	memset(options, 0, sizeof(*options));
 
-	/* Portable-specific options */
-	options->pam_authentication_via_kbd_int = -1;
-
-	/* Standard Options */
 	options->num_ports = 0;
 	options->ports_from_cmdline = 0;
 	options->listen_addrs = NULL;
@@ -131,10 +127,6 @@
 void
 fill_default_server_options(ServerOptions *options)
 {
-	/* Portable-specific options */
-	if (options->pam_authentication_via_kbd_int == -1)
-		options->pam_authentication_via_kbd_int = 0;
-
 	/* Standard Options */
 	if (options->protocol == SSH_PROTO_UNKNOWN)
 		options->protocol = SSH_PROTO_1|SSH_PROTO_2;
@@ -274,9 +266,6 @@
 /* Keyword tokens. */
 typedef enum {
 	sBadOption,		/* == unknown option */
-	/* Portable-specific options */
-	sPAMAuthenticationViaKbdInt,
-	/* Standard Options */
 	sPort, sHostKeyFile, sServerKeyBits, sLoginGraceTime, sKeyRegenerationTime,
 	sPermitRootLogin, sLogFacility, sLogLevel,
 	sRhostsAuthentication, sRhostsRSAAuthentication, sRSAAuthentication,
@@ -310,9 +299,6 @@
 	const char *name;
 	ServerOpCodes opcode;
 } keywords[] = {
-	/* Portable-specific options */
-	{ "PAMAuthenticationViaKbdInt", sPAMAuthenticationViaKbdInt },
-	/* Standard Options */
 	{ "port", sPort },
 	{ "hostkey", sHostKeyFile },
 	{ "hostdsakey", sHostKeyFile },					/* alias */
@@ -457,12 +443,6 @@
 	charptr = NULL;
 	opcode = parse_token(arg, filename, linenum);
 	switch (opcode) {
-	/* Portable-specific options */
-	case sPAMAuthenticationViaKbdInt:
-		intptr = &options->pam_authentication_via_kbd_int;
-		goto parse_flag;
-
-	/* Standard Options */
 	case sBadOption:
 		return -1;
 	case sPort:
Index: servconf.h
===================================================================
RCS file: /var/cvs/openssh/servconf.h,v
retrieving revision 1.50
diff -u -r1.50 servconf.h
--- servconf.h	1 Aug 2002 01:28:39 -0000	1.50
+++ servconf.h	10 Jan 2003 01:17:06 -0000
@@ -131,7 +131,6 @@
 
 	char   *authorized_keys_file;	/* File containing public keys */
 	char   *authorized_keys_file2;
-	int	pam_authentication_via_kbd_int;
 }       ServerOptions;
 
 void	 initialize_server_options(ServerOptions *);
Index: sshd_config
===================================================================
RCS file: /var/cvs/openssh/sshd_config,v
retrieving revision 1.55
diff -u -r1.55 sshd_config
--- sshd_config	27 Sep 2002 03:21:58 -0000	1.55
+++ sshd_config	10 Jan 2003 01:17:06 -0000
@@ -69,10 +69,6 @@
 # Kerberos TGT Passing only works with the AFS kaserver
 #KerberosTgtPassing no
 
-# Set this to 'yes' to enable PAM keyboard-interactive authentication 
-# Warning: enabling this may bypass the setting of 'PasswordAuthentication'
-#PAMAuthenticationViaKbdInt no
-
 #X11Forwarding no
 #X11DisplayOffset 10
 #X11UseLocalhost yes
Index: sshd_config.5
===================================================================
RCS file: /var/cvs/openssh/sshd_config.5,v
retrieving revision 1.12
diff -u -r1.12 sshd_config.5
--- sshd_config.5	19 Sep 2002 01:51:22 -0000	1.12
+++ sshd_config.5	10 Jan 2003 01:17:07 -0000
@@ -421,12 +421,6 @@
 are refused if the number of unauthenticated connections reaches
 .Dq full
 (60).
-.It Cm PAMAuthenticationViaKbdInt
-Specifies whether PAM challenge response authentication is allowed. This
-allows the use of most PAM challenge response authentication modules, but
-it will allow password authentication regardless of whether
-.Cm PasswordAuthentication
-is enabled.
 .It Cm PasswordAuthentication
 Specifies whether password authentication is allowed.
 The default is
