[108349] trunk/dports/net/openssh

cal at macports.org cal at macports.org
Sat Jul 20 09:53:18 PDT 2013


Revision: 108349
          https://trac.macports.org/changeset/108349
Author:   cal at macports.org
Date:     2013-07-20 09:53:18 -0700 (Sat, 20 Jul 2013)
Log Message:
-----------
openssh: fix +gsskex variant

Modified Paths:
--------------
    trunk/dports/net/openssh/Portfile
    trunk/dports/net/openssh/files/apple-keychain.patch

Added Paths:
-----------
    trunk/dports/net/openssh/files/0002-Apple-keychain-integration-other-changes.patch
    trunk/dports/net/openssh/files/openssh-6.2p2-gsskex-all-20110125.patch

Removed Paths:
-------------
    trunk/dports/net/openssh/files/openssh-5.0p1-gsskex-20080404.patch
    trunk/dports/net/openssh/files/openssh-5.9p1-gsskex-all-20110920.patch

Modified: trunk/dports/net/openssh/Portfile
===================================================================
--- trunk/dports/net/openssh/Portfile	2013-07-20 15:56:15 UTC (rev 108348)
+++ trunk/dports/net/openssh/Portfile	2013-07-20 16:53:18 UTC (rev 108349)
@@ -47,7 +47,7 @@
 
 depends_run         port:xauth
 
-#patchfiles          launchd.patch
+patchfiles          launchd.patch
 
 # Specified -fno-builtin because GCC 3.3 has log() as a builtin
 # (from math.h) while OpenSSH has its own log() function
@@ -74,10 +74,6 @@
     depends_lib-append  port:tcp_wrappers
 }
 
-post-extract {
-    system -W ${worksrcpath} "patch -p0 <${filespath}/launchd.patch"
-}
-
 post-destroot {
     destroot.keepdirs ${destroot}${prefix}/var/run ${destroot}${prefix}/var/empty
     reinplace "s|#Port 22|Port 2222|g" ${destroot}${prefix}/etc/ssh/sshd_config
@@ -107,23 +103,20 @@
 #    }
 #}
 
-variant gss_api_trust_dns description "Enable GSSAPITrustDNS SSH configuration keyword" {
-#    patchfiles-append       GSSAPITrustDNS.patch
-    post-extract {
-        system -W ${worksrcpath} "patch -p0 <${filespath}/GSSAPITrustDNS.patch"
-    }
+variant gss_api_trust_dns description "Enable GSSAPITrustDNS SSH configuration keyword" conflicts gsskex {
+    patchfiles-append       GSSAPITrustDNS.patch
 }
 
-variant gsskex description "Add OpenSSH GSSAPI key exchange patch" {
+variant gsskex description "Add OpenSSH GSSAPI key exchange patch" conflicts gss_api_trust_dns {
     set extra_cppflags [concat \
                             "-F/System/Library/Frameworks/OpenDirectory.framework" \
                             "-F/System/Library/Frameworks/CoreFoundation.framework" \
                             "-D_UTMPX_COMPAT -D__APPLE_LAUNCHD__ -D__APPLE_MEMBERSHIP__" \
                             "-D__APPLE_XSAN__"]
     use_autoreconf          yes
-    patch.pre_args          -p1
-    patchfiles-append       openssh-5.9p1-gsskex-all-20110920.patch \
-                            apple-keychain.patch
+    patch.pre_args          -p0
+    patchfiles-append       openssh-6.2p2-gsskex-all-20110125.patch \
+                            0002-Apple-keychain-integration-other-changes.patch
     configure.args-append   --with-4in6 \
                             --with-audit=bsm \
                             --with-keychain=apple \

Added: trunk/dports/net/openssh/files/0002-Apple-keychain-integration-other-changes.patch
===================================================================
--- trunk/dports/net/openssh/files/0002-Apple-keychain-integration-other-changes.patch	                        (rev 0)
+++ trunk/dports/net/openssh/files/0002-Apple-keychain-integration-other-changes.patch	2013-07-20 16:53:18 UTC (rev 108349)
@@ -0,0 +1,2152 @@
+diff -u ../openssh-6.2p2.orig/Makefile.in ./Makefile.in
+--- ../openssh-6.2p2.orig/Makefile.in	2013-07-20 16:20:16.000000000 +0200
++++ ./Makefile.in	2013-07-20 16:23:40.000000000 +0200
+@@ -58,6 +58,7 @@
+ ENT=@ENT@
+ XAUTH_PATH=@XAUTH_PATH@
+ LDFLAGS=-L. -Lopenbsd-compat/ @LDFLAGS@
++KEYCHAIN_LDFLAGS=@KEYCHAIN_LDFLAGS@
+ EXEEXT=@EXEEXT@
+ MANFMT=@MANFMT@
+ 
+@@ -96,6 +97,8 @@
+ 	sandbox-null.o sandbox-rlimit.o sandbox-systrace.o sandbox-darwin.o \
+ 	sandbox-seccomp-filter.o
+ 
++KEYCHAINOBJS=keychain.o
++
+ MANPAGES	= moduli.5.out 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-keysign.8.out ssh-pkcs11-helper.8.out sshd_config.5.out ssh_config.5.out
+ MANPAGES_IN	= moduli.5 scp.1 ssh-add.1 ssh-agent.1 ssh-keygen.1 ssh-keyscan.1 ssh.1 sshd.8 sftp-server.8 sftp.1 ssh-keysign.8 ssh-pkcs11-helper.8 sshd_config.5 ssh_config.5
+ MANTYPE		= @MANTYPE@
+@@ -128,6 +131,7 @@
+ $(LIBSSH_OBJS): Makefile.in config.h
+ $(SSHOBJS): Makefile.in config.h
+ $(SSHDOBJS): Makefile.in config.h
++$(KEYCHAINOBJS): Makefile.in config.h
+ 
+ .c.o:
+ 	$(CC) $(CFLAGS) $(CPPFLAGS) -c $<
+@@ -141,8 +145,8 @@
+ 	$(AR) rv $@ $(LIBSSH_OBJS)
+ 	$(RANLIB) $@
+ 
+-ssh$(EXEEXT): $(LIBCOMPAT) libssh.a $(SSHOBJS)
+-	$(LD) -o $@ $(SSHOBJS) $(LDFLAGS) -lssh -lopenbsd-compat $(SSHLIBS) $(LIBS) $(GSSLIBS)
++ssh$(EXEEXT): $(LIBCOMPAT) libssh.a $(SSHOBJS) $(KEYCHAINOBJS)
++	$(LD) -o $@ $(SSHOBJS) $(KEYCHAINOBJS) $(LDFLAGS) $(KEYCHAIN_LDFLAGS) -lssh -lopenbsd-compat $(SSHLIBS) $(LIBS) $(GSSLIBS)
+ 
+ sshd$(EXEEXT): libssh.a	$(LIBCOMPAT) $(SSHDOBJS)
+ 	$(LD) -o $@ $(SSHDOBJS) $(LDFLAGS) -lssh -lopenbsd-compat $(SSHDLIBS) $(LIBS) $(GSSLIBS) $(K5LIBS)
+@@ -150,11 +154,11 @@
+ scp$(EXEEXT): $(LIBCOMPAT) libssh.a scp.o progressmeter.o
+ 	$(LD) -o $@ scp.o progressmeter.o bufaux.o $(LDFLAGS) -lssh -lopenbsd-compat $(LIBS)
+ 
+-ssh-add$(EXEEXT): $(LIBCOMPAT) libssh.a ssh-add.o
+-	$(LD) -o $@ ssh-add.o $(LDFLAGS) -lssh -lopenbsd-compat $(LIBS)
++ssh-add$(EXEEXT): $(LIBCOMPAT) libssh.a ssh-add.o $(KEYCHAINOBJS)
++	$(LD) -o $@ ssh-add.o $(KEYCHAINOBJS) $(LDFLAGS) $(KEYCHAIN_LDFLAGS) -lssh -lopenbsd-compat $(LIBS)
+ 
+-ssh-agent$(EXEEXT): $(LIBCOMPAT) libssh.a ssh-agent.o ssh-pkcs11-client.o
+-	$(LD) -o $@ ssh-agent.o ssh-pkcs11-client.o $(LDFLAGS) -lssh -lopenbsd-compat $(LIBS)
++ssh-agent$(EXEEXT): $(LIBCOMPAT) libssh.a ssh-agent.o ssh-pkcs11-client.o $(KEYCHAINOBJS)
++	$(LD) -o $@ ssh-agent.o ssh-pkcs11-client.o $(KEYCHAINOBJS) $(LDFLAGS) $(KEYCHAIN_LDFLAGS) -lssh -lopenbsd-compat $(LIBS)
+ 
+ ssh-keygen$(EXEEXT): $(LIBCOMPAT) libssh.a ssh-keygen.o
+ 	$(LD) -o $@ ssh-keygen.o $(LDFLAGS) -lssh -lopenbsd-compat $(LIBS)
+@@ -265,7 +269,7 @@
+ 	$(INSTALL) -m 0755 $(STRIP_OPT) ssh-keygen$(EXEEXT) $(DESTDIR)$(bindir)/ssh-keygen$(EXEEXT)
+ 	$(INSTALL) -m 0755 $(STRIP_OPT) ssh-keyscan$(EXEEXT) $(DESTDIR)$(bindir)/ssh-keyscan$(EXEEXT)
+ 	$(INSTALL) -m 0755 $(STRIP_OPT) sshd$(EXEEXT) $(DESTDIR)$(sbindir)/sshd$(EXEEXT)
+-	$(INSTALL) -m 4711 $(STRIP_OPT) ssh-keysign$(EXEEXT) $(DESTDIR)$(SSH_KEYSIGN)$(EXEEXT)
++	$(INSTALL) -m 0711 $(STRIP_OPT) ssh-keysign$(EXEEXT) $(DESTDIR)$(SSH_KEYSIGN)$(EXEEXT)
+ 	$(INSTALL) -m 0755 $(STRIP_OPT) ssh-pkcs11-helper$(EXEEXT) $(DESTDIR)$(SSH_PKCS11_HELPER)$(EXEEXT)
+ 	$(INSTALL) -m 0755 $(STRIP_OPT) sftp$(EXEEXT) $(DESTDIR)$(bindir)/sftp$(EXEEXT)
+ 	$(INSTALL) -m 0755 $(STRIP_OPT) sftp-server$(EXEEXT) $(DESTDIR)$(SFTP_SERVER)$(EXEEXT)
+Only in .: Makefile.in.orig
+diff -u ../openssh-6.2p2.orig/audit-bsm.c ./audit-bsm.c
+--- ../openssh-6.2p2.orig/audit-bsm.c	2012-02-24 00:40:43.000000000 +0100
++++ ./audit-bsm.c	2013-07-20 16:21:12.000000000 +0200
+@@ -263,7 +263,12 @@
+ 	pid_t		pid = getpid();
+ 	AuditInfoTermID	tid = ssh_bsm_tid;
+ 
+-	if (the_authctxt != NULL && the_authctxt->valid) {
++	if (the_authctxt == NULL) {
++		error("BSM audit: audit record internal error (NULL ctxt)");
++		abort();
++	}
++	
++	if (the_authctxt->valid) {
+ 		uid = the_authctxt->pw->pw_uid;
+ 		gid = the_authctxt->pw->pw_gid;
+ 	}
+Only in .: audit-bsm.c.orig
+diff -u ../openssh-6.2p2.orig/auth-pam.c ./auth-pam.c
+--- ../openssh-6.2p2.orig/auth-pam.c	2009-07-12 14:07:21.000000000 +0200
++++ ./auth-pam.c	2013-07-20 16:21:12.000000000 +0200
+@@ -793,10 +793,11 @@
+ 				xfree(msg);
+ 				return (0);
+ 			}
+-			error("PAM: %s for %s%.100s from %.100s", msg,
++			error("PAM: %s for %s%.100s from %.100s via %s", msg,
+ 			    sshpam_authctxt->valid ? "" : "illegal user ",
+ 			    sshpam_authctxt->user,
+-			    get_remote_name_or_ip(utmp_len, options.use_dns));
++			    get_remote_name_or_ip(utmp_len, options.use_dns),
++			    get_local_ipaddr(packet_get_connection_in()));
+ 			/* FALLTHROUGH */
+ 		default:
+ 			*num = 0;
+diff -u ../openssh-6.2p2.orig/auth.c ./auth.c
+--- ../openssh-6.2p2.orig/auth.c	2013-03-12 01:31:05.000000000 +0100
++++ ./auth.c	2013-07-20 16:21:12.000000000 +0200
+@@ -210,7 +210,7 @@
+ 	}
+ 	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
+ 		/* Get the user's group access list (primary and supplementary) */
+-		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
++		if (ga_init(pw) == 0) {
+ 			logit("User %.100s from %.100s not allowed because "
+ 			    "not in any group", pw->pw_name, hostname);
+ 			return 0;
+Only in .: auth.c.orig
+diff -u ../openssh-6.2p2.orig/authfd.c ./authfd.c
+--- ../openssh-6.2p2.orig/authfd.c	2011-08-05 22:16:00.000000000 +0200
++++ ./authfd.c	2013-07-20 16:21:12.000000000 +0200
+@@ -689,6 +689,29 @@
+ 	return decode_reply(type);
+ }
+ 
++/*
++ * Adds identities using passphrases stored in the keychain.  This call is not
++ * meant to be used by normal applications.
++ */
++
++int
++ssh_add_from_keychain(AuthenticationConnection *auth)
++{
++	Buffer msg;
++	int type;
++
++	buffer_init(&msg);
++	buffer_put_char(&msg, SSH_AGENTC_ADD_FROM_KEYCHAIN);
++
++	if (ssh_request_reply(auth, &msg, &msg) == 0) {
++		buffer_free(&msg);
++		return 0;
++	}
++	type = buffer_get_char(&msg);
++	buffer_free(&msg);
++	return decode_reply(type);
++}
++
+ int
+ decode_reply(int type)
+ {
+diff -u ../openssh-6.2p2.orig/authfd.h ./authfd.h
+--- ../openssh-6.2p2.orig/authfd.h	2009-10-06 23:47:02.000000000 +0200
++++ ./authfd.h	2013-07-20 16:21:12.000000000 +0200
+@@ -49,6 +49,9 @@
+ #define SSH2_AGENTC_ADD_ID_CONSTRAINED		25
+ #define SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED 26
+ 
++/* keychain */
++#define SSH_AGENTC_ADD_FROM_KEYCHAIN		27
++
+ #define	SSH_AGENT_CONSTRAIN_LIFETIME		1
+ #define	SSH_AGENT_CONSTRAIN_CONFIRM		2
+ 
+diff -u ../openssh-6.2p2.orig/config.h.in ./config.h.in
+--- ../openssh-6.2p2.orig/config.h.in	2013-05-16 03:35:08.000000000 +0200
++++ ./config.h.in	2013-07-20 16:21:12.000000000 +0200
+@@ -77,6 +77,18 @@
+ /* FreeBSD strnvis does not do what we need */
+ #undef BROKEN_STRNVIS
+ 
++/* platform uses an in-memory credentials cache */
++#undef USE_CCAPI
++
++/* platform has a Security Authorization Session API */
++#undef USE_SECURITY_SESSION_API
++
++/* Define to 1 if you have the `copyfile' function. */
++#undef HAVE_COPYFILE
++
++/* Define to 1 if you have the <copyfile.h> header file. */
++#undef HAVE_COPYFILE_H
++
+ /* tcgetattr with ICANON may hang */
+ #undef BROKEN_TCGETATTR_ICANON
+ 
+Only in .: config.h.in.orig
+diff -u ../openssh-6.2p2.orig/configure.ac ./configure.ac
+--- ../openssh-6.2p2.orig/configure.ac	2013-07-20 16:20:16.000000000 +0200
++++ ./configure.ac	2013-07-20 16:21:12.000000000 +0200
+@@ -4534,10 +4534,40 @@
+ #endif
+ 	])
+ 
++dnl Keychain support
++AC_ARG_WITH(keychain,
++	[  --with-keychain=apple   Use Mac OS X Keychain],
++	[
++		case "$withval" in
++		apple|no)
++			KEYCHAIN=$withval
++			;;
++		*)
++			AC_MSG_ERROR(invalid keychain type: $withval)
++			;;
++		esac
++	]
++)
++if test ! -z "$KEYCHAIN" -a "$KEYCHAIN" != "no"; then
++	case "$KEYCHAIN" in
++	apple)
++		AC_CHECK_HEADERS(Security/Security.h, [
++				CPPFLAGS="$CPPFLAGS -D__APPLE_KEYCHAIN__"
++				KEYCHAIN_LDFLAGS="-framework Security -framework CoreFoundation"
++				AC_SUBST(KEYCHAIN_LDFLAGS)
++				],
++				AC_MSG_WARN([Security framework not found. Disabling Mac OS X Keychain support.]))
++		;;
++	esac
++fi
++
+ dnl Adding -Werror to CFLAGS early prevents configure tests from running.
+ dnl Add now.
+ CFLAGS="$CFLAGS $werror_flags"
+ 
++AC_CHECK_FUNCS(copyfile)
++AC_CHECK_HEADERS(copyfile.h)
++
+ if test "x$ac_cv_func_getaddrinfo" != "xyes" ; then
+ 	TEST_SSH_IPV6=no
+ else
+Only in .: configure.ac.orig
+Common subdirectories: ../openssh-6.2p2.orig/contrib and ./contrib
+diff -u ../openssh-6.2p2.orig/groupaccess.c ./groupaccess.c
+--- ../openssh-6.2p2.orig/groupaccess.c	2008-07-04 05:51:12.000000000 +0200
++++ ./groupaccess.c	2013-07-20 16:21:12.000000000 +0200
+@@ -33,38 +33,67 @@
+ #include <stdarg.h>
+ #include <string.h>
+ 
++#ifdef __APPLE_MEMBERSHIP__
++#include <membership.h>
++#endif
++
+ #include "xmalloc.h"
+ #include "groupaccess.h"
+ #include "match.h"
+ #include "log.h"
+ 
++#ifdef __APPLE_MEMBERSHIP__
++// SPI for 5235093
++int32_t getgrouplist_2(const char *, gid_t, gid_t **);
++int32_t getgroupcount(const char *, gid_t);
++#endif
++
+ static int ngroups;
+ static char **groups_byname;
++#ifdef __APPLE_MEMBERSHIP__
++uuid_t u_uuid;
++#endif
+ 
+ /*
+  * Initialize group access list for user with primary (base) and
+  * supplementary groups.  Return the number of groups in the list.
+  */
+ int
+-ga_init(const char *user, gid_t base)
++ga_init(struct passwd *pw)
+ {
+-	gid_t *groups_bygid;
++	gid_t *groups_bygid = NULL;
+ 	int i, j;
+ 	struct group *gr;
+ 
++#ifdef __APPLE_MEMBERSHIP__
++	if (0 != mbr_uid_to_uuid(pw->pw_uid, u_uuid))
++		return 0;
++#endif
++
+ 	if (ngroups > 0)
+ 		ga_free();
+ 
++#ifndef __APPLE_MEMBERSHIP__
+ 	ngroups = NGROUPS_MAX;
+ #if defined(HAVE_SYSCONF) && defined(_SC_NGROUPS_MAX)
+ 	ngroups = MAX(NGROUPS_MAX, sysconf(_SC_NGROUPS_MAX));
+-#endif
+-
++#endif	
+ 	groups_bygid = xcalloc(ngroups, sizeof(*groups_bygid));
++#else
++	if (-1 == (ngroups = getgrouplist_2(pw->pw_name, pw->pw_gid,
++	    &groups_bygid))) {
++		logit("getgrouplist_2 failed");
++		return 0;
++	}
++#endif
+ 	groups_byname = xcalloc(ngroups, sizeof(*groups_byname));
+-
+-	if (getgrouplist(user, base, groups_bygid, &ngroups) == -1)
+-		logit("getgrouplist: groups list too small");
++#ifndef __APPLE_MEMBERSHIP__
++	if (getgrouplist(pw->pw_name, pw->pw_gid, groups_bygid, &ngroups) == -1) {
++	    logit("getgrouplist: groups list too small");
++		xfree(groups_bygid);
++		return 0;
++	}
++#endif
+ 	for (i = 0, j = 0; i < ngroups; i++)
+ 		if ((gr = getgrgid(groups_bygid[i])) != NULL)
+ 			groups_byname[j++] = xstrdup(gr->gr_name);
+@@ -75,16 +104,32 @@
+ /*
+  * Return 1 if one of user's groups is contained in groups.
+  * Return 0 otherwise.  Use match_pattern() for string comparison.
++ * Use mbr_check_membership() for membership checking on Mac OS X.
+  */
+ int
+ ga_match(char * const *groups, int n)
+ {
++#ifdef __APPLE_MEMBERSHIP__
++	int i, ismember = 0;
++	uuid_t g_uuid;
++	struct group *grp;
++
++	for (i = 0; i < n; i++) {
++		if ((grp = getgrnam(groups[i])) == NULL ||
++		   (mbr_gid_to_uuid(grp->gr_gid, g_uuid) != 0) ||
++		   (mbr_check_membership(u_uuid, g_uuid, &ismember) != 0))
++			return 0;
++		if (ismember)
++			return 1;
++	}
++#else
+ 	int i, j;
+ 
+ 	for (i = 0; i < ngroups; i++)
+ 		for (j = 0; j < n; j++)
+ 			if (match_pattern(groups_byname[i], groups[j]))
+ 				return 1;
++#endif
+ 	return 0;
+ }
+ 
+diff -u ../openssh-6.2p2.orig/groupaccess.h ./groupaccess.h
+--- ../openssh-6.2p2.orig/groupaccess.h	2008-07-04 05:51:12.000000000 +0200
++++ ./groupaccess.h	2013-07-20 16:21:12.000000000 +0200
+@@ -27,7 +27,7 @@
+ #ifndef GROUPACCESS_H
+ #define GROUPACCESS_H
+ 
+-int	 ga_init(const char *, gid_t);
++int	 ga_init(struct passwd *);
+ int	 ga_match(char * const *, int);
+ int	 ga_match_pattern_list(const char *);
+ void	 ga_free(void);
+Only in .: keychain.c
+Only in .: keychain.h
+Common subdirectories: ../openssh-6.2p2.orig/openbsd-compat and ./openbsd-compat
+diff -u ../openssh-6.2p2.orig/readconf.c ./readconf.c
+--- ../openssh-6.2p2.orig/readconf.c	2013-07-20 16:20:16.000000000 +0200
++++ ./readconf.c	2013-07-20 16:21:12.000000000 +0200
+@@ -137,6 +137,9 @@
+ 	oTunnel, oTunnelDevice, oLocalCommand, oPermitLocalCommand,
+ 	oVisualHostKey, oUseRoaming, oZeroKnowledgePasswordAuthentication,
+ 	oKexAlgorithms, oIPQoS, oRequestTTY,
++#ifdef __APPLE_KEYCHAIN__
++	oAskPassGUI,
++#endif
+ 	oDeprecated, oUnsupported
+ } OpCodes;
+ 
+@@ -257,7 +260,9 @@
+ 	{ "kexalgorithms", oKexAlgorithms },
+ 	{ "ipqos", oIPQoS },
+ 	{ "requesttty", oRequestTTY },
+-
++#ifdef __APPLE_KEYCHAIN__
++	{ "askpassgui", oAskPassGUI },
++#endif
+ 	{ NULL, oBadOption }
+ };
+ 
+@@ -1093,6 +1098,12 @@
+ 			*intptr = value;
+ 		break;
+ 
++#ifdef __APPLE_KEYCHAIN__
++	case oAskPassGUI:
++		intptr = &options->ask_pass_gui;
++		goto parse_flag;
++#endif
++
+ 	case oDeprecated:
+ 		debug("%s line %d: Deprecated option \"%s\"",
+ 		    filename, linenum, keyword);
+@@ -1258,6 +1269,9 @@
+ 	options->ip_qos_interactive = -1;
+ 	options->ip_qos_bulk = -1;
+ 	options->request_tty = -1;
++#ifdef __APPLE_KEYCHAIN__
++	options->ask_pass_gui = -1;
++#endif
+ }
+ 
+ /*
+@@ -1415,6 +1429,10 @@
+ 		options->ip_qos_bulk = IPTOS_THROUGHPUT;
+ 	if (options->request_tty == -1)
+ 		options->request_tty = REQUEST_TTY_AUTO;
++#ifdef __APPLE_KEYCHAIN__
++	if (options->ask_pass_gui == -1)
++		options->ask_pass_gui = 1;
++#endif
+ 	/* options->local_command should not be set by default */
+ 	/* options->proxy_command should not be set by default */
+ 	/* options->user will be set in the main program if appropriate */
+Only in .: readconf.c.orig
+diff -u ../openssh-6.2p2.orig/readconf.h ./readconf.h
+--- ../openssh-6.2p2.orig/readconf.h	2013-07-20 16:20:16.000000000 +0200
++++ ./readconf.h	2013-07-20 16:21:12.000000000 +0200
+@@ -141,6 +141,10 @@
+ 	int	use_roaming;
+ 
+ 	int	request_tty;
++
++#ifdef __APPLE_KEYCHAIN__
++	int ask_pass_gui;
++#endif
+ }       Options;
+ 
+ #define SSHCTL_MASTER_NO	0
+Only in .: readconf.h.orig
+Common subdirectories: ../openssh-6.2p2.orig/regress and ./regress
+Common subdirectories: ../openssh-6.2p2.orig/scard and ./scard
+diff -u ../openssh-6.2p2.orig/scp.1 ./scp.1
+--- ../openssh-6.2p2.orig/scp.1	2011-09-22 13:34:57.000000000 +0200
++++ ./scp.1	2013-07-20 16:21:12.000000000 +0200
+@@ -19,7 +19,7 @@
+ .Sh SYNOPSIS
+ .Nm scp
+ .Bk -words
+-.Op Fl 12346BCpqrv
++.Op Fl 12346BCEpqrv
+ .Op Fl c Ar cipher
+ .Op Fl F Ar ssh_config
+ .Op Fl i Ar identity_file
+@@ -97,6 +97,8 @@
+ flag to
+ .Xr ssh 1
+ to enable compression.
++.It Fl E
++Preserves extended attributes, resource forks, and ACLs.  Requires both ends to be running Mac OS X 10.4 or later.
+ .It Fl c Ar cipher
+ Selects the cipher to use for encrypting the data transfer.
+ This option is directly passed to
+diff -u ../openssh-6.2p2.orig/scp.c ./scp.c
+--- ../openssh-6.2p2.orig/scp.c	2013-03-20 02:55:15.000000000 +0100
++++ ./scp.c	2013-07-20 16:21:12.000000000 +0200
+@@ -78,6 +78,9 @@
+ #ifdef HAVE_SYS_STAT_H
+ # include <sys/stat.h>
+ #endif
++#ifdef __APPLE_XSAN__
++#include <sys/mount.h>
++#endif
+ #ifdef HAVE_POLL_H
+ #include <poll.h>
+ #else
+@@ -114,6 +117,11 @@
+ #include "misc.h"
+ #include "progressmeter.h"
+ 
++#ifdef HAVE_COPYFILE_H
++#include <libgen.h>
++#include <copyfile.h>
++#endif
++
+ extern char *__progname;
+ 
+ #define COPY_BUFLEN	16384
+@@ -150,6 +158,12 @@
+ /* This is used to store the pid of ssh_program */
+ pid_t do_cmd_pid = -1;
+ 
++#ifdef HAVE_COPYFILE
++int copy_xattr = 0;
++int md_flag = 0;
++#endif
++
++
+ static void
+ killchild(int signo)
+ {
+@@ -395,7 +409,11 @@
+ 	addargs(&args, "-oClearAllForwardings=yes");
+ 
+ 	fflag = tflag = 0;
++#if HAVE_COPYFILE
++	while ((ch = getopt(argc, argv, "dfl:prtvBCEc:i:P:q12346S:o:F:")) != -1)
++#else
+ 	while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)
++#endif
+ 		switch (ch) {
+ 		/* User-visible flags. */
+ 		case '1':
+@@ -456,6 +474,11 @@
+ 			showprogress = 0;
+ 			break;
+ 
++#ifdef HAVE_COPYFILE
++		case 'E':
++			copy_xattr = 1;
++			break;
++#endif
+ 		/* Server options. */
+ 		case 'd':
+ 			targetshouldbedirectory = 1;
+@@ -505,7 +528,12 @@
+ 	remin = remout = -1;
+ 	do_cmd_pid = -1;
+ 	/* Command to be executed on remote system using "ssh". */
++#if HAVE_COPYFILE
++	(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s%s",
++	    copy_xattr ? " -E" : "",
++#else
+ 	(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
++#endif
+ 	    verbose_mode ? " -v" : "",
+ 	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
+ 	    targetshouldbedirectory ? " -d" : "");
+@@ -733,6 +761,10 @@
+ 	int fd = -1, haderr, indx;
+ 	char *last, *name, buf[2048], encname[MAXPATHLEN];
+ 	int len;
++#if HAVE_COPYFILE
++	char md_name[MAXPATHLEN];
++	char *md_tmp;
++#endif
+ 
+ 	for (indx = 0; indx < argc; ++indx) {
+ 		name = argv[indx];
+@@ -740,12 +772,26 @@
+ 		len = strlen(name);
+ 		while (len > 1 && name[len-1] == '/')
+ 			name[--len] = '\0';
++#if HAVE_COPYFILE
++md_next:
++		statbytes = 0;
++		if (md_flag) {
++		    fd = open(md_tmp, O_RDONLY, 0);
++		    unlink(md_tmp);
++		    free(md_tmp);
++		    if (fd < 0)
++			goto syserr;
++		} else {
++#endif
+ 		if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
+ 			goto syserr;
+ 		if (strchr(name, '\n') != NULL) {
+ 			strnvis(encname, name, sizeof(encname), VIS_NL);
+ 			name = encname;
+ 		}
++#if HAVE_COPYFILE
++		}
++#endif
+ 		if (fstat(fd, &stb) < 0) {
+ syserr:			run_err("%s: %s", name, strerror(errno));
+ 			goto next;
+@@ -842,6 +888,36 @@
+ 		else
+ 			run_err("%s: %s", name, strerror(haderr));
+ 		(void) response();
++#ifdef HAVE_COPYFILE
++		if (copy_xattr && md_flag == 0)
++		{
++		    if (!copyfile(name, NULL, 0,
++			    COPYFILE_ACL | COPYFILE_XATTR | COPYFILE_CHECK))
++			continue;
++
++		    /*
++		     * this file will hold the actual metadata
++		     * to be transferred
++		     */
++		    md_tmp = strdup("/tmp/scp.md.XXXXXX");
++		    md_tmp = mktemp(md_tmp);
++
++		    if(copyfile(name, md_tmp, 0,
++				COPYFILE_ACL | COPYFILE_XATTR | COPYFILE_PACK) == 0)
++		    {
++			/*
++			 * this is the fake name to display
++			 */
++			snprintf(md_name, sizeof md_name, "%s/._%s", dirname(name), basename(name));
++			name = md_name;
++			md_flag = 1;
++			if (verbose_mode)
++			    fprintf(stderr, "copyfile(%s, %s, PACK)\n", name, md_tmp);
++			goto md_next;
++		    }
++		} else
++		    md_flag = 0;
++#endif
+ 	}
+ }
+ 
+@@ -936,6 +1012,10 @@
+ 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
+ 		targisdir = 1;
+ 	for (first = 1;; first = 0) {
++#if HAVE_COPYFILE
++		char md_src[MAXPATHLEN];
++		char md_dst[MAXPATHLEN];
++#endif
+ 		cp = buf;
+ 		if (atomicio(read, remin, cp, 1) != 1)
+ 			return;
+@@ -1069,10 +1149,51 @@
+ 		}
+ 		omode = mode;
+ 		mode |= S_IWRITE;
++
++#if HAVE_COPYFILE
++		if (copy_xattr && !strncmp(basename(curfile), "._", 2))
++		{
++			int mdfd;
++			if (targisdir)
++			{
++			    snprintf(md_src, sizeof md_src, "%s.XXXXXX", np);
++			    snprintf(md_dst, sizeof md_dst, "%s/%s",
++				    dirname(np), basename(np) + 2);
++			    if((mdfd = mkstemp(md_src)) < 0)
++				continue;
++			}
++			else
++			{
++			    snprintf(md_src, sizeof md_src, "%s/._%s.XXXXXX",
++				    dirname(np), basename(np));
++			    snprintf(md_dst, sizeof md_dst, "%s", np);
++			    if((mdfd = mkstemp(md_src)) < 0)
++				continue;
++			}
++			if (mdfd >= 0)
++				close(mdfd);
++			np = md_src;
++		}
++#endif
+ 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
+ bad:			run_err("%s: %s", np, strerror(errno));
+ 			continue;
+ 		}
++#ifdef __APPLE_XSAN__
++		{
++			/*
++			 * Pre-allocate blocks for the destination file.
++			 */
++			fstore_t fst;
++
++			fst.fst_flags = 0;
++			fst.fst_posmode = F_PEOFPOSMODE;
++			fst.fst_offset = 0;
++			fst.fst_length = size;
++				
++			(void) fcntl(ofd, F_PREALLOCATE, &fst);
++		}
++#endif /* __APPLE_XSAN__ */		
+ 		(void) atomicio(vwrite, remout, "", 1);
+ 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
+ 			(void) close(ofd);
+@@ -1157,6 +1278,29 @@
+ 			wrerrno = errno;
+ 		}
+ 		(void) response();
++#ifdef HAVE_COPYFILE
++		if (copy_xattr && strncmp(basename(np), "._", 2) == 0)
++		{
++			if (verbose_mode)
++			    fprintf(stderr, "copyfile(%s, %s, UNPACK)\n", md_src, md_dst);
++			if(!copyfile(md_src, md_dst, 0,
++			    COPYFILE_ACL | COPYFILE_XATTR | COPYFILE_UNPACK) < 0)
++			{
++			    snprintf(md_dst, sizeof md_dst, "%s/._%s",
++				    dirname(md_dst), basename(md_dst));
++			    rename(md_src, md_dst);
++			} else
++			    unlink(md_src);
++			if (setimes && wrerr == NO) {
++				setimes = 0;
++				if (utimes(md_dst, tv) < 0) {
++					run_err("%s: set times: %s",
++					np, strerror(errno));
++					wrerr = DISPLAYED;
++				}
++			}
++		} else
++#endif
+ 		if (setimes && wrerr == NO) {
+ 			setimes = 0;
+ 			if (utimes(np, tv) < 0) {
+@@ -1218,7 +1362,11 @@
+ usage(void)
+ {
+ 	(void) fprintf(stderr,
++#if HAVE_COPYFILE
++	    "usage: scp [-12346BCEpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
++#else
+ 	    "usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
++#endif
+ 	    "           [-l limit] [-o ssh_option] [-P port] [-S program]\n"
+ 	    "           [[user@]host1:]file1 ... [[user@]host2:]file2\n");
+ 	exit(1);
+Only in .: scp.c.orig
+diff -u ../openssh-6.2p2.orig/servconf.c ./servconf.c
+--- ../openssh-6.2p2.orig/servconf.c	2013-07-20 16:20:16.000000000 +0200
++++ ./servconf.c	2013-07-20 16:21:12.000000000 +0200
+@@ -156,7 +156,7 @@
+ {
+ 	/* Portable-specific options */
+ 	if (options->use_pam == -1)
+-		options->use_pam = 0;
++		options->use_pam = 1;
+ 
+ 	/* Standard Options */
+ 	if (options->protocol == SSH_PROTO_UNKNOWN)
+@@ -245,7 +245,7 @@
+ 	if (options->gss_store_rekey == -1)
+ 		options->gss_store_rekey = 0;
+ 	if (options->password_authentication == -1)
+-		options->password_authentication = 1;
++		options->password_authentication = 0;
+ 	if (options->kbd_interactive_authentication == -1)
+ 		options->kbd_interactive_authentication = 0;
+ 	if (options->challenge_response_authentication == -1)
+@@ -631,7 +631,7 @@
+ 	if ((pw = getpwnam(user)) == NULL) {
+ 		debug("Can't match group at line %d because user %.100s does "
+ 		    "not exist", line, user);
+-	} else if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
++	} else if (ga_init(pw) == 0) {
+ 		debug("Can't Match group because user %.100s not in any group "
+ 		    "at line %d", user, line);
+ 	} else if (ga_match_pattern_list(grps) != 1) {
+Only in .: servconf.c.orig
+diff -u ../openssh-6.2p2.orig/session.c ./session.c
+--- ../openssh-6.2p2.orig/session.c	2013-03-15 01:22:37.000000000 +0100
++++ ./session.c	2013-07-20 16:21:12.000000000 +0200
+@@ -2071,8 +2071,10 @@
+ 		n_bytes = packet_remaining();
+ 	tty_parse_modes(s->ttyfd, &n_bytes);
+ 
++#ifndef __APPLE_PRIVPTY__
+ 	if (!use_privsep)
+ 		pty_setowner(s->pw, s->tty);
++#endif
+ 
+ 	/* Set window size from the packet. */
+ 	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
+@@ -2312,9 +2314,11 @@
+ 	if (s->pid != 0)
+ 		record_logout(s->pid, s->tty, s->pw->pw_name);
+ 
++#ifndef __APPLE_PRIVPTY__
+ 	/* Release the pseudo-tty. */
+ 	if (getuid() == 0)
+ 		pty_release(s->tty);
++#endif
+ 
+ 	/*
+ 	 * Close the server side of the socket pairs.  We must do this after
+Only in .: session.c.orig
+diff -u ../openssh-6.2p2.orig/ssh-add.0 ./ssh-add.0
+--- ../openssh-6.2p2.orig/ssh-add.0	2013-05-16 03:35:16.000000000 +0200
++++ ./ssh-add.0	2013-07-20 16:39:57.000000000 +0200
+@@ -4,7 +4,7 @@
+      ssh-add - adds private key identities to the authentication agent
+ 
+ SYNOPSIS
+-     ssh-add [-cDdkLlXx] [-t life] [file ...]
++     ssh-add [-cDdkKLlXx] [-t life] [file ...]
+      ssh-add -s pkcs11
+      ssh-add -e pkcs11
+ 
+@@ -55,6 +55,13 @@
+      -l      Lists fingerprints of all identities currently represented by the
+              agent.
+ 
++     -m      Add identities to the agent using any passphrases stored in your
++             Mac OS X keychain.
++
++	 -M      When adding identities, each passphrase will also be stored in
++			 your Mac OS X keychain.  When removing identities with -d, each
++			 passphrase will be removed from your Mac OS X keychain.
++
+      -s pkcs11
+              Add keys provided by the PKCS#11 shared library pkcs11.
+ 
+Only in .: ssh-add.0.orig
+diff -u ../openssh-6.2p2.orig/ssh-add.1 ./ssh-add.1
+--- ../openssh-6.2p2.orig/ssh-add.1	2012-12-07 03:06:13.000000000 +0100
++++ ./ssh-add.1	2013-07-20 16:39:35.000000000 +0200
+@@ -43,7 +43,7 @@
+ .Nd adds private key identities to the authentication agent
+ .Sh SYNOPSIS
+ .Nm ssh-add
+-.Op Fl cDdkLlXx
++.Op Fl cDdkLlMmXx
+ .Op Fl t Ar life
+ .Op Ar
+ .Nm ssh-add
+@@ -118,6 +118,13 @@
+ by the agent.
+ .It Fl l
+ Lists fingerprints of all identities currently represented by the agent.
++.It Fl m
++Add identities to the agent using any passphrases stored in your Mac OS
++X keychain.
++.It Fl M
++When adding identities, each passphrase will also be stored in your Mac OS
++Xkeychain.  When removing identities with -d, each passphrase will be removed
++from your Mac OS X keychain.
+ .It Fl s Ar pkcs11
+ Add keys provided by the PKCS#11 shared library
+ .Ar pkcs11 .
+Only in .: ssh-add.1.orig
+diff -u ../openssh-6.2p2.orig/ssh-add.c ./ssh-add.c
+--- ../openssh-6.2p2.orig/ssh-add.c	2012-12-07 03:07:03.000000000 +0100
++++ ./ssh-add.c	2013-07-20 16:42:26.000000000 +0200
+@@ -62,6 +62,7 @@
+ #include "authfile.h"
+ #include "pathnames.h"
+ #include "misc.h"
++#include "keychain.h"
+ 
+ /* argv0 */
+ extern char *__progname;
+@@ -96,12 +97,24 @@
+ }
+ 
+ static int
+-delete_file(AuthenticationConnection *ac, const char *filename, int key_only)
++add_from_keychain(AuthenticationConnection *ac)
++{
++	if (ssh_add_from_keychain(ac) == 0)
++		return -1;
++
++	fprintf(stderr, "Added keychain identities.\n");
++	return 0;
++}
++
++static int
++delete_file(AuthenticationConnection *ac, int keychain, const char *filename, int key_only)
+ {
+ 	Key *public = NULL, *cert = NULL;
+ 	char *certpath = NULL, *comment = NULL;
+ 	int ret = -1;
+ 
++	if (keychain)
++		remove_from_keychain(filename);
+ 	public = key_load_public(filename, &comment);
+ 	if (public == NULL) {
+ 		printf("Bad key file %s\n", filename);
+@@ -164,7 +177,7 @@
+ }
+ 
+ static int
+-add_file(AuthenticationConnection *ac, const char *filename, int key_only)
++add_file(AuthenticationConnection *ac, int keychain, const char *filename, int key_only)
+ {
+ 	Key *private, *cert;
+ 	char *comment = NULL;
+@@ -201,11 +214,16 @@
+ 
+ 	/* At first, try empty passphrase */
+ 	private = key_parse_private(&keyblob, filename, "", &comment);
++	if (keychain && private != NULL)
++		store_in_keychain(filename, "");
+ 	if (comment == NULL)
+ 		comment = xstrdup(filename);
+ 	/* try last */
+-	if (private == NULL && pass != NULL)
++	if (private == NULL && pass != NULL) {
+ 		private = key_parse_private(&keyblob, filename, pass, NULL);
++		if (keychain && private != NULL)
++			store_in_keychain(filename, pass);
++	}
+ 	if (private == NULL) {
+ 		/* clear passphrase since it did not work */
+ 		clear_pass();
+@@ -221,8 +239,11 @@
+ 			}
+ 			private = key_parse_private(&keyblob, filename, pass,
+ 			    &comment);
+-			if (private != NULL)
++			if (private != NULL) {
++				if (keychain)
++					store_in_keychain(filename, pass);
+ 				break;
++			}
+ 			clear_pass();
+ 			snprintf(msg, sizeof msg,
+ 			    "Bad passphrase, try again for %.200s: ", comment);
+@@ -376,13 +397,13 @@
+ }
+ 
+ static int
+-do_file(AuthenticationConnection *ac, int deleting, int key_only, char *file)
++do_file(AuthenticationConnection *ac, int deleting, int keychain, int key_only, char *file)
+ {
+ 	if (deleting) {
+-		if (delete_file(ac, file, key_only) == -1)
++		if (delete_file(ac, keychain, file, key_only) == -1)
+ 			return -1;
+ 	} else {
+-		if (add_file(ac, file, key_only) == -1)
++		if (add_file(ac, keychain, file, key_only) == -1)
+ 			return -1;
+ 	}
+ 	return 0;
+@@ -404,6 +425,11 @@
+ 	fprintf(stderr, "  -X          Unlock agent.\n");
+ 	fprintf(stderr, "  -s pkcs11   Add keys from PKCS#11 provider.\n");
+ 	fprintf(stderr, "  -e pkcs11   Remove keys provided by PKCS#11 provider.\n");
++#ifdef KEYCHAIN
++	fprintf(stderr, "  -m          Add all identities stored in your Mac OS X keychain.\n");
++	fprintf(stderr, "  -M          Store passphrases in your Mac OS X keychain.\n");
++	fprintf(stderr, "              With -d, remove passphrases from your Mac OS X keychain.\n");
++#endif
+ }
+ 
+ int
+@@ -414,6 +440,7 @@
+ 	AuthenticationConnection *ac = NULL;
+ 	char *pkcs11provider = NULL;
+ 	int i, ch, deleting = 0, ret = 0, key_only = 0;
++	int keychain = 0;
+ 
+ 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
+ 	sanitise_stdfd();
+@@ -430,7 +457,7 @@
+ 		    "Could not open a connection to your authentication agent.\n");
+ 		exit(2);
+ 	}
+-	while ((ch = getopt(argc, argv, "klLcdDxXe:s:t:")) != -1) {
++	while ((ch = getopt(argc, argv, "kKlLcdDxXe:s:t:")) != -1) {
+ 		switch (ch) {
+ 		case 'k':
+ 			key_only = 1;
+@@ -469,6 +496,13 @@
+ 				goto done;
+ 			}
+ 			break;
++		case 'm':
++			if (add_from_keychain(ac) == -1)
++				ret = 1;
++			goto done;
++		case 'M':
++			keychain = 1;
++			break;
+ 		default:
+ 			usage();
+ 			ret = 1;
+@@ -500,7 +534,7 @@
+ 			    default_files[i]);
+ 			if (stat(buf, &st) < 0)
+ 				continue;
+-			if (do_file(ac, deleting, key_only, buf) == -1)
++			if (do_file(ac, deleting, keychain, key_only, buf) == -1)
+ 				ret = 1;
+ 			else
+ 				count++;
+@@ -509,7 +543,7 @@
+ 			ret = 1;
+ 	} else {
+ 		for (i = 0; i < argc; i++) {
+-			if (do_file(ac, deleting, key_only, argv[i]) == -1)
++			if (do_file(ac, deleting, keychain, key_only, argv[i]) == -1)
+ 				ret = 1;
+ 		}
+ 	}
+Only in .: ssh-add.c.orig
+diff -u ../openssh-6.2p2.orig/ssh-agent.c ./ssh-agent.c
+--- ../openssh-6.2p2.orig/ssh-agent.c	2011-06-03 06:14:16.000000000 +0200
++++ ./ssh-agent.c	2013-07-20 16:21:12.000000000 +0200
+@@ -65,6 +65,9 @@
+ #include <time.h>
+ #include <string.h>
+ #include <unistd.h>
++#ifdef __APPLE_LAUNCHD__
++#include <launch.h>
++#endif
+ 
+ #include "xmalloc.h"
+ #include "ssh.h"
+@@ -72,9 +75,11 @@
+ #include "buffer.h"
+ #include "key.h"
+ #include "authfd.h"
++#include "authfile.h"
+ #include "compat.h"
+ #include "log.h"
+ #include "misc.h"
++#include "keychain.h"
+ 
+ #ifdef ENABLE_PKCS11
+ #include "ssh-pkcs11.h"
+@@ -793,6 +798,61 @@
+ }
+ #endif /* ENABLE_PKCS11 */
+ 
++static int
++add_identity_callback(const char *filename, const char *passphrase)
++{
++	Key *k;
++	int version;
++	Idtab *tab;
++
++	if ((k = key_load_private(filename, passphrase, NULL)) == NULL)
++		return 1;
++	switch (k->type) {
++	case KEY_RSA:
++	case KEY_RSA1:
++		if (RSA_blinding_on(k->rsa, NULL) != 1) {
++			key_free(k);
++			return 1;
++		}
++		break;
++	}
++	version = k->type == KEY_RSA1 ? 1 : 2;
++	tab = idtab_lookup(version);
++	if (lookup_identity(k, version) == NULL) {
++		Identity *id = xmalloc(sizeof(Identity));
++		id->key = k;
++		id->comment = xstrdup(filename);
++		if (id->comment == NULL) {
++			key_free(k);
++			return 1;
++		}
++		id->death = 0;
++		id->confirm = 0;
++		TAILQ_INSERT_TAIL(&tab->idlist, id, next);
++		tab->nentries++;
++	} else {
++		key_free(k);
++		return 1;
++	}
++
++	return 0;
++}
++
++static void
++process_add_from_keychain(SocketEntry *e)
++{
++	int result;
++
++	result = add_identities_using_keychain(&add_identity_callback);
++
++	/* e will be NULL when ssh-agent adds keys on its own at startup */
++	if (e) {
++		buffer_put_int(&e->output, 1);
++		buffer_put_char(&e->output,
++		    result ? SSH_AGENT_FAILURE : SSH_AGENT_SUCCESS);
++	}
++}
++
+ /* dispatch incoming messages */
+ 
+ static void
+@@ -885,6 +945,9 @@
+ 		process_remove_smartcard_key(e);
+ 		break;
+ #endif /* ENABLE_PKCS11 */
++	case SSH_AGENTC_ADD_FROM_KEYCHAIN:
++		process_add_from_keychain(e);
++		break;
+ 	default:
+ 		/* Unknown message.  Respond with failure. */
+ 		error("Unknown message %d", type);
+@@ -1126,7 +1189,11 @@
+ int
+ main(int ac, char **av)
+ {
++#ifdef __APPLE_LAUNCHD__
++	int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0, l_flag = 0;
++#else
+ 	int c_flag = 0, d_flag = 0, k_flag = 0, s_flag = 0;
++#endif
+ 	int sock, fd, ch, result, saved_errno;
+ 	u_int nalloc;
+ 	char *shell, *format, *pidstr, *agentsocket = NULL;
+@@ -1160,7 +1227,11 @@
+ 	__progname = ssh_get_progname(av[0]);
+ 	seed_rng();
+ 
++#ifdef __APPLE_LAUNCHD__
++	while ((ch = getopt(ac, av, "cdklsa:t:")) != -1) {
++#else
+ 	while ((ch = getopt(ac, av, "cdksa:t:")) != -1) {
++#endif
+ 		switch (ch) {
+ 		case 'c':
+ 			if (s_flag)
+@@ -1170,6 +1241,11 @@
+ 		case 'k':
+ 			k_flag++;
+ 			break;
++#ifdef __APPLE_LAUNCHD__
++		case 'l':
++			l_flag++;
++			break;
++#endif
+ 		case 's':
+ 			if (c_flag)
+ 				usage();
+@@ -1196,7 +1272,11 @@
+ 	ac -= optind;
+ 	av += optind;
+ 
++#ifdef __APPPLE_LAUNCHD__
++	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || l_flag))
++#else
+ 	if (ac > 0 && (c_flag || k_flag || s_flag || d_flag))
++#endif
+ 		usage();
+ 
+ 	if (ac == 0 && !c_flag && !s_flag) {
+@@ -1252,6 +1332,53 @@
+ 	 * Create socket early so it will exist before command gets run from
+ 	 * the parent.
+ 	 */
++#ifdef __APPLE_LAUNCHD__
++	if (l_flag) {
++		launch_data_t resp, msg, tmp;
++		size_t listeners_i;
++
++		msg = launch_data_new_string(LAUNCH_KEY_CHECKIN);
++
++		resp = launch_msg(msg);
++
++		if (NULL == resp) {
++			perror("launch_msg");
++			exit(1);
++		}
++		launch_data_free(msg);
++		switch (launch_data_get_type(resp)) {
++		case LAUNCH_DATA_ERRNO:
++			errno = launch_data_get_errno(resp);
++			perror("launch_msg response");
++			exit(1);
++		case LAUNCH_DATA_DICTIONARY:
++			break;
++		default:
++			fprintf(stderr, "launch_msg unknown response");
++			exit(1);
++		}
++		tmp = launch_data_dict_lookup(resp, LAUNCH_JOBKEY_SOCKETS);
++
++		if (NULL == tmp) {
++			fprintf(stderr, "no sockets\n");
++			exit(1);
++		}
++
++		tmp = launch_data_dict_lookup(tmp, "Listeners");
++
++		if (NULL == tmp) {
++			fprintf(stderr, "no known listeners\n");
++			exit(1);
++		}
++
++		for (listeners_i = 0; listeners_i < launch_data_array_get_count(tmp); listeners_i++) {
++			launch_data_t obj_at_ind = launch_data_array_get_index(tmp, listeners_i);
++			new_socket(AUTH_SOCKET, launch_data_get_fd(obj_at_ind));
++		}
++
++		launch_data_free(resp);
++	} else {
++#endif
+ 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
+ 	if (sock < 0) {
+ 		perror("socket");
+@@ -1273,6 +1400,14 @@
+ 		perror("listen");
+ 		cleanup_exit(1);
+ 	}
++#ifdef __APPLE_LAUNCHD__
++	}
++#endif
++
++#ifdef __APPLE_LAUNCHD__
++	if (l_flag)
++		goto skip2;
++#endif
+ 
+ 	/*
+ 	 * Fork, and have the parent execute the command, if any, or present
+@@ -1345,6 +1480,7 @@
+ 	pkcs11_init(0);
+ #endif
+ 	new_socket(AUTH_SOCKET, sock);
++skip2:
+ 	if (ac > 0)
+ 		parent_alive_interval = 10;
+ 	idtab_init();
+@@ -1355,6 +1491,10 @@
+ 	signal(SIGTERM, cleanup_handler);
+ 	nalloc = 0;
+ 
++#ifdef KEYCHAIN
++	process_add_from_keychain(NULL);
++#endif
++
+ 	while (1) {
+ 		prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
+ 		result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
+diff -u ../openssh-6.2p2.orig/ssh-keysign.8 ./ssh-keysign.8
+--- ../openssh-6.2p2.orig/ssh-keysign.8	2010-08-31 14:41:14.000000000 +0200
++++ ./ssh-keysign.8	2013-07-20 16:21:12.000000000 +0200
+@@ -71,6 +71,9 @@
+ Since they are readable only by root,
+ .Nm
+ must be set-uid root if host-based authentication is used.
++Note that
++.Nm
++is not set-uid by default on Mac OS X.
+ .Pp
+ .It Pa /etc/ssh/ssh_host_dsa_key-cert.pub
+ .It Pa /etc/ssh/ssh_host_ecdsa_key-cert.pub
+diff -u ../openssh-6.2p2.orig/sshconnect1.c ./sshconnect1.c
+--- ../openssh-6.2p2.orig/sshconnect1.c	2006-11-07 13:14:42.000000000 +0100
++++ ./sshconnect1.c	2013-07-20 16:21:12.000000000 +0200
+@@ -47,6 +47,7 @@
+ #include "canohost.h"
+ #include "hostfile.h"
+ #include "auth.h"
++#include "keychain.h"
+ 
+ /* Session id for the current session. */
+ u_char session_id[16];
+@@ -260,6 +261,10 @@
+ 		snprintf(buf, sizeof(buf),
+ 		    "Enter passphrase for RSA key '%.100s': ", comment);
+ 		for (i = 0; i < options.number_of_password_prompts; i++) {
++#ifdef __APPLE_KEYCHAIN__
++			passphrase = keychain_read_passphrase(comment, options.ask_pass_gui);
++			if (passphrase == NULL)
++#endif
+ 			passphrase = read_passphrase(buf, 0);
+ 			if (strcmp(passphrase, "") != 0) {
+ 				private = key_load_private_type(KEY_RSA1,
+diff -u ../openssh-6.2p2.orig/sshconnect2.c ./sshconnect2.c
+--- ../openssh-6.2p2.orig/sshconnect2.c	2013-07-20 16:20:16.000000000 +0200
++++ ./sshconnect2.c	2013-07-20 16:21:12.000000000 +0200
+@@ -72,6 +72,7 @@
+ #include "hostfile.h"
+ #include "schnorr.h"
+ #include "jpake.h"
++#include "keychain.h"
+ 
+ #ifdef GSSAPI
+ #include "ssh-gss.h"
+@@ -1449,6 +1450,10 @@
+ 		snprintf(prompt, sizeof prompt,
+ 		    "Enter passphrase for key '%.100s': ", filename);
+ 		for (i = 0; i < options.number_of_password_prompts; i++) {
++#ifdef __APPLE_KEYCHAIN__
++			passphrase = keychain_read_passphrase(filename, options.ask_pass_gui);
++			if (passphrase == NULL)
++#endif
+ 			passphrase = read_passphrase(prompt, 0);
+ 			if (strcmp(passphrase, "") != 0) {
+ 				private = key_load_private_type(KEY_UNSPEC,
+Only in .: sshconnect2.c.orig
+diff -u ../openssh-6.2p2.orig/sshd.0 ./sshd.0
+--- ../openssh-6.2p2.orig/sshd.0	2013-05-16 03:35:17.000000000 +0200
++++ ./sshd.0	2013-07-20 16:21:12.000000000 +0200
+@@ -619,8 +619,8 @@
+ 
+ SEE ALSO
+      scp(1), sftp(1), ssh(1), ssh-add(1), ssh-agent(1), ssh-keygen(1),
+-     ssh-keyscan(1), chroot(2), hosts_access(5), login.conf(5), moduli(5),
+-     sshd_config(5), inetd(8), sftp-server(8)
++     ssh-keyscan(1), chroot(2), hosts_access(5), sshd_config(5)
++     sftp-server(8)
+ 
+ AUTHORS
+      OpenSSH is a derivative of the original and free ssh 1.2.12 release by
+Only in .: sshd.0.orig
+diff -u ../openssh-6.2p2.orig/sshd.8 ./sshd.8
+--- ../openssh-6.2p2.orig/sshd.8	2012-10-05 03:02:40.000000000 +0200
++++ ./sshd.8	2013-07-20 16:21:12.000000000 +0200
+@@ -955,10 +955,7 @@
+ .Xr ssh-keyscan 1 ,
+ .Xr chroot 2 ,
+ .Xr hosts_access 5 ,
+-.Xr login.conf 5 ,
+-.Xr moduli 5 ,
+ .Xr sshd_config 5 ,
+-.Xr inetd 8 ,
+ .Xr sftp-server 8
+ .Sh AUTHORS
+ OpenSSH is a derivative of the original and free
+Only in .: sshd.8.orig
+diff -u ../openssh-6.2p2.orig/sshd.c ./sshd.c
+--- ../openssh-6.2p2.orig/sshd.c	2013-07-20 16:20:16.000000000 +0200
++++ ./sshd.c	2013-07-20 16:21:12.000000000 +0200
+@@ -2108,6 +2108,12 @@
+ 	audit_event(SSH_AUTH_SUCCESS);
+ #endif
+ 
++#ifdef USE_PAM
++	if (options.use_pam) {
++		do_pam_setcred(1);
++		do_pam_session();
++	}
++#endif
+ #ifdef GSSAPI
+ 	if (options.gss_authentication) {
+ 		temporarily_use_uid(authctxt->pw);
+@@ -2115,12 +2121,6 @@
+ 		restore_uid();
+ 	}
+ #endif
+-#ifdef USE_PAM
+-	if (options.use_pam) {
+-		do_pam_setcred(1);
+-		do_pam_session();
+-	}
+-#endif
+ 
+ 	/*
+ 	 * In privilege separation, we fork another child and prepare
+Only in .: sshd.c.orig
+diff -u ../openssh-6.2p2.orig/sshd_config ./sshd_config
+--- ../openssh-6.2p2.orig/sshd_config	2013-07-20 16:20:16.000000000 +0200
++++ ./sshd_config	2013-07-20 16:21:12.000000000 +0200
+@@ -31,7 +31,7 @@
+ 
+ # Logging
+ # obsoletes QuietMode and FascistLogging
+-#SyslogFacility AUTH
++SyslogFacility AUTHPRIV
+ #LogLevel INFO
+ 
+ # Authentication:
+@@ -64,8 +64,9 @@
+ # Don't read the user's ~/.rhosts and ~/.shosts files
+ #IgnoreRhosts yes
+ 
+-# To disable tunneled clear text passwords, change to no here!
+-#PasswordAuthentication yes
++# To disable tunneled clear text passwords, change to no here! Also,
++# remember to set the UsePAM setting to 'no'.
++#PasswordAuthentication no
+ #PermitEmptyPasswords no
+ 
+ # Change to no to disable s/key passwords
+@@ -92,7 +93,10 @@
+ # If you just want the PAM account and session checks to run without
+ # PAM authentication, then enable this but set PasswordAuthentication
+ # and ChallengeResponseAuthentication to 'no'.
+-#UsePAM no
++# Also, PAM will deny null passwords by default.  If you need to allow
++# null passwords, add the "	nullok" option to the end of the
++# securityserver.so line in /etc/pam.d/sshd.
++#UsePAM yes
+ 
+ #AllowAgentForwarding yes
+ #AllowTcpForwarding yes
+diff -u ../openssh-6.2p2.orig/sshd_config.0 ./sshd_config.0
+--- ../openssh-6.2p2.orig/sshd_config.0	2013-05-16 03:35:17.000000000 +0200
++++ ./sshd_config.0	2013-07-20 16:21:12.000000000 +0200
+@@ -489,7 +489,7 @@
+ 
+      PasswordAuthentication
+              Specifies whether password authentication is allowed.  The
+-             default is ``yes''.
++             default is ``no''.
+ 
+      PermitEmptyPasswords
+              When password authentication is allowed, it specifies whether the
+@@ -676,7 +676,7 @@
+              either PasswordAuthentication or ChallengeResponseAuthentication.
+ 
+              If UsePAM is enabled, you will not be able to run sshd(8) as a
+-             non-root user.  The default is ``no''.
++             non-root user.  The default is ``yes''.
+ 
+      UsePrivilegeSeparation
+              Specifies whether sshd(8) separates privileges by creating an
+Only in .: sshd_config.0.orig
+diff -u ../openssh-6.2p2.orig/sshd_config.5 ./sshd_config.5
+--- ../openssh-6.2p2.orig/sshd_config.5	2013-07-20 16:20:16.000000000 +0200
++++ ./sshd_config.5	2013-07-20 16:21:12.000000000 +0200
+@@ -869,7 +869,7 @@
+ .It Cm PasswordAuthentication
+ Specifies whether password authentication is allowed.
+ The default is
+-.Dq yes .
++.Dq no .
+ .It Cm PermitEmptyPasswords
+ When password authentication is allowed, it specifies whether the
+ server allows login to accounts with empty password strings.
+@@ -1174,7 +1174,7 @@
+ .Xr sshd 8
+ as a non-root user.
+ The default is
+-.Dq no .
++.Dq yes .
+ .It Cm UsePrivilegeSeparation
+ Specifies whether
+ .Xr sshd 8
+Only in .: sshd_config.5.orig
+Only in .: sshd_config.orig
+--- /dev/null	2013-07-20 16:48:17.000000000 +0200
++++ ./keychain.c	2013-07-20 16:21:12.000000000 +0200
+@@ -0,0 +1,694 @@
++/*
++ * Copyright (c) 2007 Apple Inc. All rights reserved.
++ *
++ * @APPLE_BSD_LICENSE_HEADER_START@
++ * 
++ * Redistribution and use in source and binary forms, with or without
++ * modification, are permitted provided that the following conditions
++ * are met:
++ * 
++ * 1.  Redistributions of source code must retain the above copyright
++ *     notice, this list of conditions and the following disclaimer. 
++ * 2.  Redistributions in binary form must reproduce the above copyright
++ *     notice, this list of conditions and the following disclaimer in the
++ *     documentation and/or other materials provided with the distribution. 
++ * 3.  Neither the name of Apple Inc. ("Apple") nor the names of its
++ *     contributors may be used to endorse or promote products derived from
++ *     this software without specific prior written permission. 
++ * 
++ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS 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.
++ * 
++ * @APPLE_BSD_LICENSE_HEADER_END@
++ */
++
++#include "includes.h"
++
++#include <stdio.h>
++#include <string.h>
++
++#include "xmalloc.h"
++#include "key.h"
++#include "authfd.h"
++#include "authfile.h"
++
++#if defined(__APPLE_KEYCHAIN__)
++
++#include <CoreFoundation/CoreFoundation.h>
++#include <Security/Security.h>
++
++/* Our Security/SecPassword.h is not yet API, so I will define the constants that I am using here. */
++int kSecPasswordGet     = 1<<0;  // Get password from keychain or user
++int kSecPasswordSet     = 1<<1;  // Set password (passed in if kSecPasswordGet not set, otherwise from user)
++int kSecPasswordFail    = 1<<2;  // Wrong password (ignore item in keychain and flag error)
++OSStatus SecGenericPasswordCreate(SecKeychainAttributeList *searchAttrList, SecKeychainAttributeList *itemAttrList, SecPasswordRef *itemRef);
++OSStatus SecPasswordAction(SecPasswordRef itemRef, CFTypeRef message, UInt32 flags, UInt32 *length, const void **data);
++OSStatus SecPasswordSetInitialAccess(SecPasswordRef itemRef, SecAccessRef accessRef);
++
++#endif
++
++/*
++ * Platform-specific helper functions.
++ */
++
++#if defined(__APPLE_KEYCHAIN__)
++
++static int get_boolean_preference(const char *key, int default_value,
++    int foreground)
++{
++	int value = default_value;
++	CFStringRef keyRef = NULL;
++	CFPropertyListRef valueRef = NULL;
++
++	keyRef = CFStringCreateWithCString(NULL, key, kCFStringEncodingUTF8);
++	if (keyRef != NULL)
++		valueRef = CFPreferencesCopyAppValue(keyRef,
++		    CFSTR("org.openbsd.openssh"));
++	if (valueRef != NULL)
++		if (CFGetTypeID(valueRef) == CFBooleanGetTypeID())
++			value = CFBooleanGetValue(valueRef);
++		else if (foreground)
++			fprintf(stderr, "Ignoring nonboolean %s preference.\n", key);
++
++	if (keyRef)
++		CFRelease(keyRef);
++	if (valueRef)
++		CFRelease(valueRef);
++
++	return value;
++}
++
++#endif
++
++/*
++ * Store the passphrase for a given identity in the keychain.
++ */
++void
++store_in_keychain(const char *filename, const char *passphrase)
++{
++
++#if defined(__APPLE_KEYCHAIN__)
++
++	/*
++	 * store_in_keychain
++	 * Mac OS X implementation
++	 */
++
++	CFStringRef cfstr_relative_filename = NULL;
++	CFURLRef cfurl_relative_filename = NULL, cfurl_filename = NULL;
++	CFStringRef cfstr_filename = NULL;
++	CFDataRef cfdata_filename = NULL;
++	CFIndex filename_len;
++	UInt8 *label = NULL;
++	UInt8 *utf8_filename;
++	OSStatus rv;
++	SecKeychainItemRef itemRef = NULL;
++	SecTrustedApplicationRef apps[] = {NULL, NULL, NULL};
++	CFArrayRef trustedlist = NULL;
++	SecAccessRef initialAccess = NULL;
++
++	/* Bail out if KeychainIntegration preference is -bool NO */
++	if (get_boolean_preference("KeychainIntegration", 1, 1) == 0) {
++		fprintf(stderr, "Keychain integration is disabled.\n");
++		goto err;
++	}
++
++	/* Interpret filename with the correct encoding. */
++	if ((cfstr_relative_filename =
++	    CFStringCreateWithFileSystemRepresentation(NULL, filename)) == NULL)
++	    {
++		fprintf(stderr, "CFStringCreateWithFileSystemRepresentation failed\n");
++		goto err;
++	}
++	if ((cfurl_relative_filename = CFURLCreateWithFileSystemPath(NULL,
++	    cfstr_relative_filename, kCFURLPOSIXPathStyle, false)) == NULL) {
++		fprintf(stderr, "CFURLCreateWithFileSystemPath failed\n");
++		goto err;
++	}
++	if ((cfurl_filename = CFURLCopyAbsoluteURL(cfurl_relative_filename)) ==
++	    NULL) {
++		fprintf(stderr, "CFURLCopyAbsoluteURL failed\n");
++		goto err;
++	}
++	if ((cfstr_filename = CFURLCopyFileSystemPath(cfurl_filename,
++	    kCFURLPOSIXPathStyle)) == NULL) {
++		fprintf(stderr, "CFURLCopyFileSystemPath failed\n");
++		goto err;
++	}
++	if ((cfdata_filename = CFStringCreateExternalRepresentation(NULL,
++	    cfstr_filename, kCFStringEncodingUTF8, 0)) == NULL) {
++		fprintf(stderr, "CFStringCreateExternalRepresentation failed\n");
++		goto err;
++	}
++	filename_len = CFDataGetLength(cfdata_filename);
++	if ((label = xmalloc(filename_len + 5)) == NULL) {
++		fprintf(stderr, "xmalloc failed\n");
++		goto err;
++	}
++	memcpy(label, "SSH: ", 5);
++	utf8_filename = label + 5;
++	CFDataGetBytes(cfdata_filename, CFRangeMake(0, filename_len),
++	    utf8_filename);
++
++	/* Check if we already have this passphrase. */
++	rv = SecKeychainFindGenericPassword(NULL, 3, "SSH", filename_len,
++	    (char *)utf8_filename, NULL, NULL, &itemRef);
++	if (rv == errSecItemNotFound) {
++		/* Add a new keychain item. */
++		SecKeychainAttribute attrs[] = {
++			{kSecLabelItemAttr, filename_len + 5, label},
++			{kSecServiceItemAttr, 3, "SSH"},
++			{kSecAccountItemAttr, filename_len, utf8_filename}
++		};
++		SecKeychainAttributeList attrList =
++		    {sizeof(attrs) / sizeof(attrs[0]), attrs};
++		if (SecTrustedApplicationCreateFromPath("/usr/bin/ssh-agent",
++		    &apps[0]) != noErr ||
++		    SecTrustedApplicationCreateFromPath("/usr/bin/ssh-add",
++		    &apps[1]) != noErr ||
++		    SecTrustedApplicationCreateFromPath("/usr/bin/ssh",
++		    &apps[2]) != noErr) {
++			fprintf(stderr, "SecTrustedApplicationCreateFromPath failed\n");
++			goto err;
++		}
++		if ((trustedlist = CFArrayCreate(NULL, (const void **)apps,
++		    sizeof(apps) / sizeof(apps[0]), &kCFTypeArrayCallBacks)) ==
++		    NULL) {
++			fprintf(stderr, "CFArrayCreate failed\n");
++			goto err;
++		}
++		if (SecAccessCreate(cfstr_filename, trustedlist,
++		    &initialAccess) != noErr) {
++			fprintf(stderr, "SecAccessCreate failed\n");
++			goto err;
++		}
++		if (SecKeychainItemCreateFromContent(
++		    kSecGenericPasswordItemClass, &attrList, strlen(passphrase),
++		    passphrase, NULL, initialAccess, NULL) == noErr)
++			fprintf(stderr, "Passphrase stored in keychain: %s\n", filename);
++		else
++			fprintf(stderr, "Could not create keychain item\n");
++	} else if (rv == noErr) {
++		/* Update an existing keychain item. */
++		if (SecKeychainItemModifyAttributesAndData(itemRef, NULL,
++		    strlen(passphrase), passphrase) == noErr)
++			fprintf(stderr, "Passphrase updated in keychain: %s\n", filename);
++		else
++			fprintf(stderr, "Could not modify keychain item\n");
++	} else
++		fprintf(stderr, "Could not access keychain\n");
++
++err:	/* Clean up. */
++	if (cfstr_relative_filename)
++		CFRelease(cfstr_relative_filename);
++	if (cfurl_relative_filename)
++		CFRelease(cfurl_relative_filename);
++	if (cfurl_filename)
++		CFRelease(cfurl_filename);
++	if (cfstr_filename)
++		CFRelease(cfstr_filename);
++	if (cfdata_filename)
++		CFRelease(cfdata_filename);
++	if (label)
++		xfree(label);
++	if (itemRef)
++		CFRelease(itemRef);
++	if (apps[0])
++		CFRelease(apps[0]);
++	if (apps[1])
++		CFRelease(apps[1]);
++	if (apps[2])
++		CFRelease(apps[2]);
++	if (trustedlist)
++		CFRelease(trustedlist);
++	if (initialAccess)
++		CFRelease(initialAccess);
++
++#else
++
++	/*
++	 * store_in_keychain
++	 * no keychain implementation
++	 */
++
++	fprintf(stderr, "Keychain is not available on this system\n");
++
++#endif
++
++}
++
++/*
++ * Remove the passphrase for a given identity from the keychain.
++ */
++void
++remove_from_keychain(const char *filename)
++{
++
++#if defined(__APPLE_KEYCHAIN__)
++
++	/*
++	 * remove_from_keychain
++	 * Mac OS X implementation
++	 */
++
++	CFStringRef cfstr_relative_filename = NULL;
++	CFURLRef cfurl_relative_filename = NULL, cfurl_filename = NULL;
++	CFStringRef cfstr_filename = NULL;
++	CFDataRef cfdata_filename = NULL;
++	CFIndex filename_len;
++	const UInt8 *utf8_filename;
++	OSStatus rv;
++	SecKeychainItemRef itemRef = NULL;
++
++	/* Bail out if KeychainIntegration preference is -bool NO */
++	if (get_boolean_preference("KeychainIntegration", 1, 1) == 0) {
++		fprintf(stderr, "Keychain integration is disabled.\n");
++		goto err;
++	}
++
++	/* Interpret filename with the correct encoding. */
++	if ((cfstr_relative_filename =
++	    CFStringCreateWithFileSystemRepresentation(NULL, filename)) == NULL)
++	    {
++		fprintf(stderr, "CFStringCreateWithFileSystemRepresentation failed\n");
++		goto err;
++	}
++	if ((cfurl_relative_filename = CFURLCreateWithFileSystemPath(NULL,
++	    cfstr_relative_filename, kCFURLPOSIXPathStyle, false)) == NULL) {
++		fprintf(stderr, "CFURLCreateWithFileSystemPath failed\n");
++		goto err;
++	}
++	if ((cfurl_filename = CFURLCopyAbsoluteURL(cfurl_relative_filename)) ==
++	    NULL) {
++		fprintf(stderr, "CFURLCopyAbsoluteURL failed\n");
++		goto err;
++	}
++	if ((cfstr_filename = CFURLCopyFileSystemPath(cfurl_filename,
++	    kCFURLPOSIXPathStyle)) == NULL) {
++		fprintf(stderr, "CFURLCopyFileSystemPath failed\n");
++		goto err;
++	}
++	if ((cfdata_filename = CFStringCreateExternalRepresentation(NULL,
++	    cfstr_filename, kCFStringEncodingUTF8, 0)) == NULL) {
++		fprintf(stderr, "CFStringCreateExternalRepresentation failed\n");
++		goto err;
++	}
++	filename_len = CFDataGetLength(cfdata_filename);
++	utf8_filename = CFDataGetBytePtr(cfdata_filename);
++
++	/* Check if we already have this passphrase. */
++	rv = SecKeychainFindGenericPassword(NULL, 3, "SSH", filename_len,
++	    (const char *)utf8_filename, NULL, NULL, &itemRef);
++	if (rv == noErr) {
++		/* Remove the passphrase from the keychain. */
++		if (SecKeychainItemDelete(itemRef) == noErr)
++			fprintf(stderr, "Passphrase removed from keychain: %s\n", filename);
++		else
++			fprintf(stderr, "Could not remove keychain item\n");
++	} else if (rv != errSecItemNotFound)
++		fprintf(stderr, "Could not access keychain\n");
++
++err:	/* Clean up. */
++	if (cfstr_relative_filename)
++		CFRelease(cfstr_relative_filename);
++	if (cfurl_relative_filename)
++		CFRelease(cfurl_relative_filename);
++	if (cfurl_filename)
++		CFRelease(cfurl_filename);
++	if (cfstr_filename)
++		CFRelease(cfstr_filename);
++	if (cfdata_filename)
++		CFRelease(cfdata_filename);
++	if (itemRef)
++		CFRelease(itemRef);
++
++#else
++
++	/*
++	 * remove_from_keychain
++	 * no keychain implementation
++	 */
++
++	fprintf(stderr, "Keychain is not available on this system\n");
++
++#endif
++
++}
++
++/*
++ * Add identities to ssh-agent using passphrases stored in the keychain.
++ * Returns zero on success and nonzero on failure.
++ * add_identity is a callback into ssh-agent.  It takes a filename and a
++ * passphrase, and attempts to add the identity to the agent.  It returns
++ * zero on success and nonzero on failure.
++ */
++int
++add_identities_using_keychain(int (*add_identity)(const char *, const char *))
++{
++
++#if defined(__APPLE_KEYCHAIN__)
++
++	/*
++	 * add_identities_using_keychain
++	 * Mac OS X implementation
++	 */
++
++	OSStatus rv;
++	SecKeychainSearchRef searchRef;
++	SecKeychainItemRef itemRef;
++	UInt32 length;
++	void *data;
++	CFIndex maxsize;
++
++	/* Bail out if KeychainIntegration preference is -bool NO */
++	if (get_boolean_preference("KeychainIntegration", 1, 0) == 0)
++		return 0;
++
++	/* Search for SSH passphrases in the keychain */
++	SecKeychainAttribute attrs[] = {
++		{kSecServiceItemAttr, 3, "SSH"}
++	};
++	SecKeychainAttributeList attrList =
++	    {sizeof(attrs) / sizeof(attrs[0]), attrs};
++	if ((rv = SecKeychainSearchCreateFromAttributes(NULL,
++	    kSecGenericPasswordItemClass, &attrList, &searchRef)) != noErr)
++		return 0;
++
++	/* Iterate through the search results. */
++	while ((rv = SecKeychainSearchCopyNext(searchRef, &itemRef)) == noErr) {
++		UInt32 tag = kSecAccountItemAttr;
++		UInt32 format = kSecFormatUnknown;
++		SecKeychainAttributeInfo info = {1, &tag, &format};
++		SecKeychainAttributeList *itemAttrList = NULL;
++		CFStringRef cfstr_filename = NULL;
++		char *filename = NULL;
++		char *passphrase = NULL;
++
++		/* Retrieve filename and passphrase. */
++		if ((rv = SecKeychainItemCopyAttributesAndData(itemRef, &info,
++		    NULL, &itemAttrList, &length, &data)) != noErr)
++			goto err;
++		if (itemAttrList->count != 1)
++			goto err;
++		cfstr_filename = CFStringCreateWithBytes(NULL,
++		    itemAttrList->attr->data, itemAttrList->attr->length,
++		    kCFStringEncodingUTF8, true);
++		maxsize = CFStringGetMaximumSizeOfFileSystemRepresentation(
++		    cfstr_filename);
++		if ((filename = xmalloc(maxsize)) == NULL)
++			goto err;
++		if (CFStringGetFileSystemRepresentation(cfstr_filename,
++		    filename, maxsize) == false)
++			goto err;
++		if ((passphrase = xmalloc(length + 1)) == NULL)
++			goto err;
++		memcpy(passphrase, data, length);
++		passphrase[length] = '\0';
++
++		/* Add the identity. */
++		add_identity(filename, passphrase);
++
++err:		/* Clean up. */
++		if (itemRef)
++			CFRelease(itemRef);
++		if (cfstr_filename)
++			CFRelease(cfstr_filename);
++		if (filename)
++			xfree(filename);
++		if (passphrase)
++			xfree(passphrase);
++		if (itemAttrList)
++			SecKeychainItemFreeAttributesAndData(itemAttrList,
++			    data);
++	}
++
++	CFRelease(searchRef);
++
++	return 0;
++
++#else
++
++	/*
++	 * add_identities_using_keychain
++	 * no implementation
++	 */
++
++	return 1;
++
++#endif
++
++}
++
++/*
++ * Prompt the user for a key's passphrase.  The user will be offered the option
++ * of storing the passphrase in their keychain.  Returns the passphrase
++ * (which the caller is responsible for xfreeing), or NULL if this function
++ * fails or is not implemented.  If this function is not implemented, ssh will
++ * fall back on the standard read_passphrase function, and the user will need
++ * to use ssh-add -K to add their keys to the keychain.
++ */
++char *
++keychain_read_passphrase(const char *filename, int oAskPassGUI)
++{
++
++#if defined(__APPLE_KEYCHAIN__)
++
++	/*
++	 * keychain_read_passphrase
++	 * Mac OS X implementation
++	 */
++
++	CFStringRef cfstr_relative_filename = NULL;
++	CFURLRef cfurl_relative_filename = NULL, cfurl_filename = NULL;
++	CFStringRef cfstr_filename = NULL;
++	CFDataRef cfdata_filename = NULL;
++	CFIndex filename_len;
++	UInt8 *label = NULL;
++	UInt8 *utf8_filename;
++	SecPasswordRef passRef = NULL;
++	SecTrustedApplicationRef apps[] = {NULL, NULL, NULL};
++	CFArrayRef trustedlist = NULL;
++	SecAccessRef initialAccess = NULL;
++	CFURLRef path = NULL;
++	CFStringRef pathFinal = NULL;
++	CFURLRef bundle_url = NULL;
++	CFBundleRef bundle = NULL;
++	CFStringRef promptTemplate = NULL, prompt = NULL;
++	UInt32 length;
++	const void *data;
++	AuthenticationConnection *ac = NULL;
++	char *result = NULL;
++
++	/* Bail out if KeychainIntegration preference is -bool NO */
++	if (get_boolean_preference("KeychainIntegration", 1, 1) == 0)
++		goto err;
++
++	/* Bail out if the user set AskPassGUI preference to -bool NO */
++	if (get_boolean_preference("AskPassGUI", 1, 1) == 0 || oAskPassGUI == 0)
++		goto err;
++
++	/* Bail out if we can't communicate with ssh-agent */
++	if ((ac = ssh_get_authentication_connection()) == NULL)
++		goto err;
++
++	/* Interpret filename with the correct encoding. */
++	if ((cfstr_relative_filename =
++	    CFStringCreateWithFileSystemRepresentation(NULL, filename)) == NULL)
++	    {
++		fprintf(stderr, "CFStringCreateWithFileSystemRepresentation failed\n");
++		goto err;
++	}
++	if ((cfurl_relative_filename = CFURLCreateWithFileSystemPath(NULL,
++	    cfstr_relative_filename, kCFURLPOSIXPathStyle, false)) == NULL) {
++		fprintf(stderr, "CFURLCreateWithFileSystemPath failed\n");
++		goto err;
++	}
++	if ((cfurl_filename = CFURLCopyAbsoluteURL(cfurl_relative_filename)) ==
++	    NULL) {
++		fprintf(stderr, "CFURLCopyAbsoluteURL failed\n");
++		goto err;
++	}
++	if ((cfstr_filename = CFURLCopyFileSystemPath(cfurl_filename,
++	    kCFURLPOSIXPathStyle)) == NULL) {
++		fprintf(stderr, "CFURLCopyFileSystemPath failed\n");
++		goto err;
++	}
++	if ((cfdata_filename = CFStringCreateExternalRepresentation(NULL,
++	    cfstr_filename, kCFStringEncodingUTF8, 0)) == NULL) {
++		fprintf(stderr, "CFStringCreateExternalRepresentation failed\n");
++		goto err;
++	}
++	filename_len = CFDataGetLength(cfdata_filename);
++	if ((label = xmalloc(filename_len + 5)) == NULL) {
++		fprintf(stderr, "xmalloc failed\n");
++		goto err;
++	}
++	memcpy(label, "SSH: ", 5);
++	utf8_filename = label + 5;
++	CFDataGetBytes(cfdata_filename, CFRangeMake(0, filename_len),
++	    utf8_filename);
++
++	/* Build a SecPasswordRef. */
++	SecKeychainAttribute searchAttrs[] = {
++		{kSecServiceItemAttr, 3, "SSH"},
++		{kSecAccountItemAttr, filename_len, utf8_filename}
++	};
++	SecKeychainAttributeList searchAttrList =
++	    {sizeof(searchAttrs) / sizeof(searchAttrs[0]), searchAttrs};
++	SecKeychainAttribute attrs[] = {
++		{kSecLabelItemAttr, filename_len + 5, label},
++		{kSecServiceItemAttr, 3, "SSH"},
++		{kSecAccountItemAttr, filename_len, utf8_filename}
++	};
++	SecKeychainAttributeList attrList =
++	    {sizeof(attrs) / sizeof(attrs[0]), attrs};
++	if (SecGenericPasswordCreate(&searchAttrList, &attrList, &passRef) !=
++	    noErr) {
++		fprintf(stderr, "SecGenericPasswordCreate failed\n");
++		goto err;
++	}
++	if (SecTrustedApplicationCreateFromPath("/usr/bin/ssh-agent", &apps[0])
++	    != noErr ||
++	    SecTrustedApplicationCreateFromPath("/usr/bin/ssh-add", &apps[1])
++	    != noErr ||
++	    SecTrustedApplicationCreateFromPath("/usr/bin/ssh", &apps[2])
++	    != noErr) {
++		fprintf(stderr, "SecTrustedApplicationCreateFromPath failed\n");
++		goto err;
++	}
++	if ((trustedlist = CFArrayCreate(NULL, (const void **)apps,
++	    sizeof(apps) / sizeof(apps[0]), &kCFTypeArrayCallBacks)) == NULL) {
++		fprintf(stderr, "CFArrayCreate failed\n");
++		goto err;
++	}
++	if (SecAccessCreate(cfstr_filename, trustedlist, &initialAccess)
++	    != noErr) {
++		fprintf(stderr, "SecAccessCreate failed\n");
++		goto err;
++	}
++	if (SecPasswordSetInitialAccess(passRef, initialAccess) != noErr) {
++		fprintf(stderr, "SecPasswordSetInitialAccess failed\n");
++		goto err;
++	}
++
++	/* Request the passphrase from the user. */
++	if ((path = CFURLCreateFromFileSystemRepresentation(NULL,
++	    (UInt8 *)filename, strlen(filename), false)) == NULL) {
++		fprintf(stderr, "CFURLCreateFromFileSystemRepresentation failed\n");
++		goto err;
++	}
++	if ((pathFinal = CFURLCopyLastPathComponent(path)) == NULL) {
++		fprintf(stderr, "CFURLCopyLastPathComponent failed\n");
++		goto err;
++	}
++	if (!((bundle_url = CFURLCreateWithFileSystemPath(NULL,
++	    CFSTR("/System/Library/CoreServices/"), kCFURLPOSIXPathStyle, true))
++	    != NULL && (bundle = CFBundleCreate(NULL, bundle_url)) != NULL &&
++	    (promptTemplate = CFCopyLocalizedStringFromTableInBundle(
++	    CFSTR("Enter your password for the SSH key \"%@\"."),
++	    CFSTR("OpenSSH"), bundle, "Text of the dialog asking the user for"
++	    "their passphrase.  The %@ will be replaced with the filename of a"
++	    "specific key.")) != NULL) &&
++	    (promptTemplate = CFStringCreateCopy(NULL,
++	    CFSTR("Enter your password for the SSH key \"%@\"."))) == NULL) {
++		fprintf(stderr, "CFStringCreateCopy failed\n");
++		goto err;
++	}
++	if ((prompt = CFStringCreateWithFormat(NULL, NULL, promptTemplate,
++	    pathFinal)) == NULL) {
++		fprintf(stderr, "CFStringCreateWithFormat failed\n");
++		goto err;
++	}
++	switch (SecPasswordAction(passRef, prompt,
++	    kSecPasswordGet|kSecPasswordFail, &length, &data)) {
++	case noErr:
++		result = xmalloc(length + 1);
++		memcpy(result, data, length);
++		result[length] = '\0';
++
++		/* Save password in keychain if requested. */
++		if (noErr != SecPasswordAction(passRef, CFSTR(""), kSecPasswordSet, &length, &data))
++			fprintf(stderr, "Saving password to keychain failed\n");
++
++		/* Add password to agent. */
++		char *comment = NULL;
++		Key *private = key_load_private(filename, result, &comment);
++		if (NULL == private)
++			break;
++		if (ssh_add_identity_constrained(ac, private, comment, 0, 0))
++			fprintf(stderr, "Identity added: %s (%s)\n", filename, comment);
++		else
++			fprintf(stderr, "Could not add identity: %s\n", filename);
++		xfree(comment);
++		key_free(private);
++		break;
++	case errAuthorizationCanceled:
++		result = xmalloc(1);
++		*result = '\0';
++		break;
++	default:
++		goto err;
++	}
++
++err:	/* Clean up. */
++	if (cfstr_relative_filename)
++		CFRelease(cfstr_relative_filename);
++	if (cfurl_relative_filename)
++		CFRelease(cfurl_relative_filename);
++	if (cfurl_filename)
++		CFRelease(cfurl_filename);
++	if (cfstr_filename)
++		CFRelease(cfstr_filename);
++	if (cfdata_filename)
++		CFRelease(cfdata_filename);
++	if (label)
++		xfree(label);
++	if (passRef)
++		CFRelease(passRef);
++	if (apps[0])
++		CFRelease(apps[0]);
++	if (apps[1])
++		CFRelease(apps[1]);
++	if (apps[2])
++		CFRelease(apps[2]);
++	if (trustedlist)
++		CFRelease(trustedlist);
++	if (initialAccess)
++		CFRelease(initialAccess);
++	if (path)
++		CFRelease(path);
++	if (pathFinal)
++		CFRelease(pathFinal);
++	if (bundle_url)
++		CFRelease(bundle_url);
++	if (bundle)
++		CFRelease(bundle);
++	if (promptTemplate)
++		CFRelease(promptTemplate);
++	if (prompt)
++		CFRelease(prompt);
++	if (ac)
++		ssh_close_authentication_connection(ac);
++
++	return result;
++
++#else
++
++	/*
++	 * keychain_read_passphrase
++	 * no implementation
++	 */
++
++	return NULL;
++
++#endif
++
++}
+--- /dev/null	2013-07-20 16:48:25.000000000 +0200
++++ ./keychain.h	2013-07-20 16:21:12.000000000 +0200
+@@ -0,0 +1,45 @@
++/*
++ * Copyright (c) 2007 Apple Inc. All rights reserved.
++ *
++ * @APPLE_BSD_LICENSE_HEADER_START@
++ * 
++ * Redistribution and use in source and binary forms, with or without
++ * modification, are permitted provided that the following conditions
++ * are met:
++ * 
++ * 1.  Redistributions of source code must retain the above copyright
++ *     notice, this list of conditions and the following disclaimer. 
++ * 2.  Redistributions in binary form must reproduce the above copyright
++ *     notice, this list of conditions and the following disclaimer in the
++ *     documentation and/or other materials provided with the distribution. 
++ * 3.  Neither the name of Apple Inc. ("Apple") nor the names of its
++ *     contributors may be used to endorse or promote products derived from
++ *     this software without specific prior written permission. 
++ * 
++ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS 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.
++ * 
++ * @APPLE_BSD_LICENSE_HEADER_END@
++ */
++
++/*
++ * KEYCHAIN indicates that keychain functionality is present.
++ * KEYCHAIN_* indicates the implementation to use, and implies KEYCHAIN.
++ */
++#if defined(__APPLE_KEYCHAIN__)
++#define KEYCHAIN
++#endif
++
++void	 store_in_keychain(const char *filename, const char *passphrase);
++void	 remove_from_keychain(const char *filename);
++int	 add_identities_using_keychain(
++	     int (*add_identity)(const char *, const char *));
++char	*keychain_read_passphrase(const char *filename, int oAskPassGUI);

Modified: trunk/dports/net/openssh/files/apple-keychain.patch
===================================================================
--- trunk/dports/net/openssh/files/apple-keychain.patch	2013-07-20 15:56:15 UTC (rev 108348)
+++ trunk/dports/net/openssh/files/apple-keychain.patch	2013-07-20 16:53:18 UTC (rev 108349)
@@ -39,10 +39,10 @@
  create mode 100644 keychain.c
  create mode 100644 keychain.h
 
-diff --git a/Makefile.in b/Makefile.in
+diff --git Makefile.in Makefile.in
 index e479a44..65538db 100644
---- a/Makefile.in
-+++ b/Makefile.in
+--- Makefile.in
++++ Makefile.in
 @@ -56,6 +56,7 @@ SED=@SED@
  ENT=@ENT@
  XAUTH_PATH=@XAUTH_PATH@
@@ -104,10 +104,10 @@
  	$(INSTALL) -m 0755 $(STRIP_OPT) ssh-pkcs11-helper$(EXEEXT) $(DESTDIR)$(SSH_PKCS11_HELPER)$(EXEEXT)
  	$(INSTALL) -m 0755 $(STRIP_OPT) sftp$(EXEEXT) $(DESTDIR)$(bindir)/sftp$(EXEEXT)
  	$(INSTALL) -m 0755 $(STRIP_OPT) sftp-server$(EXEEXT) $(DESTDIR)$(SFTP_SERVER)$(EXEEXT)
-diff --git a/audit-bsm.c b/audit-bsm.c
+diff --git audit-bsm.c audit-bsm.c
 index f196d4f..2899ef5 100644
---- a/audit-bsm.c
-+++ b/audit-bsm.c
+--- audit-bsm.c
++++ audit-bsm.c
 @@ -194,7 +194,12 @@ bsm_audit_record(int typ, char *string, au_event_t event_no)
  	pid_t		pid = getpid();
  	AuditInfoTermID	tid = ssh_bsm_tid;
@@ -122,10 +122,10 @@
  		uid = the_authctxt->pw->pw_uid;
  		gid = the_authctxt->pw->pw_gid;
  	}
-diff --git a/auth-pam.c b/auth-pam.c
+diff --git auth-pam.c auth-pam.c
 index 675006e..a195899 100644
---- a/auth-pam.c
-+++ b/auth-pam.c
+--- auth-pam.c
++++ auth-pam.c
 @@ -793,10 +793,11 @@ sshpam_query(void *ctx, char **name, char **info,
  				xfree(msg);
  				return (0);
@@ -140,10 +140,10 @@
  			/* FALLTHROUGH */
  		default:
  			*num = 0;
-diff --git a/auth.c b/auth.c
+diff --git auth.c auth.c
 index cd95da9..94fa21f 100644
---- a/auth.c
-+++ b/auth.c
+--- auth.c
++++ auth.c
 @@ -209,7 +209,7 @@ allowed_user(struct passwd * pw)
  	}
  	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
@@ -153,10 +153,10 @@
  			logit("User %.100s from %.100s not allowed because "
  			    "not in any group", pw->pw_name, hostname);
  			return 0;
-diff --git a/authfd.c b/authfd.c
+diff --git authfd.c authfd.c
 index f037e83..c25b157 100644
---- a/authfd.c
-+++ b/authfd.c
+--- authfd.c
++++ authfd.c
 @@ -689,6 +689,29 @@ ssh_remove_all_identities(AuthenticationConnection *auth, int version)
  	return decode_reply(type);
  }
@@ -187,10 +187,10 @@
  int
  decode_reply(int type)
  {
-diff --git a/authfd.h b/authfd.h
+diff --git authfd.h authfd.h
 index 2582a27..7b786fe 100644
---- a/authfd.h
-+++ b/authfd.h
+--- authfd.h
++++ authfd.h
 @@ -49,6 +49,9 @@
  #define SSH2_AGENTC_ADD_ID_CONSTRAINED		25
  #define SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED 26
@@ -201,10 +201,10 @@
  #define	SSH_AGENT_CONSTRAIN_LIFETIME		1
  #define	SSH_AGENT_CONSTRAIN_CONFIRM		2
  
-diff --git a/config.h.in b/config.h.in
+diff --git config.h.in config.h.in
 index baf0011..431720a 100644
---- a/config.h.in
-+++ b/config.h.in
+--- config.h.in
++++ config.h.in
 @@ -71,6 +71,18 @@
  /* Define if your snprintf is busted */
  #undef BROKEN_SNPRINTF
@@ -224,10 +224,10 @@
  /* tcgetattr with ICANON may hang */
  #undef BROKEN_TCGETATTR_ICANON
  
-diff --git a/configure.ac b/configure.ac
+diff --git configure.ac configure.ac
 index 8cc7ce9..bd8fdaa 100644
---- a/configure.ac
-+++ b/configure.ac
+--- configure.ac
++++ configure.ac
 @@ -4197,10 +4197,40 @@ if test ! -z "$blibpath" ; then
  	AC_MSG_WARN([Please check and edit blibpath in LDFLAGS in Makefile])
  fi
@@ -269,10 +269,10 @@
  if test "x$ac_cv_func_getaddrinfo" != "xyes" ; then
  	TEST_SSH_IPV6=no
  else
-diff --git a/groupaccess.c b/groupaccess.c
+diff --git groupaccess.c groupaccess.c
 index 2381aeb..2b5c600 100644
---- a/groupaccess.c
-+++ b/groupaccess.c
+--- groupaccess.c
++++ groupaccess.c
 @@ -33,38 +33,67 @@
  #include <stdarg.h>
  #include <string.h>
@@ -381,10 +381,10 @@
  	return 0;
  }
  
-diff --git a/groupaccess.h b/groupaccess.h
+diff --git groupaccess.h groupaccess.h
 index 000578e..ddea117 100644
---- a/groupaccess.h
-+++ b/groupaccess.h
+--- groupaccess.h
++++ groupaccess.h
 @@ -27,7 +27,7 @@
  #ifndef GROUPACCESS_H
  #define GROUPACCESS_H
@@ -394,11 +394,11 @@
  int	 ga_match(char * const *, int);
  int	 ga_match_pattern_list(const char *);
  void	 ga_free(void);
-diff --git a/keychain.c b/keychain.c
+diff --git keychain.c keychain.c
 new file mode 100644
 index 0000000..a6d5855
 --- /dev/null
-+++ b/keychain.c
++++ keychain.c
 @@ -0,0 +1,694 @@
 +/*
 + * Copyright (c) 2007 Apple Inc. All rights reserved.
@@ -1094,11 +1094,11 @@
 +#endif
 +
 +}
-diff --git a/keychain.h b/keychain.h
+diff --git keychain.h keychain.h
 new file mode 100644
 index 0000000..3ab1a6b
 --- /dev/null
-+++ b/keychain.h
++++ keychain.h
 @@ -0,0 +1,45 @@
 +/*
 + * Copyright (c) 2007 Apple Inc. All rights reserved.
@@ -1145,10 +1145,10 @@
 +int	 add_identities_using_keychain(
 +	     int (*add_identity)(const char *, const char *));
 +char	*keychain_read_passphrase(const char *filename, int oAskPassGUI);
-diff --git a/readconf.c b/readconf.c
+diff --git readconf.c readconf.c
 index 60befde..0fe8fb1 100644
---- a/readconf.c
-+++ b/readconf.c
+--- readconf.c
++++ readconf.c
 @@ -137,6 +137,9 @@ typedef enum {
  	oTunnel, oTunnelDevice, oLocalCommand, oPermitLocalCommand,
  	oVisualHostKey, oUseRoaming, oZeroKnowledgePasswordAuthentication,
@@ -1204,10 +1204,10 @@
  	/* options->local_command should not be set by default */
  	/* options->proxy_command should not be set by default */
  	/* options->user will be set in the main program if appropriate */
-diff --git a/readconf.h b/readconf.h
+diff --git readconf.h readconf.h
 index 617686f..150e95b 100644
---- a/readconf.h
-+++ b/readconf.h
+--- readconf.h
++++ readconf.h
 @@ -139,6 +139,10 @@ typedef struct {
  	int	use_roaming;
  
@@ -1219,10 +1219,10 @@
  }       Options;
  
  #define SSHCTL_MASTER_NO	0
-diff --git a/scp.1 b/scp.1
+diff --git scp.1 scp.1
 index 577dd52..c93fb0e 100644
---- a/scp.1
-+++ b/scp.1
+--- scp.1
++++ scp.1
 @@ -19,7 +19,7 @@
  .Sh SYNOPSIS
  .Nm scp
@@ -1241,10 +1241,10 @@
  .It Fl c Ar cipher
  Selects the cipher to use for encrypting the data transfer.
  This option is directly passed to
-diff --git a/scp.c b/scp.c
+diff --git scp.c scp.c
 index 18b2597..439530d 100644
---- a/scp.c
-+++ b/scp.c
+--- scp.c
++++ scp.c
 @@ -78,6 +78,9 @@
  #ifdef HAVE_SYS_STAT_H
  # include <sys/stat.h>
@@ -1497,10 +1497,10 @@
  	    "           [-l limit] [-o ssh_option] [-P port] [-S program]\n"
  	    "           [[user@]host1:]file1 ... [[user@]host2:]file2\n");
  	exit(1);
-diff --git a/servconf.c b/servconf.c
+diff --git servconf.c servconf.c
 index 756a3a2..0e2678e 100644
---- a/servconf.c
-+++ b/servconf.c
+--- servconf.c
++++ servconf.c
 @@ -148,7 +148,7 @@ fill_default_server_options(ServerOptions *options)
  {
  	/* Portable-specific options */
@@ -1528,10 +1528,10 @@
  		debug("Can't Match group because user %.100s not in any group "
  		    "at line %d", user, line);
  	} else if (ga_match_pattern_list(grps) != 1) {
-diff --git a/session.c b/session.c
+diff --git session.c session.c
 index 6a70400..42e6fac 100644
---- a/session.c
-+++ b/session.c
+--- session.c
++++ session.c
 @@ -2063,8 +2063,10 @@ session_pty_req(Session *s)
  		n_bytes = packet_remaining();
  	tty_parse_modes(s->ttyfd, &n_bytes);
@@ -1555,10 +1555,10 @@
  
  	/*
  	 * Close the server side of the socket pairs.  We must do this after
-diff --git a/ssh-add.0 b/ssh-add.0
+diff --git ssh-add.0 ssh-add.0
 index e1e2a64..74ee18a 100644
---- a/ssh-add.0
-+++ b/ssh-add.0
+--- ssh-add.0
++++ ssh-add.0
 @@ -1,10 +1,10 @@
  SSH-ADD(1)                 OpenBSD Reference Manual                 SSH-ADD(1)
  
@@ -1586,10 +1586,10 @@
  ENVIRONMENT
       DISPLAY and SSH_ASKPASS
               If ssh-add needs a passphrase, it will read the passphrase from
-diff --git a/ssh-add.1 b/ssh-add.1
+diff --git ssh-add.1 ssh-add.1
 index fd48ff9..0bd1114 100644
---- a/ssh-add.1
-+++ b/ssh-add.1
+--- ssh-add.1
++++ ssh-add.1
 @@ -43,7 +43,7 @@
  .Nd adds private key identities to the authentication agent
  .Sh SYNOPSIS
@@ -1612,10 +1612,10 @@
  .El
  .Sh ENVIRONMENT
  .Bl -tag -width Ds
-diff --git a/ssh-add.c b/ssh-add.c
+diff --git ssh-add.c ssh-add.c
 index 6d5e2a9..9621451 100644
---- a/ssh-add.c
-+++ b/ssh-add.c
+--- ssh-add.c
++++ ssh-add.c
 @@ -62,6 +62,7 @@
  #include "authfile.h"
  #include "pathnames.h"
@@ -1780,10 +1780,10 @@
  				ret = 1;
  		}
  	}
-diff --git a/ssh-agent.c b/ssh-agent.c
+diff --git ssh-agent.c ssh-agent.c
 index b9498e6..a154096 100644
---- a/ssh-agent.c
-+++ b/ssh-agent.c
+--- ssh-agent.c
++++ ssh-agent.c
 @@ -65,6 +65,9 @@
  #include <time.h>
  #include <string.h>
@@ -2014,10 +2014,10 @@
  	while (1) {
  		prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
  		result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
-diff --git a/ssh-keysign.8 b/ssh-keysign.8
+diff --git ssh-keysign.8 ssh-keysign.8
 index 5e09e02..612c8f8 100644
---- a/ssh-keysign.8
-+++ b/ssh-keysign.8
+--- ssh-keysign.8
++++ ssh-keysign.8
 @@ -71,6 +71,9 @@ accessible to others.
  Since they are readable only by root,
  .Nm
@@ -2028,10 +2028,10 @@
  .Pp
  .It Pa /etc/ssh/ssh_host_dsa_key-cert.pub
  .It Pa /etc/ssh/ssh_host_ecdsa_key-cert.pub
-diff --git a/sshconnect1.c b/sshconnect1.c
+diff --git sshconnect1.c sshconnect1.c
 index fd07bbf..f9eaeba 100644
---- a/sshconnect1.c
-+++ b/sshconnect1.c
+--- sshconnect1.c
++++ sshconnect1.c
 @@ -47,6 +47,7 @@
  #include "canohost.h"
  #include "hostfile.h"
@@ -2051,10 +2051,10 @@
  			passphrase = read_passphrase(buf, 0);
  			if (strcmp(passphrase, "") != 0) {
  				private = key_load_private_type(KEY_RSA1,
-diff --git a/sshconnect2.c b/sshconnect2.c
+diff --git sshconnect2.c sshconnect2.c
 index 3ddef32..a8ed741 100644
---- a/sshconnect2.c
-+++ b/sshconnect2.c
+--- sshconnect2.c
++++ sshconnect2.c
 @@ -72,6 +72,7 @@
  #include "hostfile.h"
  #include "schnorr.h"
@@ -2074,10 +2074,10 @@
  			passphrase = read_passphrase(prompt, 0);
  			if (strcmp(passphrase, "") != 0) {
  				private = key_load_private_type(KEY_UNSPEC,
-diff --git a/sshd.0 b/sshd.0
+diff --git sshd.0 sshd.0
 index e8b4983..471841c 100644
---- a/sshd.0
-+++ b/sshd.0
+--- sshd.0
++++ sshd.0
 @@ -617,8 +617,8 @@ FILES
  
  SEE ALSO
@@ -2089,10 +2089,10 @@
  
  AUTHORS
       OpenSSH is a derivative of the original and free ssh 1.2.12 release by
-diff --git a/sshd.8 b/sshd.8
+diff --git sshd.8 sshd.8
 index a91be0f..18941a6 100644
---- a/sshd.8
-+++ b/sshd.8
+--- sshd.8
++++ sshd.8
 @@ -950,10 +950,7 @@ The content of this file is not sensitive; it can be world-readable.
  .Xr ssh-keyscan 1 ,
  .Xr chroot 2 ,
@@ -2104,10 +2104,10 @@
  .Xr sftp-server 8
  .Sh AUTHORS
  OpenSSH is a derivative of the original and free
-diff --git a/sshd.c b/sshd.c
+diff --git sshd.c sshd.c
 index 112a5f9..4773543 100644
---- a/sshd.c
-+++ b/sshd.c
+--- sshd.c
++++ sshd.c
 @@ -2076,6 +2076,12 @@ main(int ac, char **av)
  	audit_event(SSH_AUTH_SUCCESS);
  #endif
@@ -2134,10 +2134,10 @@
  
  	/*
  	 * In privilege separation, we fork another child and prepare
-diff --git a/sshd_config b/sshd_config
+diff --git sshd_config sshd_config
 index d02d7a7..53966ab 100644
---- a/sshd_config
-+++ b/sshd_config
+--- sshd_config
++++ sshd_config
 @@ -31,7 +31,7 @@
  
  # Logging
@@ -2171,10 +2171,10 @@
  
  #AllowAgentForwarding yes
  #AllowTcpForwarding yes
-diff --git a/sshd_config.0 b/sshd_config.0
+diff --git sshd_config.0 sshd_config.0
 index e19ca87..5bee36a 100644
---- a/sshd_config.0
-+++ b/sshd_config.0
+--- sshd_config.0
++++ sshd_config.0
 @@ -436,7 +436,7 @@ DESCRIPTION
  
       PasswordAuthentication
@@ -2193,10 +2193,10 @@
  
       UsePrivilegeSeparation
               Specifies whether sshd(8) separates privileges by creating an
-diff --git a/sshd_config.5 b/sshd_config.5
+diff --git sshd_config.5 sshd_config.5
 index 76c95aa..adebac6 100644
---- a/sshd_config.5
-+++ b/sshd_config.5
+--- sshd_config.5
++++ sshd_config.5
 @@ -794,7 +794,7 @@ are refused if the number of unauthenticated connections reaches
  .It Cm PasswordAuthentication
  Specifies whether password authentication is allowed.

Deleted: trunk/dports/net/openssh/files/openssh-5.0p1-gsskex-20080404.patch
===================================================================
--- trunk/dports/net/openssh/files/openssh-5.0p1-gsskex-20080404.patch	2013-07-20 15:56:15 UTC (rev 108348)
+++ trunk/dports/net/openssh/files/openssh-5.0p1-gsskex-20080404.patch	2013-07-20 16:53:18 UTC (rev 108349)
@@ -1,2295 +0,0 @@
-? gss-genr.c.pre14
-? kex.c.pre14
-? kex.h.pre14
-? kexgssc.c.pre14
-? kexgsss.c.pre14
-? monitor.c.pre14
-? new.patch
-? ssh-gss.h.pre14
-? sshconnect2.c.pre14
-? sshd.c.pre14
-Index: ChangeLog.gssapi
-===================================================================
-RCS file: ChangeLog.gssapi
-diff -N ChangeLog.gssapi
---- /dev/null	1 Jan 1970 00:00:00 -0000
-+++ ChangeLog.gssapi	4 Apr 2008 12:52:27 -0000
-@@ -0,0 +1,75 @@
-+20080404
-+  - [ gss-serv.c ]
-+    Add code to actually implement GSSAPIStrictAcceptCheck, which had somehow
-+    been omitted from a previous version of this patch. Reported by Borislav
-+    Stoichkov
-+
-+20070317
-+  - [ gss-serv-krb5.c ]
-+    Remove C99ism, where new_ccname was being declared in the middle of a 
-+    function
-+
-+20061220
-+  - [ servconf.c ]
-+    Make default for GSSAPIStrictAcceptorCheck be Yes, to match previous, and 
-+    documented, behaviour. Reported by Dan Watson.
-+
-+20060910
-+  - [ gss-genr.c kexgssc.c kexgsss.c kex.h monitor.c sshconnect2.c sshd.c
-+      ssh-gss.h ]
-+    add support for gss-group14-sha1 key exchange mechanisms
-+  - [ gss-serv.c servconf.c servconf.h sshd_config sshd_config.5 ]
-+    Add GSSAPIStrictAcceptorCheck option to allow the disabling of
-+    acceptor principal checking on multi-homed machines.
-+    <Bugzilla #928>
-+  - [ sshd_config ssh_config ]
-+    Add settings for GSSAPIKeyExchange and GSSAPITrustDNS to the sample
-+    configuration files
-+  - [ kexgss.c kegsss.c sshconnect2.c sshd.c ]
-+    Code cleanup. Replace strlen/xmalloc/snprintf sequences with xasprintf()
-+    Limit length of error messages displayed by client
-+
-+20060909
-+  - [ gss-genr.c gss-serv.c ]
-+    move ssh_gssapi_acquire_cred() and ssh_gssapi_server_ctx to be server
-+    only, where they belong 
-+    <Bugzilla #1225>
-+
-+20060829
-+  - [ gss-serv-krb5.c ]
-+    Fix CCAPI credentials cache name when creating KRB5CCNAME environment 
-+    variable
-+
-+20060828
-+  - [ gss-genr.c ]
-+    Avoid Heimdal context freeing problem
-+    <Fixed upstream 20060829>
-+
-+20060818
-+  - [ gss-genr.c ssh-gss.h sshconnect2.c ]
-+    Make sure that SPENGO is disabled 
-+    <Bugzilla #1218 - Fixed upstream 20060818>
-+
-+20060421
-+  - [ gssgenr.c, sshconnect2.c ]
-+    a few type changes (signed versus unsigned, int versus size_t) to
-+    fix compiler errors/warnings 
-+    (from jbasney AT ncsa.uiuc.edu)
-+  - [ kexgssc.c, sshconnect2.c ]
-+    fix uninitialized variable warnings
-+    (from jbasney AT ncsa.uiuc.edu)
-+  - [ gssgenr.c ]
-+    pass oid to gss_display_status (helpful when using GSSAPI mechglue)
-+    (from jbasney AT ncsa.uiuc.edu)
-+    <Bugzilla #1220 >
-+  - [ gss-serv-krb5.c ]
-+    #ifdef HAVE_GSSAPI_KRB5 should be #ifdef HAVE_GSSAPI_KRB5_H
-+    (from jbasney AT ncsa.uiuc.edu)
-+    <Fixed upstream 20060304>
-+  - [ readconf.c, readconf.h, ssh_config.5, sshconnect2.c 
-+    add client-side GssapiKeyExchange option
-+    (from jbasney AT ncsa.uiuc.edu)
-+  - [ sshconnect2.c ]
-+    add support for GssapiTrustDns option for gssapi-with-mic
-+    (from jbasney AT ncsa.uiuc.edu)
-+    <gssapi-with-mic support is Bugzilla #1008>
-Index: Makefile.in
-===================================================================
-RCS file: /cvs/openssh/Makefile.in,v
-retrieving revision 1.289
-diff -u -r1.289 Makefile.in
---- Makefile.in	13 Mar 2008 01:41:31 -0000	1.289
-+++ Makefile.in	4 Apr 2008 12:52:27 -0000
-@@ -71,7 +71,7 @@
- 	atomicio.o key.o dispatch.o kex.o mac.o uidswap.o uuencode.o misc.o \
- 	monitor_fdpass.o rijndael.o ssh-dss.o ssh-rsa.o dh.o kexdh.o \
- 	kexgex.o kexdhc.o kexgexc.o scard.o msg.o progressmeter.o dns.o \
--	entropy.o scard-opensc.o gss-genr.o umac.o
-+	entropy.o scard-opensc.o gss-genr.o umac.o kexgssc.o
- 
- SSHOBJS= ssh.o readconf.o clientloop.o sshtty.o \
- 	sshconnect.o sshconnect1.o sshconnect2.o
-@@ -84,7 +84,7 @@
- 	auth2-none.o auth2-passwd.o auth2-pubkey.o \
- 	monitor_mm.o monitor.o monitor_wrap.o kexdhs.o kexgexs.o \
- 	auth-krb5.o \
--	auth2-gss.o gss-serv.o gss-serv-krb5.o \
-+	auth2-gss.o gss-serv.o gss-serv-krb5.o kexgsss.o\
- 	loginrec.o auth-pam.o auth-shadow.o auth-sia.o md5crypt.o \
- 	audit.o audit-bsm.o platform.o sftp-server.o sftp-common.o
- 
-Index: auth-krb5.c
-===================================================================
-RCS file: /cvs/openssh/auth-krb5.c,v
-retrieving revision 1.35
-diff -u -r1.35 auth-krb5.c
---- auth-krb5.c	5 Aug 2006 02:39:39 -0000	1.35
-+++ auth-krb5.c	4 Apr 2008 12:52:28 -0000
-@@ -166,8 +166,13 @@
- 
- 	len = strlen(authctxt->krb5_ticket_file) + 6;
- 	authctxt->krb5_ccname = xmalloc(len);
-+#ifdef USE_CCAPI
-+	snprintf(authctxt->krb5_ccname, len, "API:%s",
-+	    authctxt->krb5_ticket_file);
-+#else
- 	snprintf(authctxt->krb5_ccname, len, "FILE:%s",
- 	    authctxt->krb5_ticket_file);
-+#endif
- 
- #ifdef USE_PAM
- 	if (options.use_pam)
-@@ -219,15 +224,22 @@
- #ifndef HEIMDAL
- krb5_error_code
- ssh_krb5_cc_gen(krb5_context ctx, krb5_ccache *ccache) {
--	int tmpfd, ret;
-+	int ret;
- 	char ccname[40];
- 	mode_t old_umask;
-+#ifdef USE_CCAPI
-+	char cctemplate[] = "API:krb5cc_%d";
-+#else
-+	char cctemplate[] = "FILE:/tmp/krb5cc_%d_XXXXXXXXXX";
-+	int tmpfd;
-+#endif
- 
- 	ret = snprintf(ccname, sizeof(ccname),
--	    "FILE:/tmp/krb5cc_%d_XXXXXXXXXX", geteuid());
-+	    cctemplate, geteuid());
- 	if (ret < 0 || (size_t)ret >= sizeof(ccname))
- 		return ENOMEM;
- 
-+#ifndef USE_CCAPI
- 	old_umask = umask(0177);
- 	tmpfd = mkstemp(ccname + strlen("FILE:"));
- 	umask(old_umask);
-@@ -242,6 +254,7 @@
- 		return errno;
- 	}
- 	close(tmpfd);
-+#endif
- 
- 	return (krb5_cc_resolve(ctx, ccname, ccache));
- }
-Index: auth.h
-===================================================================
-RCS file: /cvs/openssh/auth.h,v
-retrieving revision 1.78
-diff -u -r1.78 auth.h
---- auth.h	26 Oct 2007 04:25:13 -0000	1.78
-+++ auth.h	4 Apr 2008 12:52:28 -0000
-@@ -53,6 +53,7 @@
- 	int		 valid;		/* user exists and is allowed to login */
- 	int		 attempt;
- 	int		 failures;
-+	int		 server_caused_failure; 
- 	int		 force_pwchange;
- 	char		*user;		/* username sent by the client */
- 	char		*service;
-Index: auth2-gss.c
-===================================================================
-RCS file: /cvs/openssh/auth2-gss.c,v
-retrieving revision 1.19
-diff -u -r1.19 auth2-gss.c
---- auth2-gss.c	2 Dec 2007 11:59:45 -0000	1.19
-+++ auth2-gss.c	4 Apr 2008 12:52:28 -0000
-@@ -52,6 +52,39 @@
- static void input_gssapi_exchange_complete(int type, u_int32_t plen, void *ctxt);
- static void input_gssapi_errtok(int, u_int32_t, void *);
- 
-+/* 
-+ * The 'gssapi_keyex' userauth mechanism.
-+ */
-+static int
-+userauth_gsskeyex(Authctxt *authctxt)
-+{
-+	int authenticated = 0;
-+	Buffer b;
-+	gss_buffer_desc mic, gssbuf;
-+	u_int len;
-+
-+	mic.value = packet_get_string(&len);
-+	mic.length = len;
-+
-+	packet_check_eom();
-+
-+	ssh_gssapi_buildmic(&b, authctxt->user, authctxt->service,
-+	    "gssapi-keyex");
-+
-+	gssbuf.value = buffer_ptr(&b);
-+	gssbuf.length = buffer_len(&b);
-+
-+	/* gss_kex_context is NULL with privsep, so we can't check it here */
-+	if (!GSS_ERROR(PRIVSEP(ssh_gssapi_checkmic(gss_kex_context, 
-+	    &gssbuf, &mic))))
-+		authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user));
-+	
-+	buffer_free(&b);
-+	xfree(mic.value);
-+
-+	return (authenticated);
-+}
-+
- /*
-  * We only support those mechanisms that we know about (ie ones that we know
-  * how to check local user kuserok and the like)
-@@ -102,6 +135,7 @@
- 
- 	if (!present) {
- 		xfree(doid);
-+		authctxt->server_caused_failure = 1;
- 		return (0);
- 	}
- 
-@@ -109,6 +143,7 @@
- 		if (ctxt != NULL)
- 			ssh_gssapi_delete_ctx(&ctxt);
- 		xfree(doid);
-+		authctxt->server_caused_failure = 1;
- 		return (0);
- 	}
- 
-@@ -291,6 +326,12 @@
- 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, NULL);
- 	userauth_finish(authctxt, authenticated, "gssapi-with-mic");
- }
-+
-+Authmethod method_gsskeyex = {
-+	"gssapi-keyex",
-+	userauth_gsskeyex,
-+	&options.gss_authentication
-+};
- 
- Authmethod method_gssapi = {
- 	"gssapi-with-mic",
-Index: auth2.c
-===================================================================
-RCS file: /cvs/openssh/auth2.c,v
-retrieving revision 1.145
-diff -u -r1.145 auth2.c
---- auth2.c	26 Oct 2007 04:26:16 -0000	1.145
-+++ auth2.c	4 Apr 2008 12:52:28 -0000
-@@ -64,6 +64,7 @@
- extern Authmethod method_kbdint;
- extern Authmethod method_hostbased;
- #ifdef GSSAPI
-+extern Authmethod method_gsskeyex;
- extern Authmethod method_gssapi;
- #endif
- 
-@@ -71,6 +72,7 @@
- 	&method_none,
- 	&method_pubkey,
- #ifdef GSSAPI
-+	&method_gsskeyex,
- 	&method_gssapi,
- #endif
- 	&method_passwd,
-@@ -194,6 +196,7 @@
- #endif
- 
- 	authctxt->postponed = 0;
-+	authctxt->server_caused_failure = 0;
- 
- 	/* try to authenticate user */
- 	m = authmethod_lookup(method);
-@@ -264,7 +267,9 @@
- 		/* now we can break out */
- 		authctxt->success = 1;
- 	} else {
--		if (authctxt->failures++ > options.max_authtries) {
-+		/* Dont count server configuration issues against the client */
-+		if (!authctxt->server_caused_failure && 
-+		    authctxt->failures++ > options.max_authtries) {
- #ifdef SSH_AUDIT_EVENTS
- 			PRIVSEP(audit_event(SSH_LOGIN_EXCEED_MAXTRIES));
- #endif
-Index: configure.ac
-===================================================================
-RCS file: /cvs/openssh/configure.ac,v
-retrieving revision 1.397
-diff -u -r1.397 configure.ac
---- configure.ac	27 Mar 2008 01:33:07 -0000	1.397
-+++ configure.ac	4 Apr 2008 12:52:29 -0000
-@@ -459,6 +459,30 @@
- 	    [Use tunnel device compatibility to OpenBSD])
- 	AC_DEFINE(SSH_TUN_PREPEND_AF, 1,
- 	    [Prepend the address family to IP tunnel traffic])
-+	AC_MSG_CHECKING(if we have the Security Authorization Session API)
-+	AC_TRY_COMPILE([#include <Security/AuthSession.h>],
-+		[SessionCreate(0, 0);],
-+		[ac_cv_use_security_session_api="yes"
-+		 AC_DEFINE(USE_SECURITY_SESSION_API, 1, 
-+			[platform has the Security Authorization Session API])
-+		 LIBS="$LIBS -framework Security"
-+		 AC_MSG_RESULT(yes)],
-+		[ac_cv_use_security_session_api="no"
-+		 AC_MSG_RESULT(no)])
-+	AC_MSG_CHECKING(if we have an in-memory credentials cache)
-+	AC_TRY_COMPILE(
-+		[#include <Kerberos/Kerberos.h>],
-+		[cc_context_t c;
-+		 (void) cc_initialize (&c, 0, NULL, NULL);],
-+		[AC_DEFINE(USE_CCAPI, 1, 
-+			[platform uses an in-memory credentials cache])
-+		 LIBS="$LIBS -framework Security"
-+		 AC_MSG_RESULT(yes)
-+		 if test "x$ac_cv_use_security_session_api" = "xno"; then
-+			AC_MSG_ERROR(*** Need a security framework to use the credentials cache API ***)
-+		fi],
-+		[AC_MSG_RESULT(no)]
-+	)
- 	m4_pattern_allow(AU_IPv)
- 	AC_CHECK_DECL(AU_IPv4, [], 
- 	    AC_DEFINE(AU_IPv4, 0, [System only supports IPv4 audit records])
-Index: gss-genr.c
-===================================================================
-RCS file: /cvs/openssh/gss-genr.c,v
-retrieving revision 1.21
-diff -u -r1.21 gss-genr.c
---- gss-genr.c	12 Jun 2007 13:44:36 -0000	1.21
-+++ gss-genr.c	4 Apr 2008 12:52:29 -0000
-@@ -39,12 +39,160 @@
- #include "buffer.h"
- #include "log.h"
- #include "ssh2.h"
-+#include "cipher.h"
-+#include "key.h"
-+#include "kex.h"
-+#include <openssl/evp.h>
- 
- #include "ssh-gss.h"
- 
- extern u_char *session_id2;
- extern u_int session_id2_len;
- 
-+typedef struct {
-+	char *encoded;
-+	gss_OID oid;
-+} ssh_gss_kex_mapping;
-+
-+/*
-+ * XXX - It would be nice to find a more elegant way of handling the
-+ * XXX   passing of the key exchange context to the userauth routines
-+ */
-+
-+Gssctxt *gss_kex_context = NULL;
-+
-+static ssh_gss_kex_mapping *gss_enc2oid = NULL;
-+
-+int 
-+ssh_gssapi_oid_table_ok() {
-+	return (gss_enc2oid != NULL);
-+}
-+
-+/*
-+ * Return a list of the gss-group1-sha1 mechanisms supported by this program
-+ *
-+ * We test mechanisms to ensure that we can use them, to avoid starting
-+ * a key exchange with a bad mechanism
-+ */
-+
-+char *
-+ssh_gssapi_client_mechanisms(const char *host) {
-+	gss_OID_set gss_supported;
-+	OM_uint32 min_status;
-+
-+	gss_indicate_mechs(&min_status, &gss_supported);
-+
-+	return(ssh_gssapi_kex_mechs(gss_supported, ssh_gssapi_check_mechanism,
-+	    host));
-+}
-+
-+char *
-+ssh_gssapi_kex_mechs(gss_OID_set gss_supported, ssh_gssapi_check_fn *check,
-+    const char *data) {
-+	Buffer buf;
-+	size_t i;
-+	int oidpos, enclen;
-+	char *mechs, *encoded;
-+	u_char digest[EVP_MAX_MD_SIZE];
-+	char deroid[2];
-+	const EVP_MD *evp_md = EVP_md5();
-+	EVP_MD_CTX md;
-+
-+	if (gss_enc2oid != NULL) {
-+		for (i = 0; gss_enc2oid[i].encoded != NULL; i++)
-+			xfree(gss_enc2oid[i].encoded);
-+		xfree(gss_enc2oid);
-+	}
-+
-+	gss_enc2oid = xmalloc(sizeof(ssh_gss_kex_mapping) *
-+	    (gss_supported->count + 1));
-+
-+	buffer_init(&buf);
-+
-+	oidpos = 0;
-+	for (i = 0; i < gss_supported->count; i++) {
-+		if (gss_supported->elements[i].length < 128 &&
-+		    (*check)(NULL, &(gss_supported->elements[i]), data)) {
-+
-+			deroid[0] = SSH_GSS_OIDTYPE;
-+			deroid[1] = gss_supported->elements[i].length;
-+
-+			EVP_DigestInit(&md, evp_md);
-+			EVP_DigestUpdate(&md, deroid, 2);
-+			EVP_DigestUpdate(&md,
-+			    gss_supported->elements[i].elements,
-+			    gss_supported->elements[i].length);
-+			EVP_DigestFinal(&md, digest, NULL);
-+
-+			encoded = xmalloc(EVP_MD_size(evp_md) * 2);
-+			enclen = __b64_ntop(digest, EVP_MD_size(evp_md),
-+			    encoded, EVP_MD_size(evp_md) * 2);
-+
-+			if (oidpos != 0)
-+				buffer_put_char(&buf, ',');
-+
-+			buffer_append(&buf, KEX_GSS_GEX_SHA1_ID,
-+			    sizeof(KEX_GSS_GEX_SHA1_ID) - 1);
-+			buffer_append(&buf, encoded, enclen);
-+			buffer_put_char(&buf, ',');
-+			buffer_append(&buf, KEX_GSS_GRP1_SHA1_ID, 
-+			    sizeof(KEX_GSS_GRP1_SHA1_ID) - 1);
-+			buffer_append(&buf, encoded, enclen);
-+			buffer_put_char(&buf, ',');
-+			buffer_append(&buf, KEX_GSS_GRP14_SHA1_ID,
-+			    sizeof(KEX_GSS_GRP14_SHA1_ID) - 1);
-+			buffer_append(&buf, encoded, enclen);
-+
-+			gss_enc2oid[oidpos].oid = &(gss_supported->elements[i]);
-+			gss_enc2oid[oidpos].encoded = encoded;
-+			oidpos++;
-+		}
-+	}
-+	gss_enc2oid[oidpos].oid = NULL;
-+	gss_enc2oid[oidpos].encoded = NULL;
-+
-+	buffer_put_char(&buf, '\0');
-+
-+	mechs = xmalloc(buffer_len(&buf));
-+	buffer_get(&buf, mechs, buffer_len(&buf));
-+	buffer_free(&buf);
-+
-+	if (strlen(mechs) == 0) {
-+		xfree(mechs);
-+		mechs = NULL;
-+	}
-+	
-+	return (mechs);
-+}
-+
-+gss_OID
-+ssh_gssapi_id_kex(Gssctxt *ctx, char *name, int kex_type) {
-+	int i = 0;
-+	
-+	switch (kex_type) {
-+	case KEX_GSS_GRP1_SHA1:
-+		name += sizeof(KEX_GSS_GRP1_SHA1_ID) - 1;
-+		break;
-+	case KEX_GSS_GRP14_SHA1:
-+		name += sizeof(KEX_GSS_GRP14_SHA1_ID) - 1;
-+		break;
-+	case KEX_GSS_GEX_SHA1:
-+		name += sizeof(KEX_GSS_GEX_SHA1_ID) - 1;
-+		break;
-+	default:
-+		return GSS_C_NO_OID;
-+	}
-+
-+	while (gss_enc2oid[i].encoded != NULL &&
-+	    strcmp(name, gss_enc2oid[i].encoded) != 0)
-+		i++;
-+
-+	if (gss_enc2oid[i].oid != NULL && ctx != NULL)
-+		ssh_gssapi_set_oid(ctx, gss_enc2oid[i].oid);
-+
-+	return gss_enc2oid[i].oid;
-+}
-+
- /* Check that the OID in a data stream matches that in the context */
- int
- ssh_gssapi_check_oid(Gssctxt *ctx, void *data, size_t len)
-@@ -229,6 +377,9 @@
- OM_uint32
- ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_t buffer, gss_buffer_t hash)
- {
-+	if (ctx == NULL) 
-+		return -1;
-+
- 	if ((ctx->major = gss_get_mic(&ctx->minor, ctx->context,
- 	    GSS_C_QOP_DEFAULT, buffer, hash)))
- 		ssh_gssapi_error(ctx);
-@@ -236,6 +387,19 @@
- 	return (ctx->major);
- }
- 
-+/* Priviledged when used by server */
-+OM_uint32
-+ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
-+{
-+	if (ctx == NULL)
-+		return -1;
-+
-+	ctx->major = gss_verify_mic(&ctx->minor, ctx->context,
-+	    gssbuf, gssmic, NULL);
-+
-+	return (ctx->major);
-+}
-+
- void
- ssh_gssapi_buildmic(Buffer *b, const char *user, const char *service,
-     const char *context)
-@@ -254,6 +418,10 @@
- 	gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
- 	OM_uint32 major, minor;
- 	gss_OID_desc spnego_oid = {6, (void *)"\x2B\x06\x01\x05\x05\x02"};
-+	Gssctxt *intctx = NULL;
-+
-+	if (ctx == NULL)
-+		ctx = &intctx;
- 
- 	/* RFC 4462 says we MUST NOT do SPNEGO */
- 	if (oid->length == spnego_oid.length && 
-@@ -272,7 +440,7 @@
- 			    GSS_C_NO_BUFFER);
- 	}
- 
--	if (GSS_ERROR(major)) 
-+	if (GSS_ERROR(major) || intctx != NULL) 
- 		ssh_gssapi_delete_ctx(ctx);
- 
- 	return (!GSS_ERROR(major));
-Index: gss-serv-krb5.c
-===================================================================
-RCS file: /cvs/openssh/gss-serv-krb5.c,v
-retrieving revision 1.17
-diff -u -r1.17 gss-serv-krb5.c
---- gss-serv-krb5.c	1 Sep 2006 05:38:36 -0000	1.17
-+++ gss-serv-krb5.c	4 Apr 2008 12:52:29 -0000
-@@ -120,6 +120,7 @@
- 	krb5_principal princ;
- 	OM_uint32 maj_status, min_status;
- 	int len;
-+	const char *new_ccname;
- 
- 	if (client->creds == NULL) {
- 		debug("No credentials stored");
-@@ -168,11 +169,16 @@
- 		return;
- 	}
- 
--	client->store.filename = xstrdup(krb5_cc_get_name(krb_context, ccache));
-+	new_ccname = krb5_cc_get_name(krb_context, ccache);
-+
- 	client->store.envvar = "KRB5CCNAME";
--	len = strlen(client->store.filename) + 6;
--	client->store.envval = xmalloc(len);
--	snprintf(client->store.envval, len, "FILE:%s", client->store.filename);
-+#ifdef USE_CCAPI
-+	xasprintf(&client->store.envval, "API:%s", new_ccname);
-+	client->store.filename = NULL;
-+#else
-+	xasprintf(&client->store.envval, "FILE:%s", new_ccname);
-+	client->store.filename = xstrdup(new_ccname);
-+#endif
- 
- #ifdef USE_PAM
- 	if (options.use_pam)
-Index: gss-serv.c
-===================================================================
-RCS file: /cvs/openssh/gss-serv.c,v
-retrieving revision 1.23
-diff -u -r1.23 gss-serv.c
---- gss-serv.c	12 Jun 2007 13:40:39 -0000	1.23
-+++ gss-serv.c	4 Apr 2008 12:52:29 -0000
-@@ -1,7 +1,7 @@
- /* $OpenBSD: gss-serv.c,v 1.21 2007/06/12 08:20:00 djm Exp $ */
- 
- /*
-- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
-+ * Copyright (c) 2001-2008 Simon Wilkinson. All rights reserved.
-  *
-  * Redistribution and use in source and binary forms, with or without
-  * modification, are permitted provided that the following conditions
-@@ -44,8 +44,12 @@
- #include "channels.h"
- #include "session.h"
- #include "misc.h"
-+#include "servconf.h"
- 
- #include "ssh-gss.h"
-+#include "monitor_wrap.h"
-+
-+extern ServerOptions options;
- 
- static ssh_gssapi_client gssapi_client =
-     { GSS_C_EMPTY_BUFFER, GSS_C_EMPTY_BUFFER,
-@@ -80,25 +84,32 @@
- 	char lname[MAXHOSTNAMELEN];
- 	gss_OID_set oidset;
- 
--	gss_create_empty_oid_set(&status, &oidset);
--	gss_add_oid_set_member(&status, ctx->oid, &oidset);
-+	if (options.gss_strict_acceptor) {
-+		gss_create_empty_oid_set(&status, &oidset);
-+		gss_add_oid_set_member(&status, ctx->oid, &oidset);
-+
-+		if (gethostname(lname, MAXHOSTNAMELEN)) {
-+			gss_release_oid_set(&status, &oidset);
-+			return (-1);
-+		}
- 
--	if (gethostname(lname, MAXHOSTNAMELEN)) {
--		gss_release_oid_set(&status, &oidset);
--		return (-1);
--	}
-+		if (GSS_ERROR(ssh_gssapi_import_name(ctx, lname))) {
-+			gss_release_oid_set(&status, &oidset);
-+			return (ctx->major);
-+		}
-+
-+		if ((ctx->major = gss_acquire_cred(&ctx->minor,
-+		    ctx->name, 0, oidset, GSS_C_ACCEPT, &ctx->creds, 
-+		    NULL, NULL)))
-+			ssh_gssapi_error(ctx);
- 
--	if (GSS_ERROR(ssh_gssapi_import_name(ctx, lname))) {
- 		gss_release_oid_set(&status, &oidset);
- 		return (ctx->major);
-+	} else {
-+		ctx->name = GSS_C_NO_NAME;
-+		ctx->creds = GSS_C_NO_CREDENTIAL;
- 	}
--
--	if ((ctx->major = gss_acquire_cred(&ctx->minor,
--	    ctx->name, 0, oidset, GSS_C_ACCEPT, &ctx->creds, NULL, NULL)))
--		ssh_gssapi_error(ctx);
--
--	gss_release_oid_set(&status, &oidset);
--	return (ctx->major);
-+	return GSS_S_COMPLETE;
- }
- 
- /* Privileged */
-@@ -113,6 +124,28 @@
- }
- 
- /* Unprivileged */
-+char *
-+ssh_gssapi_server_mechanisms() {
-+	gss_OID_set	supported;
-+
-+	ssh_gssapi_supported_oids(&supported);
-+	return (ssh_gssapi_kex_mechs(supported, &ssh_gssapi_server_check_mech,
-+	    NULL));
-+}
-+
-+/* Unprivileged */
-+int
-+ssh_gssapi_server_check_mech(Gssctxt **dum, gss_OID oid, const char *data) {
-+	Gssctxt *ctx = NULL;
-+	int res;
-+ 
-+	res = !GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctx, oid)));
-+	ssh_gssapi_delete_ctx(&ctx);
-+
-+	return (res);
-+}
-+
-+/* Unprivileged */
- void
- ssh_gssapi_supported_oids(gss_OID_set *oidset)
- {
-@@ -349,16 +382,6 @@
- 	else
- 		debug("ssh_gssapi_userok: Unknown GSSAPI mechanism");
- 	return (0);
--}
--
--/* Privileged */
--OM_uint32
--ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
--{
--	ctx->major = gss_verify_mic(&ctx->minor, ctx->context,
--	    gssbuf, gssmic, NULL);
--
--	return (ctx->major);
- }
- 
- #endif
-Index: kex.c
-===================================================================
-RCS file: /cvs/openssh/kex.c,v
-retrieving revision 1.86
-diff -u -r1.86 kex.c
---- kex.c	5 Jun 2007 08:30:18 -0000	1.86
-+++ kex.c	4 Apr 2008 12:52:29 -0000
-@@ -49,6 +49,10 @@
- #include "dispatch.h"
- #include "monitor.h"
- 
-+#ifdef GSSAPI
-+#include "ssh-gss.h"
-+#endif
-+
- #define KEX_COOKIE_LEN	16
- 
- #if OPENSSL_VERSION_NUMBER >= 0x00907000L
-@@ -326,6 +330,20 @@
- 	} else if (strcmp(k->name, KEX_DHGEX_SHA256) == 0) {
- 		k->kex_type = KEX_DH_GEX_SHA256;
- 		k->evp_md = evp_ssh_sha256();
-+#endif
-+#ifdef GSSAPI
-+	} else if (strncmp(k->name, KEX_GSS_GEX_SHA1_ID,
-+	    sizeof(KEX_GSS_GEX_SHA1_ID) - 1) == 0) {
-+		k->kex_type = KEX_GSS_GEX_SHA1;
-+		k->evp_md = EVP_sha1();
-+	} else if (strncmp(k->name, KEX_GSS_GRP1_SHA1_ID,
-+	    sizeof(KEX_GSS_GRP1_SHA1_ID) - 1) == 0) {
-+		k->kex_type = KEX_GSS_GRP1_SHA1;
-+		k->evp_md = EVP_sha1();
-+	} else if (strncmp(k->name, KEX_GSS_GRP14_SHA1_ID,
-+	    sizeof(KEX_GSS_GRP14_SHA1_ID) - 1) == 0) {
-+		k->kex_type = KEX_GSS_GRP14_SHA1;
-+		k->evp_md = EVP_sha1();
- #endif
- 	} else
- 		fatal("bad kex alg %s", k->name);
-Index: kex.h
-===================================================================
-RCS file: /cvs/openssh/kex.h,v
-retrieving revision 1.49
-diff -u -r1.49 kex.h
---- kex.h	11 Jun 2007 04:01:42 -0000	1.49
-+++ kex.h	4 Apr 2008 12:52:29 -0000
-@@ -64,6 +64,9 @@
- 	KEX_DH_GRP14_SHA1,
- 	KEX_DH_GEX_SHA1,
- 	KEX_DH_GEX_SHA256,
-+	KEX_GSS_GRP1_SHA1,
-+	KEX_GSS_GRP14_SHA1,
-+	KEX_GSS_GEX_SHA1,
- 	KEX_MAX
- };
- 
-@@ -119,6 +122,11 @@
- 	sig_atomic_t done;
- 	int	flags;
- 	const EVP_MD *evp_md;
-+#ifdef GSSAPI
-+	int	gss_deleg_creds;
-+	int	gss_trust_dns;
-+	char    *gss_host;
-+#endif
- 	char	*client_version_string;
- 	char	*server_version_string;
- 	int	(*verify_host_key)(Key *);
-@@ -140,6 +148,11 @@
- void	 kexdh_server(Kex *);
- void	 kexgex_client(Kex *);
- void	 kexgex_server(Kex *);
-+
-+#ifdef GSSAPI
-+void	kexgss_client(Kex *);
-+void	kexgss_server(Kex *);
-+#endif
- 
- void
- kex_dh_hash(char *, char *, char *, int, char *, int, u_char *, int,
-Index: kexgssc.c
-===================================================================
-RCS file: kexgssc.c
-diff -N kexgssc.c
---- /dev/null	1 Jan 1970 00:00:00 -0000
-+++ kexgssc.c	4 Apr 2008 12:52:29 -0000
-@@ -0,0 +1,319 @@
-+/*
-+ * Copyright (c) 2001-2006 Simon Wilkinson. All rights reserved.
-+ *
-+ * Redistribution and use in source and binary forms, with or without
-+ * modification, are permitted provided that the following conditions
-+ * are met:
-+ * 1. Redistributions of source code must retain the above copyright
-+ *    notice, this list of conditions and the following disclaimer.
-+ * 2. Redistributions in binary form must reproduce the above copyright
-+ *    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.
-+ */
-+
-+#include "includes.h"
-+
-+#ifdef GSSAPI
-+
-+#include "includes.h"
-+
-+#include <openssl/crypto.h>
-+#include <openssl/bn.h>
-+
-+#include <string.h>
-+
-+#include "xmalloc.h"
-+#include "buffer.h"
-+#include "ssh2.h"
-+#include "key.h"
-+#include "cipher.h"
-+#include "kex.h"
-+#include "log.h"
-+#include "packet.h"
-+#include "dh.h"
-+
-+#include "ssh-gss.h"
-+
-+void
-+kexgss_client(Kex *kex) {
-+	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
-+	gss_buffer_desc recv_tok, gssbuf, msg_tok, *token_ptr;
-+	Gssctxt *ctxt;
-+	OM_uint32 maj_status, min_status, ret_flags;
-+	u_int klen, kout, slen = 0, hashlen, strlen;
-+	DH *dh; 
-+	BIGNUM *dh_server_pub = NULL;
-+	BIGNUM *shared_secret = NULL;
-+	BIGNUM *p = NULL;
-+	BIGNUM *g = NULL;	
-+	u_char *kbuf, *hash;
-+	u_char *serverhostkey = NULL;
-+	char *msg;
-+	char *lang;
-+	int type = 0;
-+	int first = 1;
-+	int nbits = 0, min = DH_GRP_MIN, max = DH_GRP_MAX;
-+
-+	/* Initialise our GSSAPI world */	
-+	ssh_gssapi_build_ctx(&ctxt);
-+	if (ssh_gssapi_id_kex(ctxt, kex->name, kex->kex_type) 
-+	    == GSS_C_NO_OID)
-+		fatal("Couldn't identify host exchange");
-+
-+	if (ssh_gssapi_import_name(ctxt, kex->gss_host))
-+		fatal("Couldn't import hostname");
-+	
-+	switch (kex->kex_type) {
-+	case KEX_GSS_GRP1_SHA1:
-+		dh = dh_new_group1();
-+		break;
-+	case KEX_GSS_GRP14_SHA1:
-+		dh = dh_new_group14();
-+		break;
-+	case KEX_GSS_GEX_SHA1:
-+		debug("Doing group exchange\n");
-+		nbits = dh_estimate(kex->we_need * 8);
-+		packet_start(SSH2_MSG_KEXGSS_GROUPREQ);
-+		packet_put_int(min);
-+		packet_put_int(nbits);
-+		packet_put_int(max);
-+
-+		packet_send();
-+
-+		packet_read_expect(SSH2_MSG_KEXGSS_GROUP);
-+
-+		if ((p = BN_new()) == NULL)
-+			fatal("BN_new() failed");
-+		packet_get_bignum2(p);
-+		if ((g = BN_new()) == NULL)
-+			fatal("BN_new() failed");
-+		packet_get_bignum2(g);
-+		packet_check_eom();
-+
-+		if (BN_num_bits(p) < min || BN_num_bits(p) > max)
-+			fatal("GSSGRP_GEX group out of range: %d !< %d !< %d",
-+			    min, BN_num_bits(p), max);
-+
-+		dh = dh_new_group(g, p);
-+		break;
-+	default:
-+		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
-+	}
-+	
-+	/* Step 1 - e is dh->pub_key */
-+	dh_gen_key(dh, kex->we_need * 8);
-+
-+	/* This is f, we initialise it now to make life easier */
-+	dh_server_pub = BN_new();
-+	if (dh_server_pub == NULL)
-+		fatal("dh_server_pub == NULL");
-+
-+	token_ptr = GSS_C_NO_BUFFER;
-+			 
-+	do {
-+		debug("Calling gss_init_sec_context");
-+		
-+		maj_status = ssh_gssapi_init_ctx(ctxt,
-+		    kex->gss_deleg_creds, token_ptr, &send_tok,
-+		    &ret_flags);
-+
-+		if (GSS_ERROR(maj_status)) {
-+			if (send_tok.length != 0) {
-+				packet_start(SSH2_MSG_KEXGSS_CONTINUE);
-+				packet_put_string(send_tok.value,
-+				    send_tok.length);
-+			}
-+			fatal("gss_init_context failed");
-+		}
-+
-+		/* If we've got an old receive buffer get rid of it */
-+		if (token_ptr != GSS_C_NO_BUFFER)
-+			xfree(recv_tok.value);
-+
-+		if (maj_status == GSS_S_COMPLETE) {
-+			/* If mutual state flag is not true, kex fails */
-+			if (!(ret_flags & GSS_C_MUTUAL_FLAG))
-+				fatal("Mutual authentication failed");
-+
-+			/* If integ avail flag is not true kex fails */
-+			if (!(ret_flags & GSS_C_INTEG_FLAG))
-+				fatal("Integrity check failed");
-+		}
-+
-+		/* 
-+		 * If we have data to send, then the last message that we
-+		 * received cannot have been a 'complete'. 
-+		 */
-+		if (send_tok.length != 0) {
-+			if (first) {
-+				packet_start(SSH2_MSG_KEXGSS_INIT);
-+				packet_put_string(send_tok.value,
-+				    send_tok.length);
-+				packet_put_bignum2(dh->pub_key);
-+				first = 0;
-+			} else {
-+				packet_start(SSH2_MSG_KEXGSS_CONTINUE);
-+				packet_put_string(send_tok.value,
-+				    send_tok.length);
-+			}
-+			packet_send();
-+			gss_release_buffer(&min_status, &send_tok);
-+
-+			/* If we've sent them data, they should reply */
-+			do {	
-+				type = packet_read();
-+				if (type == SSH2_MSG_KEXGSS_HOSTKEY) {
-+					debug("Received KEXGSS_HOSTKEY");
-+					if (serverhostkey)
-+						fatal("Server host key received more than once");
-+					serverhostkey = 
-+					    packet_get_string(&slen);
-+				}
-+			} while (type == SSH2_MSG_KEXGSS_HOSTKEY);
-+
-+			switch (type) {
-+			case SSH2_MSG_KEXGSS_CONTINUE:
-+				debug("Received GSSAPI_CONTINUE");
-+				if (maj_status == GSS_S_COMPLETE) 
-+					fatal("GSSAPI Continue received from server when complete");
-+				recv_tok.value = packet_get_string(&strlen);
-+				recv_tok.length = strlen; 
-+				break;
-+			case SSH2_MSG_KEXGSS_COMPLETE:
-+				debug("Received GSSAPI_COMPLETE");
-+				packet_get_bignum2(dh_server_pub);
-+				msg_tok.value =  packet_get_string(&strlen);
-+				msg_tok.length = strlen; 
-+
-+				/* Is there a token included? */
-+				if (packet_get_char()) {
-+					recv_tok.value=
-+					    packet_get_string(&strlen);
-+					recv_tok.length = strlen;
-+					/* If we're already complete - protocol error */
-+					if (maj_status == GSS_S_COMPLETE)
-+						packet_disconnect("Protocol error: received token when complete");
-+					} else {
-+						/* No token included */
-+						if (maj_status != GSS_S_COMPLETE)
-+							packet_disconnect("Protocol error: did not receive final token");
-+				}
-+				break;
-+			case SSH2_MSG_KEXGSS_ERROR:
-+				debug("Received Error");
-+				maj_status = packet_get_int();
-+				min_status = packet_get_int();
-+				msg = packet_get_string(NULL);
-+				lang = packet_get_string(NULL);
-+				fatal("GSSAPI Error: \n%.400s",msg);
-+			default:
-+				packet_disconnect("Protocol error: didn't expect packet type %d",
-+		    		type);
-+			}
-+			token_ptr = &recv_tok;
-+		} else {
-+			/* No data, and not complete */
-+			if (maj_status != GSS_S_COMPLETE)
-+				fatal("Not complete, and no token output");
-+		}
-+	} while (maj_status & GSS_S_CONTINUE_NEEDED);
-+
-+	/* 
-+	 * We _must_ have received a COMPLETE message in reply from the 
-+	 * server, which will have set dh_server_pub and msg_tok 
-+	 */
-+
-+	if (type != SSH2_MSG_KEXGSS_COMPLETE)
-+		fatal("Didn't receive a SSH2_MSG_KEXGSS_COMPLETE when I expected it");
-+
-+	/* Check f in range [1, p-1] */
-+	if (!dh_pub_is_valid(dh, dh_server_pub))
-+		packet_disconnect("bad server public DH value");
-+
-+	/* compute K=f^x mod p */
-+	klen = DH_size(dh);
-+	kbuf = xmalloc(klen);
-+	kout = DH_compute_key(kbuf, dh_server_pub, dh);
-+
-+	shared_secret = BN_new();
-+	BN_bin2bn(kbuf,kout, shared_secret);
-+	memset(kbuf, 0, klen);
-+	xfree(kbuf);
-+
-+	switch (kex->kex_type) {
-+	case KEX_GSS_GRP1_SHA1:
-+	case KEX_GSS_GRP14_SHA1:
-+		kex_dh_hash( kex->client_version_string, 
-+		    kex->server_version_string,
-+		    buffer_ptr(&kex->my), buffer_len(&kex->my),
-+		    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
-+		    serverhostkey, slen, /* server host key */
-+		    dh->pub_key,	/* e */
-+		    dh_server_pub,	/* f */
-+		    shared_secret,	/* K */
-+		    &hash, &hashlen
-+		);
-+		break;
-+	case KEX_GSS_GEX_SHA1:
-+		kexgex_hash(
-+		    kex->evp_md,
-+		    kex->client_version_string,
-+		    kex->server_version_string,
-+		    buffer_ptr(&kex->my), buffer_len(&kex->my),
-+		    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
-+		    serverhostkey, slen,
-+ 		    min, nbits, max,
-+		    dh->p, dh->g,
-+		    dh->pub_key,
-+		    dh_server_pub,
-+		    shared_secret,
-+		    &hash, &hashlen
-+		);
-+		break;
-+	default:
-+		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
-+	}
-+
-+	gssbuf.value = hash;
-+	gssbuf.length = hashlen;
-+
-+	/* Verify that the hash matches the MIC we just got. */
-+	if (GSS_ERROR(ssh_gssapi_checkmic(ctxt, &gssbuf, &msg_tok)))
-+		packet_disconnect("Hash's MIC didn't verify");
-+
-+	xfree(msg_tok.value);
-+
-+	DH_free(dh);
-+	if (serverhostkey)
-+		xfree(serverhostkey);
-+	BN_clear_free(dh_server_pub);
-+
-+	/* save session id */
-+	if (kex->session_id == NULL) {
-+		kex->session_id_len = hashlen;
-+		kex->session_id = xmalloc(kex->session_id_len);
-+		memcpy(kex->session_id, hash, kex->session_id_len);
-+	}
-+
-+	if (gss_kex_context == NULL)
-+		gss_kex_context = ctxt;
-+	else
-+		ssh_gssapi_delete_ctx(&ctxt);
-+
-+	kex_derive_keys(kex, hash, hashlen, shared_secret);
-+	BN_clear_free(shared_secret);
-+	kex_finish(kex);
-+}
-+
-+#endif /* GSSAPI */
-Index: kexgsss.c
-===================================================================
-RCS file: kexgsss.c
-diff -N kexgsss.c
---- /dev/null	1 Jan 1970 00:00:00 -0000
-+++ kexgsss.c	4 Apr 2008 12:52:29 -0000
-@@ -0,0 +1,271 @@
-+/*
-+ * Copyright (c) 2001-2006 Simon Wilkinson. All rights reserved.
-+ *
-+ * Redistribution and use in source and binary forms, with or without
-+ * modification, are permitted provided that the following conditions
-+ * are met:
-+ * 1. Redistributions of source code must retain the above copyright
-+ *    notice, this list of conditions and the following disclaimer.
-+ * 2. Redistributions in binary form must reproduce the above copyright
-+ *    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.
-+ */
-+
-+#include "includes.h"
-+
-+#ifdef GSSAPI
-+
-+#include <string.h>
-+
-+#include <openssl/crypto.h>
-+#include <openssl/bn.h>
-+
-+#include "xmalloc.h"
-+#include "buffer.h"
-+#include "ssh2.h"
-+#include "key.h"
-+#include "cipher.h"
-+#include "kex.h"
-+#include "log.h"
-+#include "packet.h"
-+#include "dh.h"
-+#include "ssh-gss.h"
-+#include "monitor_wrap.h"
-+
-+void
-+kexgss_server(Kex *kex)
-+{
-+	OM_uint32 maj_status, min_status;
-+	
-+	/* 
-+	 * Some GSSAPI implementations use the input value of ret_flags (an
-+ 	 * output variable) as a means of triggering mechanism specific 
-+ 	 * features. Initializing it to zero avoids inadvertently 
-+ 	 * activating this non-standard behaviour.
-+	 */
-+
-+	OM_uint32 ret_flags = 0;
-+	gss_buffer_desc gssbuf, recv_tok, msg_tok;
-+	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
-+	Gssctxt *ctxt = NULL;
-+	u_int slen, klen, kout, hashlen;
-+	u_char *kbuf, *hash;
-+	DH *dh;
-+	int min = -1, max = -1, nbits = -1;
-+	BIGNUM *shared_secret = NULL;
-+	BIGNUM *dh_client_pub = NULL;
-+	int type = 0;
-+	gss_OID oid;
-+
-+	/* Initialise GSSAPI */
-+
-+	/* If we're rekeying, privsep means that some of the private structures
-+	 * in the GSSAPI code are no longer available. This kludges them back
-+	 * into life
-+	 */
-+	if (!ssh_gssapi_oid_table_ok()) 
-+		ssh_gssapi_server_mechanisms();
-+
-+	debug2("%s: Identifying %s", __func__, kex->name);
-+	oid = ssh_gssapi_id_kex(NULL, kex->name, kex->kex_type);
-+	if (oid == GSS_C_NO_OID)
-+	   fatal("Unknown gssapi mechanism");
-+
-+	debug2("%s: Acquiring credentials", __func__);
-+
-+	if (GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctxt, oid))))
-+		fatal("Unable to acquire credentials for the server");
-+
-+	switch (kex->kex_type) {
-+	case KEX_GSS_GRP1_SHA1:
-+		dh = dh_new_group1();
-+		break;
-+	case KEX_GSS_GRP14_SHA1:
-+		dh = dh_new_group14();
-+		break;
-+	case KEX_GSS_GEX_SHA1:
-+		debug("Doing group exchange");
-+		packet_read_expect(SSH2_MSG_KEXGSS_GROUPREQ);
-+		min = packet_get_int();
-+		nbits = packet_get_int();
-+		max = packet_get_int();
-+		min = MAX(DH_GRP_MIN, min);
-+		max = MIN(DH_GRP_MAX, max);
-+		packet_check_eom();
-+		if (max < min || nbits < min || max < nbits)
-+			fatal("GSS_GEX, bad parameters: %d !< %d !< %d",
-+			    min, nbits, max);
-+		dh = PRIVSEP(choose_dh(min, nbits, max));
-+		if (dh == NULL)
-+			packet_disconnect("Protocol error: no matching group found");
-+
-+		packet_start(SSH2_MSG_KEXGSS_GROUP);
-+		packet_put_bignum2(dh->p);
-+		packet_put_bignum2(dh->g);
-+		packet_send();
-+
-+		packet_write_wait();
-+		break;
-+	default:
-+		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
-+	}
-+
-+	dh_gen_key(dh, kex->we_need * 8);
-+
-+	do {
-+		debug("Wait SSH2_MSG_GSSAPI_INIT");
-+		type = packet_read();
-+		switch(type) {
-+		case SSH2_MSG_KEXGSS_INIT:
-+			if (dh_client_pub != NULL) 
-+				fatal("Received KEXGSS_INIT after initialising");
-+			recv_tok.value = packet_get_string(&slen);
-+			recv_tok.length = slen; 
-+
-+			if ((dh_client_pub = BN_new()) == NULL)
-+				fatal("dh_client_pub == NULL");
-+
-+			packet_get_bignum2(dh_client_pub);
-+
-+			/* Send SSH_MSG_KEXGSS_HOSTKEY here, if we want */
-+			break;
-+		case SSH2_MSG_KEXGSS_CONTINUE:
-+			recv_tok.value = packet_get_string(&slen);
-+			recv_tok.length = slen; 
-+			break;
-+		default:
-+			packet_disconnect(
-+			    "Protocol error: didn't expect packet type %d",
-+			    type);
-+		}
-+
-+		maj_status = PRIVSEP(ssh_gssapi_accept_ctx(ctxt, &recv_tok, 
-+		    &send_tok, &ret_flags));
-+
-+		xfree(recv_tok.value);
-+
-+		if (maj_status != GSS_S_COMPLETE && send_tok.length == 0)
-+			fatal("Zero length token output when incomplete");
-+
-+		if (dh_client_pub == NULL)
-+			fatal("No client public key");
-+		
-+		if (maj_status & GSS_S_CONTINUE_NEEDED) {
-+			debug("Sending GSSAPI_CONTINUE");
-+			packet_start(SSH2_MSG_KEXGSS_CONTINUE);
-+			packet_put_string(send_tok.value, send_tok.length);
-+			packet_send();
-+			gss_release_buffer(&min_status, &send_tok);
-+		}
-+	} while (maj_status & GSS_S_CONTINUE_NEEDED);
-+
-+	if (GSS_ERROR(maj_status)) {
-+		if (send_tok.length > 0) {
-+			packet_start(SSH2_MSG_KEXGSS_CONTINUE);
-+			packet_put_string(send_tok.value, send_tok.length);
-+			packet_send();
-+		}
-+		fatal("accept_ctx died");
-+	}
-+
-+	if (!(ret_flags & GSS_C_MUTUAL_FLAG))
-+		fatal("Mutual Authentication flag wasn't set");
-+
-+	if (!(ret_flags & GSS_C_INTEG_FLAG))
-+		fatal("Integrity flag wasn't set");
-+	
-+	if (!dh_pub_is_valid(dh, dh_client_pub))
-+		packet_disconnect("bad client public DH value");
-+
-+	klen = DH_size(dh);
-+	kbuf = xmalloc(klen); 
-+	kout = DH_compute_key(kbuf, dh_client_pub, dh);
-+
-+	shared_secret = BN_new();
-+	BN_bin2bn(kbuf, kout, shared_secret);
-+	memset(kbuf, 0, klen);
-+	xfree(kbuf);
-+
-+	switch (kex->kex_type) {
-+	case KEX_GSS_GRP1_SHA1:
-+	case KEX_GSS_GRP14_SHA1:
-+		kex_dh_hash(
-+		    kex->client_version_string, kex->server_version_string,
-+		    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
-+		    buffer_ptr(&kex->my), buffer_len(&kex->my),
-+		    NULL, 0, /* Change this if we start sending host keys */
-+		    dh_client_pub, dh->pub_key, shared_secret,
-+		    &hash, &hashlen
-+		);
-+		break;
-+	case KEX_GSS_GEX_SHA1:
-+		kexgex_hash(
-+		    kex->evp_md,
-+		    kex->client_version_string, kex->server_version_string,
-+		    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
-+		    buffer_ptr(&kex->my), buffer_len(&kex->my),
-+		    NULL, 0,
-+		    min, nbits, max,
-+		    dh->p, dh->g,
-+		    dh_client_pub,
-+		    dh->pub_key,
-+		    shared_secret,
-+		    &hash, &hashlen
-+		);
-+		break;
-+	default:
-+		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
-+	}
-+
-+	BN_free(dh_client_pub);
-+
-+	if (kex->session_id == NULL) {
-+		kex->session_id_len = hashlen;
-+		kex->session_id = xmalloc(kex->session_id_len);
-+		memcpy(kex->session_id, hash, kex->session_id_len);
-+	}
-+
-+	gssbuf.value = hash;
-+	gssbuf.length = hashlen;
-+
-+	if (GSS_ERROR(PRIVSEP(ssh_gssapi_sign(ctxt,&gssbuf,&msg_tok))))
-+		fatal("Couldn't get MIC");
-+
-+	packet_start(SSH2_MSG_KEXGSS_COMPLETE);
-+	packet_put_bignum2(dh->pub_key);
-+	packet_put_string(msg_tok.value,msg_tok.length);
-+
-+	if (send_tok.length != 0) {
-+		packet_put_char(1); /* true */
-+		packet_put_string(send_tok.value, send_tok.length);
-+	} else {
-+		packet_put_char(0); /* false */
-+	}
-+	packet_send();
-+
-+	gss_release_buffer(&min_status, &send_tok);
-+	gss_release_buffer(&min_status, &msg_tok);
-+
-+	if (gss_kex_context == NULL)
-+		gss_kex_context = ctxt;
-+	else 
-+		ssh_gssapi_delete_ctx(&ctxt);
-+
-+	DH_free(dh);
-+
-+	kex_derive_keys(kex, hash, hashlen, shared_secret);
-+	BN_clear_free(shared_secret);
-+	kex_finish(kex);
-+}
-+#endif /* GSSAPI */
-Index: key.c
-===================================================================
-RCS file: /cvs/openssh/key.c,v
-retrieving revision 1.72
-diff -u -r1.72 key.c
---- key.c	28 Feb 2008 08:22:04 -0000	1.72
-+++ key.c	4 Apr 2008 12:52:29 -0000
-@@ -649,6 +649,8 @@
- 		return KEY_RSA;
- 	} else if (strcmp(name, "ssh-dss") == 0) {
- 		return KEY_DSA;
-+	} else if (strcmp(name, "null") == 0) {
-+		return KEY_NULL;
- 	}
- 	debug2("key_type_from_name: unknown key type '%s'", name);
- 	return KEY_UNSPEC;
-Index: key.h
-===================================================================
-RCS file: /cvs/openssh/key.h,v
-retrieving revision 1.28
-diff -u -r1.28 key.h
---- key.h	5 Aug 2006 02:39:40 -0000	1.28
-+++ key.h	4 Apr 2008 12:52:29 -0000
-@@ -34,6 +34,7 @@
- 	KEY_RSA1,
- 	KEY_RSA,
- 	KEY_DSA,
-+	KEY_NULL,
- 	KEY_UNSPEC
- };
- enum fp_type {
-Index: monitor.c
-===================================================================
-RCS file: /cvs/openssh/monitor.c,v
-retrieving revision 1.127
-diff -u -r1.127 monitor.c
---- monitor.c	11 Mar 2008 11:58:25 -0000	1.127
-+++ monitor.c	4 Apr 2008 12:52:29 -0000
-@@ -163,6 +163,7 @@
- int mm_answer_gss_accept_ctx(int, Buffer *);
- int mm_answer_gss_userok(int, Buffer *);
- int mm_answer_gss_checkmic(int, Buffer *);
-+int mm_answer_gss_sign(int, Buffer *);
- #endif
- 
- #ifdef SSH_AUDIT_EVENTS
-@@ -232,11 +233,17 @@
-     {MONITOR_REQ_GSSSTEP, MON_ISAUTH, mm_answer_gss_accept_ctx},
-     {MONITOR_REQ_GSSUSEROK, MON_AUTH, mm_answer_gss_userok},
-     {MONITOR_REQ_GSSCHECKMIC, MON_ISAUTH, mm_answer_gss_checkmic},
-+    {MONITOR_REQ_GSSSIGN, MON_ONCE, mm_answer_gss_sign},
- #endif
-     {0, 0, NULL}
- };
- 
- struct mon_table mon_dispatch_postauth20[] = {
-+#ifdef GSSAPI
-+    {MONITOR_REQ_GSSSETUP, 0, mm_answer_gss_setup_ctx},
-+    {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
-+    {MONITOR_REQ_GSSSIGN, 0, mm_answer_gss_sign},
-+#endif
-     {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
-     {MONITOR_REQ_SIGN, 0, mm_answer_sign},
-     {MONITOR_REQ_PTY, 0, mm_answer_pty},
-@@ -341,6 +348,10 @@
- 		/* Permit requests for moduli and signatures */
- 		monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
- 		monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
-+#ifdef GSSAPI
-+		/* and for the GSSAPI key exchange */
-+		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSETUP, 1);
-+#endif
- 	} else {
- 		mon_dispatch = mon_dispatch_proto15;
- 
-@@ -418,6 +429,10 @@
- 		monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
- 		monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
- 		monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
-+#ifdef GSSAPI
-+		/* and for the GSSAPI key exchange */
-+		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSETUP, 1);
-+#endif		
- 	} else {
- 		mon_dispatch = mon_dispatch_postauth15;
- 		monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
-@@ -1670,6 +1685,11 @@
- 	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
- 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
- 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
-+#ifdef GSSAPI
-+	kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
-+	kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
-+	kex->kex[KEX_GSS_GEX_SHA1] = kexgss_server;
-+#endif
- 	kex->server = 1;
- 	kex->hostkey_type = buffer_get_int(m);
- 	kex->kex_type = buffer_get_int(m);
-@@ -1911,6 +1931,7 @@
- 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
- 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
- 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
-+		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSIGN, 1);
- 	}
- 	return (0);
- }
-@@ -1961,4 +1982,42 @@
- 	/* Monitor loop will terminate if authenticated */
- 	return (authenticated);
- }
-+
-+int 
-+mm_answer_gss_sign(int socket, Buffer *m)
-+{
-+	gss_buffer_desc data;
-+	gss_buffer_desc hash = GSS_C_EMPTY_BUFFER;
-+	OM_uint32 major, minor;
-+	u_int len;
-+
-+	data.value = buffer_get_string(m, &len);
-+	data.length = len;
-+	if (data.length != 20) 
-+		fatal("%s: data length incorrect: %d", __func__, data.length);
-+
-+	/* Save the session ID on the first time around */
-+	if (session_id2_len == 0) {
-+		session_id2_len = data.length;
-+		session_id2 = xmalloc(session_id2_len);
-+		memcpy(session_id2, data.value, session_id2_len);
-+	}
-+	major = ssh_gssapi_sign(gsscontext, &data, &hash);
-+
-+	xfree(data.value);
-+
-+	buffer_clear(m);
-+	buffer_put_int(m, major);
-+	buffer_put_string(m, hash.value, hash.length);
-+
-+	mm_request_send(socket, MONITOR_ANS_GSSSIGN, m);
-+
-+	gss_release_buffer(&minor, &hash);
-+
-+	/* Turn on getpwnam permissions */
-+	monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
-+
-+	return (0);
-+}
-+
- #endif /* GSSAPI */
-Index: monitor.h
-===================================================================
-RCS file: /cvs/openssh/monitor.h,v
-retrieving revision 1.21
-diff -u -r1.21 monitor.h
---- monitor.h	26 Mar 2006 03:30:02 -0000	1.21
-+++ monitor.h	4 Apr 2008 12:52:29 -0000
-@@ -53,6 +53,7 @@
- 	MONITOR_REQ_GSSSTEP, MONITOR_ANS_GSSSTEP,
- 	MONITOR_REQ_GSSUSEROK, MONITOR_ANS_GSSUSEROK,
- 	MONITOR_REQ_GSSCHECKMIC, MONITOR_ANS_GSSCHECKMIC,
-+	MONITOR_REQ_GSSSIGN, MONITOR_ANS_GSSSIGN,
- 	MONITOR_REQ_PAM_START,
- 	MONITOR_REQ_PAM_ACCOUNT, MONITOR_ANS_PAM_ACCOUNT,
- 	MONITOR_REQ_PAM_INIT_CTX, MONITOR_ANS_PAM_INIT_CTX,
-Index: monitor_wrap.c
-===================================================================
-RCS file: /cvs/openssh/monitor_wrap.c,v
-retrieving revision 1.76
-diff -u -r1.76 monitor_wrap.c
---- monitor_wrap.c	2 Dec 2007 12:02:15 -0000	1.76
-+++ monitor_wrap.c	4 Apr 2008 12:52:29 -0000
-@@ -1238,4 +1238,27 @@
- 	debug3("%s: user %sauthenticated",__func__, authenticated ? "" : "not ");
- 	return (authenticated);
- }
-+
-+OM_uint32
-+mm_ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_desc *data, gss_buffer_desc *hash)
-+{
-+	Buffer m;
-+	OM_uint32 major;
-+	u_int len;
-+
-+	buffer_init(&m);
-+	buffer_put_string(&m, data->value, data->length);
-+
-+	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSSIGN, &m);
-+	mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSSIGN, &m);
-+
-+	major = buffer_get_int(&m);
-+	hash->value = buffer_get_string(&m, &len);
-+	hash->length = len;
-+
-+	buffer_free(&m);
-+
-+	return(major);
-+}
-+
- #endif /* GSSAPI */
-Index: monitor_wrap.h
-===================================================================
-RCS file: /cvs/openssh/monitor_wrap.h,v
-retrieving revision 1.27
-diff -u -r1.27 monitor_wrap.h
---- monitor_wrap.h	5 Aug 2006 02:39:40 -0000	1.27
-+++ monitor_wrap.h	4 Apr 2008 12:52:29 -0000
-@@ -59,6 +59,7 @@
-    gss_buffer_desc *, gss_buffer_desc *, OM_uint32 *);
- int mm_ssh_gssapi_userok(char *user);
- OM_uint32 mm_ssh_gssapi_checkmic(Gssctxt *, gss_buffer_t, gss_buffer_t);
-+OM_uint32 mm_ssh_gssapi_sign(Gssctxt *, gss_buffer_t, gss_buffer_t);
- #endif
- 
- #ifdef USE_PAM
-Index: readconf.c
-===================================================================
-RCS file: /cvs/openssh/readconf.c,v
-retrieving revision 1.142
-diff -u -r1.142 readconf.c
---- readconf.c	10 Feb 2008 11:25:52 -0000	1.142
-+++ readconf.c	4 Apr 2008 12:52:29 -0000
-@@ -127,6 +127,8 @@
- 	oClearAllForwardings, oNoHostAuthenticationForLocalhost,
- 	oEnableSSHKeysign, oRekeyLimit, oVerifyHostKeyDNS, oConnectTimeout,
- 	oAddressFamily, oGssAuthentication, oGssDelegateCreds,
-+	oGssKeyEx,
-+	oGssTrustDns,
- 	oServerAliveInterval, oServerAliveCountMax, oIdentitiesOnly,
- 	oSendEnv, oControlPath, oControlMaster, oHashKnownHosts,
- 	oTunnel, oTunnelDevice, oLocalCommand, oPermitLocalCommand,
-@@ -163,10 +165,14 @@
- 	{ "afstokenpassing", oUnsupported },
- #if defined(GSSAPI)
- 	{ "gssapiauthentication", oGssAuthentication },
-+	{ "gssapikeyexchange", oGssKeyEx },
- 	{ "gssapidelegatecredentials", oGssDelegateCreds },
-+	{ "gssapitrustdns", oGssTrustDns },
- #else
- 	{ "gssapiauthentication", oUnsupported },
-+	{ "gssapikeyexchange", oUnsupported },
- 	{ "gssapidelegatecredentials", oUnsupported },
-+	{ "gssapitrustdns", oUnsupported },
- #endif
- 	{ "fallbacktorsh", oDeprecated },
- 	{ "usersh", oDeprecated },
-@@ -442,10 +448,18 @@
- 		intptr = &options->gss_authentication;
- 		goto parse_flag;
- 
-+	case oGssKeyEx:
-+	    	intptr = &options->gss_keyex;
-+		goto parse_flag;
-+
- 	case oGssDelegateCreds:
- 		intptr = &options->gss_deleg_creds;
- 		goto parse_flag;
- 
-+	case oGssTrustDns:
-+		intptr = &options->gss_trust_dns;
-+		goto parse_flag;
-+
- 	case oBatchMode:
- 		intptr = &options->batch_mode;
- 		goto parse_flag;
-@@ -1010,7 +1024,9 @@
- 	options->pubkey_authentication = -1;
- 	options->challenge_response_authentication = -1;
- 	options->gss_authentication = -1;
-+	options->gss_keyex = -1;
- 	options->gss_deleg_creds = -1;
-+	options->gss_trust_dns = -1;
- 	options->password_authentication = -1;
- 	options->kbd_interactive_authentication = -1;
- 	options->kbd_interactive_devices = NULL;
-@@ -1099,8 +1115,12 @@
- 		options->challenge_response_authentication = 1;
- 	if (options->gss_authentication == -1)
- 		options->gss_authentication = 0;
-+	if (options->gss_keyex == -1)
-+		options->gss_keyex = 0;
- 	if (options->gss_deleg_creds == -1)
- 		options->gss_deleg_creds = 0;
-+	if (options->gss_trust_dns == -1)
-+		options->gss_trust_dns = 0;
- 	if (options->password_authentication == -1)
- 		options->password_authentication = 1;
- 	if (options->kbd_interactive_authentication == -1)
-Index: readconf.h
-===================================================================
-RCS file: /cvs/openssh/readconf.h,v
-retrieving revision 1.64
-diff -u -r1.64 readconf.h
---- readconf.h	10 Feb 2008 11:25:52 -0000	1.64
-+++ readconf.h	4 Apr 2008 12:52:29 -0000
-@@ -44,7 +44,9 @@
- 	int     challenge_response_authentication;
- 					/* Try S/Key or TIS, authentication. */
- 	int     gss_authentication;	/* Try GSS authentication */
-+	int	gss_keyex;              /* Try GSS key exchange */
- 	int     gss_deleg_creds;	/* Delegate GSS credentials */
-+	int	gss_trust_dns;		/* Trust DNS for GSS canonicalization */
- 	int     password_authentication;	/* Try password
- 						 * authentication. */
- 	int     kbd_interactive_authentication; /* Try keyboard-interactive auth. */
-Index: servconf.c
-===================================================================
-RCS file: /cvs/openssh/servconf.c,v
-retrieving revision 1.168
-diff -u -r1.168 servconf.c
---- servconf.c	10 Feb 2008 11:48:55 -0000	1.168
-+++ servconf.c	4 Apr 2008 12:52:30 -0000
-@@ -90,7 +90,9 @@
- 	options->kerberos_ticket_cleanup = -1;
- 	options->kerberos_get_afs_token = -1;
- 	options->gss_authentication=-1;
-+	options->gss_keyex = -1;
- 	options->gss_cleanup_creds = -1;
-+	options->gss_strict_acceptor = -1;
- 	options->password_authentication = -1;
- 	options->kbd_interactive_authentication = -1;
- 	options->challenge_response_authentication = -1;
-@@ -205,8 +207,12 @@
- 		options->kerberos_get_afs_token = 0;
- 	if (options->gss_authentication == -1)
- 		options->gss_authentication = 0;
-+	if (options->gss_keyex == -1)
-+		options->gss_keyex = 0;
- 	if (options->gss_cleanup_creds == -1)
- 		options->gss_cleanup_creds = 1;
-+	if (options->gss_strict_acceptor == -1)
-+		options->gss_strict_acceptor = 1;
- 	if (options->password_authentication == -1)
- 		options->password_authentication = 1;
- 	if (options->kbd_interactive_authentication == -1)
-@@ -291,7 +297,9 @@
- 	sBanner, sUseDNS, sHostbasedAuthentication,
- 	sHostbasedUsesNameFromPacketOnly, sClientAliveInterval,
- 	sClientAliveCountMax, sAuthorizedKeysFile, sAuthorizedKeysFile2,
--	sGssAuthentication, sGssCleanupCreds, sAcceptEnv, sPermitTunnel,
-+	sGssAuthentication, sGssCleanupCreds, sGssStrictAcceptor,
-+	sGssKeyEx,
-+	sAcceptEnv, sPermitTunnel,
- 	sMatch, sPermitOpen, sForceCommand, sChrootDirectory,
- 	sUsePrivilegeSeparation,
- 	sDeprecated, sUnsupported
-@@ -352,9 +360,13 @@
- #ifdef GSSAPI
- 	{ "gssapiauthentication", sGssAuthentication, SSHCFG_ALL },
- 	{ "gssapicleanupcredentials", sGssCleanupCreds, SSHCFG_GLOBAL },
-+	{ "gssapistrictacceptorcheck", sGssStrictAcceptor, SSHCFG_GLOBAL },
-+	{ "gssapikeyexchange", sGssKeyEx, SSHCFG_GLOBAL },
- #else
- 	{ "gssapiauthentication", sUnsupported, SSHCFG_ALL },
- 	{ "gssapicleanupcredentials", sUnsupported, SSHCFG_GLOBAL },
-+	{ "gssapistrictacceptorcheck", sUnsupported, SSHCFG_GLOBAL },
-+	{ "gssapikeyexchange", sUnsupported, SSHCFG_GLOBAL },
- #endif
- 	{ "passwordauthentication", sPasswordAuthentication, SSHCFG_ALL },
- 	{ "kbdinteractiveauthentication", sKbdInteractiveAuthentication, SSHCFG_ALL },
-@@ -875,8 +887,16 @@
- 		intptr = &options->gss_authentication;
- 		goto parse_flag;
- 
-+	case sGssKeyEx:
-+		intptr = &options->gss_keyex;
-+		goto parse_flag;
-+
- 	case sGssCleanupCreds:
- 		intptr = &options->gss_cleanup_creds;
-+		goto parse_flag;
-+
-+	case sGssStrictAcceptor:
-+		intptr = &options->gss_strict_acceptor;
- 		goto parse_flag;
- 
- 	case sPasswordAuthentication:
-Index: servconf.h
-===================================================================
-RCS file: /cvs/openssh/servconf.h,v
-retrieving revision 1.74
-diff -u -r1.74 servconf.h
---- servconf.h	7 Mar 2008 07:31:24 -0000	1.74
-+++ servconf.h	4 Apr 2008 12:52:30 -0000
-@@ -90,7 +90,9 @@
- 	int     kerberos_get_afs_token;		/* If true, try to get AFS token if
- 						 * authenticated with Kerberos. */
- 	int     gss_authentication;	/* If true, permit GSSAPI authentication */
-+	int 	gss_keyex;		/* If true, permit GSSAPI key exchange */
- 	int     gss_cleanup_creds;	/* If true, destroy cred cache on logout */
-+	int 	gss_strict_acceptor;	/* If true, restrict the GSSAPI acceptor name */
- 	int     password_authentication;	/* If true, permit password
- 						 * authentication. */
- 	int     kbd_interactive_authentication;	/* If true, permit */
-Index: ssh-gss.h
-===================================================================
-RCS file: /cvs/openssh/ssh-gss.h,v
-retrieving revision 1.12
-diff -u -r1.12 ssh-gss.h
---- ssh-gss.h	12 Jun 2007 13:40:39 -0000	1.12
-+++ ssh-gss.h	4 Apr 2008 12:52:30 -0000
-@@ -60,6 +60,17 @@
- 
- #define SSH_GSS_OIDTYPE 0x06
- 
-+#define SSH2_MSG_KEXGSS_INIT                            30
-+#define SSH2_MSG_KEXGSS_CONTINUE                        31
-+#define SSH2_MSG_KEXGSS_COMPLETE                        32
-+#define SSH2_MSG_KEXGSS_HOSTKEY                         33
-+#define SSH2_MSG_KEXGSS_ERROR                           34
-+#define SSH2_MSG_KEXGSS_GROUPREQ			40
-+#define SSH2_MSG_KEXGSS_GROUP				41
-+#define KEX_GSS_GRP1_SHA1_ID				"gss-group1-sha1-"
-+#define KEX_GSS_GRP14_SHA1_ID				"gss-group14-sha1-"
-+#define KEX_GSS_GEX_SHA1_ID				"gss-gex-sha1-"
-+
- typedef struct {
- 	char *filename;
- 	char *envvar;
-@@ -97,6 +108,7 @@
- } Gssctxt;
- 
- extern ssh_gssapi_mech *supported_mechs[];
-+extern Gssctxt *gss_kex_context;
- 
- int  ssh_gssapi_check_oid(Gssctxt *, void *, size_t);
- void ssh_gssapi_set_oid_data(Gssctxt *, void *, size_t);
-@@ -119,6 +131,11 @@
- int ssh_gssapi_check_mechanism(Gssctxt **, gss_OID, const char *);
- 
- /* In the server */
-+typedef int ssh_gssapi_check_fn(Gssctxt **, gss_OID, const char *);
-+char *ssh_gssapi_client_mechanisms(const char *host);
-+char *ssh_gssapi_kex_mechs(gss_OID_set, ssh_gssapi_check_fn *, const char *);
-+gss_OID ssh_gssapi_id_kex(Gssctxt *, char *, int);
-+int ssh_gssapi_server_check_mech(Gssctxt **,gss_OID, const char *);
- OM_uint32 ssh_gssapi_server_ctx(Gssctxt **, gss_OID);
- int ssh_gssapi_userok(char *name);
- OM_uint32 ssh_gssapi_checkmic(Gssctxt *, gss_buffer_t, gss_buffer_t);
-@@ -126,6 +143,8 @@
- void ssh_gssapi_cleanup_creds(void);
- void ssh_gssapi_storecreds(void);
- 
-+char *ssh_gssapi_server_mechanisms(void);
-+int ssh_gssapi_oid_table_ok();
- #endif /* GSSAPI */
- 
- #endif /* _SSH_GSS_H */
-Index: ssh_config
-===================================================================
-RCS file: /cvs/openssh/ssh_config,v
-retrieving revision 1.25
-diff -u -r1.25 ssh_config
---- ssh_config	11 Jun 2007 04:04:42 -0000	1.25
-+++ ssh_config	4 Apr 2008 12:52:30 -0000
-@@ -26,6 +26,8 @@
- #   HostbasedAuthentication no
- #   GSSAPIAuthentication no
- #   GSSAPIDelegateCredentials no
-+#   GSSAPIKeyExchange no
-+#   GSSAPITrustDNS no
- #   BatchMode no
- #   CheckHostIP yes
- #   AddressFamily any
-Index: ssh_config.5
-===================================================================
-RCS file: /cvs/openssh/ssh_config.5,v
-retrieving revision 1.105
-diff -u -r1.105 ssh_config.5
---- ssh_config.5	2 Dec 2007 12:09:30 -0000	1.105
-+++ ssh_config.5	4 Apr 2008 12:52:30 -0000
-@@ -477,11 +477,28 @@
- The default is
- .Dq no .
- Note that this option applies to protocol version 2 only.
-+.It Cm GSSAPIKeyExchange
-+Specifies whether key exchange based on GSSAPI may be used. When using
-+GSSAPI key exchange the server need not have a host key.
-+The default is
-+.Dq no .
-+Note that this option applies to protocol version 2 only.
- .It Cm GSSAPIDelegateCredentials
- Forward (delegate) credentials to the server.
- The default is
- .Dq no .
- Note that this option applies to protocol version 2 only.
-+.It Cm GSSAPITrustDns
-+Set to 
-+.Dq yes 
-+to indicate that the DNS is trusted to securely canonicalize
-+the name of the host being connected to. If 
-+.Dq no , 
-+the hostname entered on the
-+command line will be passed untouched to the GSSAPI library.
-+The default is
-+.Dq no .
-+This option only applies to protocol version 2 connections using GSSAPI.
- .It Cm HashKnownHosts
- Indicates that
- .Xr ssh 1
-Index: sshconnect2.c
-===================================================================
-RCS file: /cvs/openssh/sshconnect2.c,v
-retrieving revision 1.156
-diff -u -r1.156 sshconnect2.c
---- sshconnect2.c	10 Feb 2008 11:25:53 -0000	1.156
-+++ sshconnect2.c	4 Apr 2008 12:52:30 -0000
-@@ -99,9 +99,34 @@
- {
- 	Kex *kex;
- 
-+#ifdef GSSAPI
-+	char *orig = NULL, *gss = NULL;
-+	char *gss_host = NULL;
-+#endif
-+
- 	xxx_host = host;
- 	xxx_hostaddr = hostaddr;
- 
-+#ifdef GSSAPI
-+	if (options.gss_keyex) {
-+		/* Add the GSSAPI mechanisms currently supported on this 
-+		 * client to the key exchange algorithm proposal */
-+		orig = myproposal[PROPOSAL_KEX_ALGS];
-+
-+		if (options.gss_trust_dns)
-+			gss_host = (char *)get_canonical_hostname(1);
-+		else
-+			gss_host = host;
-+
-+		gss = ssh_gssapi_client_mechanisms(gss_host);
-+		if (gss) {
-+			debug("Offering GSSAPI proposal: %s", gss);
-+			xasprintf(&myproposal[PROPOSAL_KEX_ALGS],
-+			    "%s,%s", gss, orig);
-+		}
-+	}
-+#endif
-+
- 	if (options.ciphers == (char *)-1) {
- 		logit("No valid ciphers for protocol version 2 given, using defaults.");
- 		options.ciphers = NULL;
-@@ -129,6 +154,16 @@
- 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
- 		    options.hostkeyalgorithms;
- 
-+#ifdef GSSAPI
-+	/* If we've got GSSAPI algorithms, then we also support the
-+	 * 'null' hostkey, as a last resort */
-+	if (options.gss_keyex && gss) {
-+		orig = myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS];
-+		xasprintf(&myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS], 
-+		    "%s,null", orig);
-+	}
-+#endif
-+
- 	if (options.rekey_limit)
- 		packet_set_rekey_limit((u_int32_t)options.rekey_limit);
- 
-@@ -138,10 +173,21 @@
- 	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
- 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
- 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
-+#ifdef GSSAPI
-+	kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_client;
-+	kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_client;
-+	kex->kex[KEX_GSS_GEX_SHA1] = kexgss_client;
-+#endif
- 	kex->client_version_string=client_version_string;
- 	kex->server_version_string=server_version_string;
- 	kex->verify_host_key=&verify_host_key_callback;
- 
-+#ifdef GSSAPI
-+	kex->gss_deleg_creds = options.gss_deleg_creds;
-+	kex->gss_trust_dns = options.gss_trust_dns;
-+	kex->gss_host = gss_host;
-+#endif
-+
- 	xxx_kex = kex;
- 
- 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
-@@ -224,6 +270,7 @@
- void	input_gssapi_hash(int type, u_int32_t, void *);
- void	input_gssapi_error(int, u_int32_t, void *);
- void	input_gssapi_errtok(int, u_int32_t, void *);
-+int	userauth_gsskeyex(Authctxt *authctxt);
- #endif
- 
- void	userauth(Authctxt *, char *);
-@@ -239,6 +286,10 @@
- 
- Authmethod authmethods[] = {
- #ifdef GSSAPI
-+	{"gssapi-keyex",
-+		userauth_gsskeyex,
-+		&options.gss_authentication,
-+		NULL},
- 	{"gssapi-with-mic",
- 		userauth_gssapi,
- 		&options.gss_authentication,
-@@ -501,6 +552,12 @@
- 	static u_int mech = 0;
- 	OM_uint32 min;
- 	int ok = 0;
-+	char *gss_host = NULL;
-+
-+	if (options.gss_trust_dns)
-+		gss_host = (char *)get_canonical_hostname(1);
-+	else
-+		gss_host = (char *)authctxt->host;
- 
- 	/* Try one GSSAPI method at a time, rather than sending them all at
- 	 * once. */
-@@ -513,7 +570,7 @@
- 		/* My DER encoding requires length<128 */
- 		if (gss_supported->elements[mech].length < 128 &&
- 		    ssh_gssapi_check_mechanism(&gssctxt, 
--		    &gss_supported->elements[mech], authctxt->host)) {
-+		    &gss_supported->elements[mech], gss_host)) {
- 			ok = 1; /* Mechanism works */
- 		} else {
- 			mech++;
-@@ -609,8 +666,8 @@
- {
- 	Authctxt *authctxt = ctxt;
- 	Gssctxt *gssctxt;
--	int oidlen;
--	char *oidv;
-+	u_int oidlen;
-+	u_char *oidv;
- 
- 	if (authctxt == NULL)
- 		fatal("input_gssapi_response: no authentication context");
-@@ -717,6 +774,48 @@
- 	xfree(msg);
- 	xfree(lang);
- }
-+
-+int
-+userauth_gsskeyex(Authctxt *authctxt)
-+{
-+	Buffer b;
-+	gss_buffer_desc gssbuf;
-+	gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
-+	OM_uint32 ms;
-+
-+	static int attempt = 0;
-+	if (attempt++ >= 1)
-+		return (0);
-+
-+	if (gss_kex_context == NULL) {
-+		debug("No valid Key exchange context"); 
-+		return (0);
-+	}
-+
-+	ssh_gssapi_buildmic(&b, authctxt->server_user, authctxt->service,
-+	    "gssapi-keyex");
-+
-+	gssbuf.value = buffer_ptr(&b);
-+	gssbuf.length = buffer_len(&b);
-+
-+	if (GSS_ERROR(ssh_gssapi_sign(gss_kex_context, &gssbuf, &mic))) {
-+		buffer_free(&b);
-+		return (0);
-+	}
-+
-+	packet_start(SSH2_MSG_USERAUTH_REQUEST);
-+	packet_put_cstring(authctxt->server_user);
-+	packet_put_cstring(authctxt->service);
-+	packet_put_cstring(authctxt->method->name);
-+	packet_put_string(mic.value, mic.length);
-+	packet_send();
-+
-+	buffer_free(&b);
-+	gss_release_buffer(&ms, &mic);
-+
-+	return (1);
-+}
-+
- #endif /* GSSAPI */
- 
- int
-Index: sshd.c
-===================================================================
-RCS file: /cvs/openssh/sshd.c,v
-retrieving revision 1.372
-diff -u -r1.372 sshd.c
---- sshd.c	11 Mar 2008 11:58:25 -0000	1.372
-+++ sshd.c	4 Apr 2008 12:52:30 -0000
-@@ -119,6 +119,10 @@
- #include "monitor_fdpass.h"
- #include "version.h"
- 
-+#ifdef USE_SECURITY_SESSION_API
-+#include <Security/AuthSession.h>
-+#endif
-+
- #ifdef LIBWRAP
- #include <tcpd.h>
- #include <syslog.h>
-@@ -1501,10 +1505,13 @@
- 		logit("Disabling protocol version 1. Could not load host key");
- 		options.protocol &= ~SSH_PROTO_1;
- 	}
-+#ifndef GSSAPI
-+	/* The GSSAPI key exchange can run without a host key */
- 	if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
- 		logit("Disabling protocol version 2. Could not load host key");
- 		options.protocol &= ~SSH_PROTO_2;
- 	}
-+#endif
- 	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
- 		logit("sshd: no hostkeys available -- exiting.");
- 		exit(1);
-@@ -1777,6 +1784,60 @@
- 	/* Log the connection. */
- 	verbose("Connection from %.500s port %d", remote_ip, remote_port);
- 
-+#ifdef USE_SECURITY_SESSION_API
-+	/*
-+	 * Create a new security session for use by the new user login if
-+	 * the current session is the root session or we are not launched
-+	 * by inetd (eg: debugging mode or server mode).  We do not
-+	 * necessarily need to create a session if we are launched from
-+	 * inetd because Panther xinetd will create a session for us.
-+	 *
-+	 * The only case where this logic will fail is if there is an
-+	 * inetd running in a non-root session which is not creating
-+	 * new sessions for us.  Then all the users will end up in the
-+	 * same session (bad).
-+	 *
-+	 * When the client exits, the session will be destroyed for us
-+	 * automatically.
-+	 *
-+	 * We must create the session before any credentials are stored
-+	 * (including AFS pags, which happens a few lines below).
-+	 */
-+	{
-+		OSStatus err = 0;
-+		SecuritySessionId sid = 0;
-+		SessionAttributeBits sattrs = 0;
-+
-+		err = SessionGetInfo(callerSecuritySession, &sid, &sattrs);
-+		if (err)
-+			error("SessionGetInfo() failed with error %.8X",
-+			    (unsigned) err);
-+		else
-+			debug("Current Session ID is %.8X / Session Attributes are %.8X",
-+			    (unsigned) sid, (unsigned) sattrs);
-+
-+		if (inetd_flag && !(sattrs & sessionIsRoot))
-+			debug("Running in inetd mode in a non-root session... "
-+			    "assuming inetd created the session for us.");
-+		else {
-+			debug("Creating new security session...");
-+			err = SessionCreate(0, sessionHasTTY | sessionIsRemote);
-+			if (err)
-+				error("SessionCreate() failed with error %.8X",
-+				    (unsigned) err);
-+
-+			err = SessionGetInfo(callerSecuritySession, &sid, 
-+			    &sattrs);
-+			if (err)
-+				error("SessionGetInfo() failed with error %.8X",
-+				    (unsigned) err);
-+			else
-+				debug("New Session ID is %.8X / Session Attributes are %.8X",
-+				    (unsigned) sid, (unsigned) sattrs);
-+		}
-+	}
-+#endif
-+
- 	/*
- 	 * We don't want to listen forever unless the other side
- 	 * successfully authenticates itself.  So we set up an alarm which is
-@@ -2153,12 +2214,59 @@
- 
- 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
- 
-+#ifdef GSSAPI
-+	{
-+	char *orig;
-+	char *gss = NULL;
-+	char *newstr = NULL;
-+	orig = myproposal[PROPOSAL_KEX_ALGS];
-+
-+	/* 
-+	 * If we don't have a host key, then there's no point advertising
-+	 * the other key exchange algorithms
-+	 */
-+
-+	if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]) == 0)
-+		orig = NULL;
-+
-+	if (options.gss_keyex)
-+		gss = ssh_gssapi_server_mechanisms();
-+	else
-+		gss = NULL;
-+
-+	if (gss && orig)
-+		xasprintf(&newstr, "%s,%s", gss, orig);
-+	else if (gss)
-+		newstr = gss;
-+	else if (orig)
-+		newstr = orig;
-+
-+	/* 
-+	 * If we've got GSSAPI mechanisms, then we've got the 'null' host
-+	 * key alg, but we can't tell people about it unless its the only
-+  	 * host key algorithm we support
-+	 */
-+	if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0)
-+		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = "null";
-+
-+	if (newstr)
-+		myproposal[PROPOSAL_KEX_ALGS] = newstr;
-+	else
-+		fatal("No supported key exchange algorithms");
-+	}
-+#endif
-+
- 	/* start key exchange */
- 	kex = kex_setup(myproposal);
- 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
- 	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
- 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
- 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
-+#ifdef GSSAPI
-+	kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
-+	kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
-+	kex->kex[KEX_GSS_GEX_SHA1] = kexgss_server;
-+#endif
- 	kex->server = 1;
- 	kex->client_version_string=client_version_string;
- 	kex->server_version_string=server_version_string;
-Index: sshd_config
-===================================================================
-RCS file: /cvs/openssh/sshd_config,v
-retrieving revision 1.79
-diff -u -r1.79 sshd_config
---- sshd_config	10 Feb 2008 11:40:12 -0000	1.79
-+++ sshd_config	4 Apr 2008 12:52:30 -0000
-@@ -72,6 +72,8 @@
- # GSSAPI options
- #GSSAPIAuthentication no
- #GSSAPICleanupCredentials yes
-+#GSSAPIStrictAcceptorCheck yes
-+#GSSAPIKeyExchange no
- 
- # Set this to 'yes' to enable PAM authentication, account processing, 
- # and session processing. If this is enabled, PAM authentication will 
-Index: sshd_config.5
-===================================================================
-RCS file: /cvs/openssh/sshd_config.5,v
-retrieving revision 1.90
-diff -u -r1.90 sshd_config.5
---- sshd_config.5	27 Mar 2008 00:02:02 -0000	1.90
-+++ sshd_config.5	4 Apr 2008 12:52:30 -0000
-@@ -365,12 +365,35 @@
- The default is
- .Dq no .
- Note that this option applies to protocol version 2 only.
-+.It Cm GSSAPIKeyExchange
-+Specifies whether key exchange based on GSSAPI is allowed. GSSAPI key exchange 
-+doesn't rely on ssh keys to verify host identity.
-+The default is
-+.Dq no .
-+Note that this option applies to protocol version 2 only.
- .It Cm GSSAPICleanupCredentials
- Specifies whether to automatically destroy the user's credentials cache
- on logout.
- The default is
- .Dq yes .
- Note that this option applies to protocol version 2 only.
-+.It Cm GSSAPIStrictAcceptorCheck
-+Determines whether to be strict about the identity of the GSSAPI acceptor 
-+a client authenticates against. If
-+.Dq yes
-+then the client must authenticate against the
-+.Pa host
-+service on the current hostname. If 
-+.Dq no
-+then the client may authenticate against any service key stored in the 
-+machine's default store. This facility is provided to assist with operation 
-+on multi homed machines. 
-+The default is
-+.Dq yes .
-+Note that this option applies only to protocol version 2 GSSAPI connections,
-+and setting it to 
-+.Dq no
-+may only work with recent Kerberos GSSAPI libraries.
- .It Cm HostbasedAuthentication
- Specifies whether rhosts or /etc/hosts.equiv authentication together
- with successful public key client host authentication is allowed

Deleted: trunk/dports/net/openssh/files/openssh-5.9p1-gsskex-all-20110920.patch
===================================================================
--- trunk/dports/net/openssh/files/openssh-5.9p1-gsskex-all-20110920.patch	2013-07-20 15:56:15 UTC (rev 108348)
+++ trunk/dports/net/openssh/files/openssh-5.9p1-gsskex-all-20110920.patch	2013-07-20 16:53:18 UTC (rev 108349)
@@ -1,3028 +0,0 @@
-From 29169b27afb10a3743bfd272c990503f6559637b Mon Sep 17 00:00:00 2001
-From: Lassi Tuura <lat at cern.ch>
-Date: Wed, 21 Sep 2011 19:35:20 +0200
-Subject: [PATCH 1/2] GSS key exchange patch.
-
----
- ChangeLog.gssapi |  113 ++++++++++++++++++
- Makefile.in      |    3 +-
- auth-krb5.c      |   17 +++-
- auth2-gss.c      |   48 ++++++++-
- auth2.c          |    2 +
- clientloop.c     |   13 ++
- configure.ac     |   24 ++++
- gss-genr.c       |  276 ++++++++++++++++++++++++++++++++++++++++++++-
- gss-serv-krb5.c  |   84 +++++++++++++-
- gss-serv.c       |  220 +++++++++++++++++++++++++++++++-----
- kex.c            |   18 +++
- kex.h            |   14 +++
- kexgssc.c        |  334 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
- kexgsss.c        |  288 ++++++++++++++++++++++++++++++++++++++++++++++
- key.c            |    4 +
- key.h            |    1 +
- monitor.c        |  108 +++++++++++++++++-
- monitor.h        |    2 +
- monitor_wrap.c   |   47 ++++++++-
- monitor_wrap.h   |    4 +-
- readconf.c       |   42 +++++++
- readconf.h       |    5 +
- servconf.c       |   38 ++++++-
- servconf.h       |    3 +
- ssh-gss.h        |   39 ++++++-
- ssh_config       |    2 +
- ssh_config.5     |   34 ++++++-
- sshconnect2.c    |  124 +++++++++++++++++++-
- sshd.c           |  110 ++++++++++++++++++
- sshd_config      |    2 +
- sshd_config.5    |   28 +++++
- 31 files changed, 1990 insertions(+), 57 deletions(-)
- create mode 100644 ChangeLog.gssapi
- create mode 100644 kexgssc.c
- create mode 100644 kexgsss.c
-
-diff --git a/ChangeLog.gssapi b/ChangeLog.gssapi
-new file mode 100644
-index 0000000..f117a33
---- /dev/null
-+++ b/ChangeLog.gssapi
-@@ -0,0 +1,113 @@
-+20110101
-+  - Finally update for OpenSSH 5.6p1
-+  - Add GSSAPIServerIdentity option from Jim Basney
-+ 
-+20100308
-+  - [ Makefile.in, key.c, key.h ]
-+    Updates for OpenSSH 5.4p1
-+  - [ servconf.c ]
-+    Include GSSAPI options in the sshd -T configuration dump, and flag
-+    some older configuration options as being unsupported. Thanks to Colin 
-+    Watson.
-+  -
-+
-+20100124
-+  - [ sshconnect2.c ]
-+    Adapt to deal with additional element in Authmethod structure. Thanks to
-+    Colin Watson
-+
-+20090615
-+  - [ gss-genr.c gss-serv.c kexgssc.c kexgsss.c monitor.c sshconnect2.c
-+      sshd.c ]
-+    Fix issues identified by Greg Hudson following a code review
-+	Check return value of gss_indicate_mechs
-+	Protect GSSAPI calls in monitor, so they can only be used if enabled
-+	Check return values of bignum functions in key exchange
-+	Use BN_clear_free to clear other side's DH value
-+	Make ssh_gssapi_id_kex more robust
-+	Only configure kex table pointers if GSSAPI is enabled
-+	Don't leak mechanism list, or gss mechanism list
-+	Cast data.length before printing
-+	If serverkey isn't provided, use an empty string, rather than NULL
-+
-+20090201
-+  - [ gss-genr.c gss-serv.c kex.h kexgssc.c readconf.c readconf.h ssh-gss.h
-+      ssh_config.5 sshconnet2.c ]
-+    Add support for the GSSAPIClientIdentity option, which allows the user
-+    to specify which GSSAPI identity to use to contact a given server
-+
-+20080404
-+  - [ gss-serv.c ]
-+    Add code to actually implement GSSAPIStrictAcceptCheck, which had somehow
-+    been omitted from a previous version of this patch. Reported by Borislav
-+    Stoichkov
-+
-+20070317
-+  - [ gss-serv-krb5.c ]
-+    Remove C99ism, where new_ccname was being declared in the middle of a 
-+    function
-+
-+20061220
-+  - [ servconf.c ]
-+    Make default for GSSAPIStrictAcceptorCheck be Yes, to match previous, and 
-+    documented, behaviour. Reported by Dan Watson.
-+
-+20060910
-+  - [ gss-genr.c kexgssc.c kexgsss.c kex.h monitor.c sshconnect2.c sshd.c
-+      ssh-gss.h ]
-+    add support for gss-group14-sha1 key exchange mechanisms
-+  - [ gss-serv.c servconf.c servconf.h sshd_config sshd_config.5 ]
-+    Add GSSAPIStrictAcceptorCheck option to allow the disabling of
-+    acceptor principal checking on multi-homed machines.
-+    <Bugzilla #928>
-+  - [ sshd_config ssh_config ]
-+    Add settings for GSSAPIKeyExchange and GSSAPITrustDNS to the sample
-+    configuration files
-+  - [ kexgss.c kegsss.c sshconnect2.c sshd.c ]
-+    Code cleanup. Replace strlen/xmalloc/snprintf sequences with xasprintf()
-+    Limit length of error messages displayed by client
-+
-+20060909
-+  - [ gss-genr.c gss-serv.c ]
-+    move ssh_gssapi_acquire_cred() and ssh_gssapi_server_ctx to be server
-+    only, where they belong 
-+    <Bugzilla #1225>
-+
-+20060829
-+  - [ gss-serv-krb5.c ]
-+    Fix CCAPI credentials cache name when creating KRB5CCNAME environment 
-+    variable
-+
-+20060828
-+  - [ gss-genr.c ]
-+    Avoid Heimdal context freeing problem
-+    <Fixed upstream 20060829>
-+
-+20060818
-+  - [ gss-genr.c ssh-gss.h sshconnect2.c ]
-+    Make sure that SPENGO is disabled 
-+    <Bugzilla #1218 - Fixed upstream 20060818>
-+
-+20060421
-+  - [ gssgenr.c, sshconnect2.c ]
-+    a few type changes (signed versus unsigned, int versus size_t) to
-+    fix compiler errors/warnings 
-+    (from jbasney AT ncsa.uiuc.edu)
-+  - [ kexgssc.c, sshconnect2.c ]
-+    fix uninitialized variable warnings
-+    (from jbasney AT ncsa.uiuc.edu)
-+  - [ gssgenr.c ]
-+    pass oid to gss_display_status (helpful when using GSSAPI mechglue)
-+    (from jbasney AT ncsa.uiuc.edu)
-+    <Bugzilla #1220 >
-+  - [ gss-serv-krb5.c ]
-+    #ifdef HAVE_GSSAPI_KRB5 should be #ifdef HAVE_GSSAPI_KRB5_H
-+    (from jbasney AT ncsa.uiuc.edu)
-+    <Fixed upstream 20060304>
-+  - [ readconf.c, readconf.h, ssh_config.5, sshconnect2.c 
-+    add client-side GssapiKeyExchange option
-+    (from jbasney AT ncsa.uiuc.edu)
-+  - [ sshconnect2.c ]
-+    add support for GssapiTrustDns option for gssapi-with-mic
-+    (from jbasney AT ncsa.uiuc.edu)
-+    <gssapi-with-mic support is Bugzilla #1008>
-diff --git a/Makefile.in b/Makefile.in
-index 3be3aa6..e479a44 100644
---- a/Makefile.in
-+++ b/Makefile.in
-@@ -70,6 +70,7 @@ LIBSSH_OBJS=acss.o authfd.o authfile.o bufaux.o bufbn.o buffer.o \
- 	atomicio.o key.o dispatch.o kex.o mac.o uidswap.o uuencode.o misc.o \
- 	monitor_fdpass.o rijndael.o ssh-dss.o ssh-ecdsa.o ssh-rsa.o dh.o \
- 	kexdh.o kexgex.o kexdhc.o kexgexc.o bufec.o kexecdh.o kexecdhc.o \
-+	kexgssc.o \
- 	msg.o progressmeter.o dns.o entropy.o gss-genr.o umac.o jpake.o \
- 	schnorr.o ssh-pkcs11.o
- 
-@@ -86,7 +87,7 @@ SSHDOBJS=sshd.o auth-rhosts.o auth-passwd.o auth-rsa.o auth-rh-rsa.o \
- 	auth2-none.o auth2-passwd.o auth2-pubkey.o auth2-jpake.o \
- 	monitor_mm.o monitor.o monitor_wrap.o kexdhs.o kexgexs.o kexecdhs.o \
- 	auth-krb5.o \
--	auth2-gss.o gss-serv.o gss-serv-krb5.o \
-+	auth2-gss.o gss-serv.o gss-serv-krb5.o kexgsss.o\
- 	loginrec.o auth-pam.o auth-shadow.o auth-sia.o md5crypt.o \
- 	sftp-server.o sftp-common.o \
- 	roaming_common.o roaming_serv.o \
---- a/auth-krb5.c	2012-04-25 16:52:15.000000000 -0700
-+++ b/auth-krb5.c	2012-09-16 22:34:03.000000000 -0700
-@@ -170,8 +170,13 @@
- 
- 	len = strlen(authctxt->krb5_ticket_file) + 6;
- 	authctxt->krb5_ccname = xmalloc(len);
-+#ifdef USE_CCAPI
-+	snprintf(authctxt->krb5_ccname, len, "API:%s",
-+	    authctxt->krb5_ticket_file);
-+#else
- 	snprintf(authctxt->krb5_ccname, len, "FILE:%s",
- 	    authctxt->krb5_ticket_file);
-+#endif
- 
- #ifdef USE_PAM
- 	if (options.use_pam)
-@@ -226,15 +231,22 @@
- #ifndef HEIMDAL
- krb5_error_code
- ssh_krb5_cc_gen(krb5_context ctx, krb5_ccache *ccache) {
--	int tmpfd, ret, oerrno;
-+	int ret, oerrno;
- 	char ccname[40];
- 	mode_t old_umask;
-+#ifdef USE_CCAPI
-+	char cctemplate[] = "API:krb5cc_%d";
-+#else
-+	char cctemplate[] = "FILE:/tmp/krb5cc_%d_XXXXXXXXXX";
-+	int tmpfd;
-+#endif
- 
- 	ret = snprintf(ccname, sizeof(ccname),
--	    "FILE:/tmp/krb5cc_%d_XXXXXXXXXX", geteuid());
-+	    cctemplate, geteuid());
- 	if (ret < 0 || (size_t)ret >= sizeof(ccname))
- 		return ENOMEM;
- 
-+#ifndef USE_CCAPI
- 	old_umask = umask(0177);
- 	tmpfd = mkstemp(ccname + strlen("FILE:"));
- 	oerrno = errno;
-@@ -251,6 +263,7 @@
- 		return oerrno;
- 	}
- 	close(tmpfd);
-+#endif
- 
- 	return (krb5_cc_resolve(ctx, ccname, ccache));
- }
-diff --git a/auth2-gss.c b/auth2-gss.c
-index 0d59b21..7dc87db 100644
---- a/auth2-gss.c
-+++ b/auth2-gss.c
-@@ -1,7 +1,7 @@
- /* $OpenBSD: auth2-gss.c,v 1.17 2011/03/10 02:52:57 djm Exp $ */
- 
- /*
-- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
-+ * Copyright (c) 2001-2007 Simon Wilkinson. All rights reserved.
-  *
-  * Redistribution and use in source and binary forms, with or without
-  * modification, are permitted provided that the following conditions
-@@ -52,6 +52,40 @@ static void input_gssapi_mic(int type, u_int32_t plen, void *ctxt);
- static void input_gssapi_exchange_complete(int type, u_int32_t plen, void *ctxt);
- static void input_gssapi_errtok(int, u_int32_t, void *);
- 
-+/* 
-+ * The 'gssapi_keyex' userauth mechanism.
-+ */
-+static int
-+userauth_gsskeyex(Authctxt *authctxt)
-+{
-+	int authenticated = 0;
-+	Buffer b;
-+	gss_buffer_desc mic, gssbuf;
-+	u_int len;
-+
-+	mic.value = packet_get_string(&len);
-+	mic.length = len;
-+
-+	packet_check_eom();
-+
-+	ssh_gssapi_buildmic(&b, authctxt->user, authctxt->service,
-+	    "gssapi-keyex");
-+
-+	gssbuf.value = buffer_ptr(&b);
-+	gssbuf.length = buffer_len(&b);
-+
-+	/* gss_kex_context is NULL with privsep, so we can't check it here */
-+	if (!GSS_ERROR(PRIVSEP(ssh_gssapi_checkmic(gss_kex_context, 
-+	    &gssbuf, &mic))))
-+		authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user,
-+		    authctxt->pw));
-+	
-+	buffer_free(&b);
-+	xfree(mic.value);
-+
-+	return (authenticated);
-+}
-+
- /*
-  * We only support those mechanisms that we know about (ie ones that we know
-  * how to check local user kuserok and the like)
-@@ -244,7 +278,8 @@ input_gssapi_exchange_complete(int type, u_int32_t plen, void *ctxt)
- 
- 	packet_check_eom();
- 
--	authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user));
-+	authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user,
-+	    authctxt->pw));
- 
- 	authctxt->postponed = 0;
- 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, NULL);
-@@ -279,7 +314,8 @@ input_gssapi_mic(int type, u_int32_t plen, void *ctxt)
- 	gssbuf.length = buffer_len(&b);
- 
- 	if (!GSS_ERROR(PRIVSEP(ssh_gssapi_checkmic(gssctxt, &gssbuf, &mic))))
--		authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user));
-+		authenticated = 
-+		    PRIVSEP(ssh_gssapi_userok(authctxt->user, authctxt->pw));
- 	else
- 		logit("GSSAPI MIC check failed");
- 
-@@ -294,6 +330,12 @@ input_gssapi_mic(int type, u_int32_t plen, void *ctxt)
- 	userauth_finish(authctxt, authenticated, "gssapi-with-mic");
- }
- 
-+Authmethod method_gsskeyex = {
-+	"gssapi-keyex",
-+	userauth_gsskeyex,
-+	&options.gss_authentication
-+};
-+
- Authmethod method_gssapi = {
- 	"gssapi-with-mic",
- 	userauth_gssapi,
-diff --git a/auth2.c b/auth2.c
-index c06c95f..f73ac18 100644
---- a/auth2.c
-+++ b/auth2.c
-@@ -69,6 +69,7 @@ extern Authmethod method_passwd;
- extern Authmethod method_kbdint;
- extern Authmethod method_hostbased;
- #ifdef GSSAPI
-+extern Authmethod method_gsskeyex;
- extern Authmethod method_gssapi;
- #endif
- #ifdef JPAKE
-@@ -79,6 +80,7 @@ Authmethod *authmethods[] = {
- 	&method_none,
- 	&method_pubkey,
- #ifdef GSSAPI
-+	&method_gsskeyex,
- 	&method_gssapi,
- #endif
- #ifdef JPAKE
-diff --git a/clientloop.c b/clientloop.c
-index c19b01f..17628ef 100644
---- a/clientloop.c
-+++ b/clientloop.c
-@@ -111,6 +111,10 @@
- #include "msg.h"
- #include "roaming.h"
- 
-+#ifdef GSSAPI
-+#include "ssh-gss.h"
-+#endif
-+
- /* import options */
- extern Options options;
- 
-@@ -1508,6 +1512,15 @@ client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
- 		/* Do channel operations unless rekeying in progress. */
- 		if (!rekeying) {
- 			channel_after_select(readset, writeset);
-+
-+#ifdef GSSAPI
-+			if (options.gss_renewal_rekey &&
-+			    ssh_gssapi_credentials_updated(GSS_C_NO_CONTEXT)) {
-+				debug("credentials updated - forcing rekey");
-+				need_rekeying = 1;
-+			}
-+#endif
-+
- 			if (need_rekeying || packet_need_rekeying()) {
- 				debug("need rekeying");
- 				xxx_kex->done = 0;
-diff --git a/configure.ac b/configure.ac
-index 7a91527..8cc7ce9 100644
---- a/configure.ac
-+++ b/configure.ac
-@@ -515,6 +515,30 @@ main() { if (NSVersionOfRunTimeLibrary("System") >= (60 << 16))
- 	    [Use tunnel device compatibility to OpenBSD])
- 	AC_DEFINE([SSH_TUN_PREPEND_AF], [1],
- 	    [Prepend the address family to IP tunnel traffic])
-+ 	AC_MSG_CHECKING(if we have the Security Authorization Session API)
-+ 	AC_TRY_COMPILE([#include <Security/AuthSession.h>],
-+ 		[SessionCreate(0, 0);],
-+ 		[ac_cv_use_security_session_api="yes"
-+ 		 AC_DEFINE(USE_SECURITY_SESSION_API, 1, 
-+ 			[platform has the Security Authorization Session API])
-+ 		 LIBS="$LIBS -framework Security"
-+ 		 AC_MSG_RESULT(yes)],
-+ 		[ac_cv_use_security_session_api="no"
-+ 		 AC_MSG_RESULT(no)])
-+ 	AC_MSG_CHECKING(if we have an in-memory credentials cache)
-+ 	AC_TRY_COMPILE(
-+ 		[#include <Kerberos/Kerberos.h>],
-+ 		[cc_context_t c;
-+ 		 (void) cc_initialize (&c, 0, NULL, NULL);],
-+ 		[AC_DEFINE(USE_CCAPI, 1, 
-+ 			[platform uses an in-memory credentials cache])
-+ 		 LIBS="$LIBS -framework Security"
-+ 		 AC_MSG_RESULT(yes)
-+ 		 if test "x$ac_cv_use_security_session_api" = "xno"; then
-+ 			AC_MSG_ERROR(*** Need a security framework to use the credentials cache API ***)
-+ 		fi],
-+ 		[AC_MSG_RESULT(no)]
-+ 	)
- 	m4_pattern_allow([AU_IPv])
- 	AC_CHECK_DECL([AU_IPv4], [], 
- 	    AC_DEFINE([AU_IPv4], [0], [System only supports IPv4 audit records])
-diff --git a/gss-genr.c b/gss-genr.c
-index 842f385..f9b39cf 100644
---- a/gss-genr.c
-+++ b/gss-genr.c
-@@ -1,7 +1,7 @@
- /* $OpenBSD: gss-genr.c,v 1.20 2009/06/22 05:39:28 dtucker Exp $ */
- 
- /*
-- * Copyright (c) 2001-2007 Simon Wilkinson. All rights reserved.
-+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
-  *
-  * Redistribution and use in source and binary forms, with or without
-  * modification, are permitted provided that the following conditions
-@@ -39,12 +39,167 @@
- #include "buffer.h"
- #include "log.h"
- #include "ssh2.h"
-+#include "cipher.h"
-+#include "key.h"
-+#include "kex.h"
-+#include <openssl/evp.h>
- 
- #include "ssh-gss.h"
- 
- extern u_char *session_id2;
- extern u_int session_id2_len;
- 
-+typedef struct {
-+	char *encoded;
-+	gss_OID oid;
-+} ssh_gss_kex_mapping;
-+
-+/*
-+ * XXX - It would be nice to find a more elegant way of handling the
-+ * XXX   passing of the key exchange context to the userauth routines
-+ */
-+
-+Gssctxt *gss_kex_context = NULL;
-+
-+static ssh_gss_kex_mapping *gss_enc2oid = NULL;
-+
-+int 
-+ssh_gssapi_oid_table_ok() {
-+	return (gss_enc2oid != NULL);
-+}
-+
-+/*
-+ * Return a list of the gss-group1-sha1 mechanisms supported by this program
-+ *
-+ * We test mechanisms to ensure that we can use them, to avoid starting
-+ * a key exchange with a bad mechanism
-+ */
-+
-+char *
-+ssh_gssapi_client_mechanisms(const char *host, const char *client) {
-+	gss_OID_set gss_supported;
-+	OM_uint32 min_status;
-+
-+	if (GSS_ERROR(gss_indicate_mechs(&min_status, &gss_supported)))
-+		return NULL;
-+
-+	return(ssh_gssapi_kex_mechs(gss_supported, ssh_gssapi_check_mechanism,
-+	    host, client));
-+}
-+
-+char *
-+ssh_gssapi_kex_mechs(gss_OID_set gss_supported, ssh_gssapi_check_fn *check,
-+    const char *host, const char *client) {
-+	Buffer buf;
-+	size_t i;
-+	int oidpos, enclen;
-+	char *mechs, *encoded;
-+	u_char digest[EVP_MAX_MD_SIZE];
-+	char deroid[2];
-+	const EVP_MD *evp_md = EVP_md5();
-+	EVP_MD_CTX md;
-+
-+	if (gss_enc2oid != NULL) {
-+		for (i = 0; gss_enc2oid[i].encoded != NULL; i++)
-+			xfree(gss_enc2oid[i].encoded);
-+		xfree(gss_enc2oid);
-+	}
-+
-+	gss_enc2oid = xmalloc(sizeof(ssh_gss_kex_mapping) *
-+	    (gss_supported->count + 1));
-+
-+	buffer_init(&buf);
-+
-+	oidpos = 0;
-+	for (i = 0; i < gss_supported->count; i++) {
-+		if (gss_supported->elements[i].length < 128 &&
-+		    (*check)(NULL, &(gss_supported->elements[i]), host, client)) {
-+
-+			deroid[0] = SSH_GSS_OIDTYPE;
-+			deroid[1] = gss_supported->elements[i].length;
-+
-+			EVP_DigestInit(&md, evp_md);
-+			EVP_DigestUpdate(&md, deroid, 2);
-+			EVP_DigestUpdate(&md,
-+			    gss_supported->elements[i].elements,
-+			    gss_supported->elements[i].length);
-+			EVP_DigestFinal(&md, digest, NULL);
-+
-+			encoded = xmalloc(EVP_MD_size(evp_md) * 2);
-+			enclen = __b64_ntop(digest, EVP_MD_size(evp_md),
-+			    encoded, EVP_MD_size(evp_md) * 2);
-+
-+			if (oidpos != 0)
-+				buffer_put_char(&buf, ',');
-+
-+			buffer_append(&buf, KEX_GSS_GEX_SHA1_ID,
-+			    sizeof(KEX_GSS_GEX_SHA1_ID) - 1);
-+			buffer_append(&buf, encoded, enclen);
-+			buffer_put_char(&buf, ',');
-+			buffer_append(&buf, KEX_GSS_GRP1_SHA1_ID, 
-+			    sizeof(KEX_GSS_GRP1_SHA1_ID) - 1);
-+			buffer_append(&buf, encoded, enclen);
-+			buffer_put_char(&buf, ',');
-+			buffer_append(&buf, KEX_GSS_GRP14_SHA1_ID,
-+			    sizeof(KEX_GSS_GRP14_SHA1_ID) - 1);
-+			buffer_append(&buf, encoded, enclen);
-+
-+			gss_enc2oid[oidpos].oid = &(gss_supported->elements[i]);
-+			gss_enc2oid[oidpos].encoded = encoded;
-+			oidpos++;
-+		}
-+	}
-+	gss_enc2oid[oidpos].oid = NULL;
-+	gss_enc2oid[oidpos].encoded = NULL;
-+
-+	buffer_put_char(&buf, '\0');
-+
-+	mechs = xmalloc(buffer_len(&buf));
-+	buffer_get(&buf, mechs, buffer_len(&buf));
-+	buffer_free(&buf);
-+
-+	if (strlen(mechs) == 0) {
-+		xfree(mechs);
-+		mechs = NULL;
-+	}
-+	
-+	return (mechs);
-+}
-+
-+gss_OID
-+ssh_gssapi_id_kex(Gssctxt *ctx, char *name, int kex_type) {
-+	int i = 0;
-+	
-+	switch (kex_type) {
-+	case KEX_GSS_GRP1_SHA1:
-+		if (strlen(name) < sizeof(KEX_GSS_GRP1_SHA1_ID))
-+			return GSS_C_NO_OID;
-+		name += sizeof(KEX_GSS_GRP1_SHA1_ID) - 1;
-+		break;
-+	case KEX_GSS_GRP14_SHA1:
-+		if (strlen(name) < sizeof(KEX_GSS_GRP14_SHA1_ID))
-+			return GSS_C_NO_OID;
-+		name += sizeof(KEX_GSS_GRP14_SHA1_ID) - 1;
-+		break;
-+	case KEX_GSS_GEX_SHA1:
-+		if (strlen(name) < sizeof(KEX_GSS_GEX_SHA1_ID))
-+			return GSS_C_NO_OID;
-+		name += sizeof(KEX_GSS_GEX_SHA1_ID) - 1;
-+		break;
-+	default:
-+		return GSS_C_NO_OID;
-+	}
-+
-+	while (gss_enc2oid[i].encoded != NULL &&
-+	    strcmp(name, gss_enc2oid[i].encoded) != 0)
-+		i++;
-+
-+	if (gss_enc2oid[i].oid != NULL && ctx != NULL)
-+		ssh_gssapi_set_oid(ctx, gss_enc2oid[i].oid);
-+
-+	return gss_enc2oid[i].oid;
-+}
-+
- /* Check that the OID in a data stream matches that in the context */
- int
- ssh_gssapi_check_oid(Gssctxt *ctx, void *data, size_t len)
-@@ -197,7 +352,7 @@ ssh_gssapi_init_ctx(Gssctxt *ctx, int deleg_creds, gss_buffer_desc *recv_tok,
- 	}
- 
- 	ctx->major = gss_init_sec_context(&ctx->minor,
--	    GSS_C_NO_CREDENTIAL, &ctx->context, ctx->name, ctx->oid,
-+	    ctx->client_creds, &ctx->context, ctx->name, ctx->oid,
- 	    GSS_C_MUTUAL_FLAG | GSS_C_INTEG_FLAG | deleg_flag,
- 	    0, NULL, recv_tok, NULL, send_tok, flags, NULL);
- 
-@@ -227,8 +382,42 @@ ssh_gssapi_import_name(Gssctxt *ctx, const char *host)
- }
- 
- OM_uint32
-+ssh_gssapi_client_identity(Gssctxt *ctx, const char *name)
-+{
-+	gss_buffer_desc gssbuf;
-+	gss_name_t gssname;
-+	OM_uint32 status;
-+	gss_OID_set oidset;
-+
-+	gssbuf.value = (void *) name;
-+	gssbuf.length = strlen(gssbuf.value);
-+
-+	gss_create_empty_oid_set(&status, &oidset);
-+	gss_add_oid_set_member(&status, ctx->oid, &oidset);
-+
-+	ctx->major = gss_import_name(&ctx->minor, &gssbuf,
-+	    GSS_C_NT_USER_NAME, &gssname);
-+
-+	if (!ctx->major)
-+		ctx->major = gss_acquire_cred(&ctx->minor, 
-+		    gssname, 0, oidset, GSS_C_INITIATE, 
-+		    &ctx->client_creds, NULL, NULL);
-+
-+	gss_release_name(&status, &gssname);
-+	gss_release_oid_set(&status, &oidset);
-+
-+	if (ctx->major)
-+		ssh_gssapi_error(ctx);
-+
-+	return(ctx->major);
-+}
-+
-+OM_uint32
- ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_t buffer, gss_buffer_t hash)
- {
-+	if (ctx == NULL) 
-+		return -1;
-+
- 	if ((ctx->major = gss_get_mic(&ctx->minor, ctx->context,
- 	    GSS_C_QOP_DEFAULT, buffer, hash)))
- 		ssh_gssapi_error(ctx);
-@@ -236,6 +425,19 @@ ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_t buffer, gss_buffer_t hash)
- 	return (ctx->major);
- }
- 
-+/* Priviledged when used by server */
-+OM_uint32
-+ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
-+{
-+	if (ctx == NULL)
-+		return -1;
-+
-+	ctx->major = gss_verify_mic(&ctx->minor, ctx->context,
-+	    gssbuf, gssmic, NULL);
-+
-+	return (ctx->major);
-+}
-+
- void
- ssh_gssapi_buildmic(Buffer *b, const char *user, const char *service,
-     const char *context)
-@@ -249,11 +451,16 @@ ssh_gssapi_buildmic(Buffer *b, const char *user, const char *service,
- }
- 
- int
--ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host)
-+ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host, 
-+    const char *client)
- {
- 	gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
- 	OM_uint32 major, minor;
- 	gss_OID_desc spnego_oid = {6, (void *)"\x2B\x06\x01\x05\x05\x02"};
-+	Gssctxt *intctx = NULL;
-+
-+	if (ctx == NULL)
-+		ctx = &intctx;
- 
- 	/* RFC 4462 says we MUST NOT do SPNEGO */
- 	if (oid->length == spnego_oid.length && 
-@@ -263,6 +470,10 @@ ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host)
- 	ssh_gssapi_build_ctx(ctx);
- 	ssh_gssapi_set_oid(*ctx, oid);
- 	major = ssh_gssapi_import_name(*ctx, host);
-+
-+	if (!GSS_ERROR(major) && client)
-+		major = ssh_gssapi_client_identity(*ctx, client);
-+
- 	if (!GSS_ERROR(major)) {
- 		major = ssh_gssapi_init_ctx(*ctx, 0, GSS_C_NO_BUFFER, &token, 
- 		    NULL);
-@@ -272,10 +483,67 @@ ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host)
- 			    GSS_C_NO_BUFFER);
- 	}
- 
--	if (GSS_ERROR(major)) 
-+	if (GSS_ERROR(major) || intctx != NULL) 
- 		ssh_gssapi_delete_ctx(ctx);
- 
- 	return (!GSS_ERROR(major));
- }
- 
-+int
-+ssh_gssapi_credentials_updated(Gssctxt *ctxt) {
-+	static gss_name_t saved_name = GSS_C_NO_NAME;
-+	static OM_uint32 saved_lifetime = 0;
-+	static gss_OID saved_mech = GSS_C_NO_OID;
-+	static gss_name_t name;
-+	static OM_uint32 last_call = 0;
-+	OM_uint32 lifetime, now, major, minor;
-+	int equal;
-+	gss_cred_usage_t usage = GSS_C_INITIATE;
-+	
-+	now = time(NULL);
-+
-+	if (ctxt) {
-+		debug("Rekey has happened - updating saved versions");
-+
-+		if (saved_name != GSS_C_NO_NAME)
-+			gss_release_name(&minor, &saved_name);
-+
-+		major = gss_inquire_cred(&minor, GSS_C_NO_CREDENTIAL,
-+		    &saved_name, &saved_lifetime, NULL, NULL);
-+
-+		if (!GSS_ERROR(major)) {
-+			saved_mech = ctxt->oid;
-+		        saved_lifetime+= now;
-+		} else {
-+			/* Handle the error */
-+		}
-+		return 0;
-+	}
-+
-+	if (now - last_call < 10)
-+		return 0;
-+
-+	last_call = now;
-+
-+	if (saved_mech == GSS_C_NO_OID)
-+		return 0;
-+	
-+	major = gss_inquire_cred(&minor, GSS_C_NO_CREDENTIAL, 
-+	    &name, &lifetime, NULL, NULL);
-+	if (major == GSS_S_CREDENTIALS_EXPIRED)
-+		return 0;
-+	else if (GSS_ERROR(major))
-+		return 0;
-+
-+	major = gss_compare_name(&minor, saved_name, name, &equal);
-+	gss_release_name(&minor, &name);
-+	if (GSS_ERROR(major))
-+		return 0;
-+
-+	if (equal && (saved_lifetime < lifetime + now - 10))
-+		return 1;
-+
-+	return 0;
-+}
-+
- #endif /* GSSAPI */
-diff --git a/gss-serv-krb5.c b/gss-serv-krb5.c
-index 5a625ac..e7170ee 100644
---- a/gss-serv-krb5.c
-+++ b/gss-serv-krb5.c
-@@ -1,7 +1,7 @@
- /* $OpenBSD: gss-serv-krb5.c,v 1.7 2006/08/03 03:34:42 deraadt Exp $ */
- 
- /*
-- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
-+ * Copyright (c) 2001-2007 Simon Wilkinson. All rights reserved.
-  *
-  * Redistribution and use in source and binary forms, with or without
-  * modification, are permitted provided that the following conditions
-@@ -120,6 +120,7 @@ ssh_gssapi_krb5_storecreds(ssh_gssapi_client *client)
- 	krb5_principal princ;
- 	OM_uint32 maj_status, min_status;
- 	int len;
-+	const char *new_ccname;
- 
- 	if (client->creds == NULL) {
- 		debug("No credentials stored");
-@@ -168,11 +169,16 @@ ssh_gssapi_krb5_storecreds(ssh_gssapi_client *client)
- 		return;
- 	}
- 
--	client->store.filename = xstrdup(krb5_cc_get_name(krb_context, ccache));
-+	new_ccname = krb5_cc_get_name(krb_context, ccache);
-+
- 	client->store.envvar = "KRB5CCNAME";
--	len = strlen(client->store.filename) + 6;
--	client->store.envval = xmalloc(len);
--	snprintf(client->store.envval, len, "FILE:%s", client->store.filename);
-+#ifdef USE_CCAPI
-+	xasprintf(&client->store.envval, "API:%s", new_ccname);
-+	client->store.filename = NULL;
-+#else
-+	xasprintf(&client->store.envval, "FILE:%s", new_ccname);
-+	client->store.filename = xstrdup(new_ccname);
-+#endif
- 
- #ifdef USE_PAM
- 	if (options.use_pam)
-@@ -184,6 +190,71 @@ ssh_gssapi_krb5_storecreds(ssh_gssapi_client *client)
- 	return;
- }
- 
-+int
-+ssh_gssapi_krb5_updatecreds(ssh_gssapi_ccache *store, 
-+    ssh_gssapi_client *client)
-+{
-+	krb5_ccache ccache = NULL;
-+	krb5_principal principal = NULL;
-+	char *name = NULL;
-+	krb5_error_code problem;
-+	OM_uint32 maj_status, min_status;
-+
-+   	if ((problem = krb5_cc_resolve(krb_context, store->envval, &ccache))) {
-+                logit("krb5_cc_resolve(): %.100s",
-+                    krb5_get_err_text(krb_context, problem));
-+                return 0;
-+       	}
-+	
-+	/* Find out who the principal in this cache is */
-+	if ((problem = krb5_cc_get_principal(krb_context, ccache, 
-+	    &principal))) {
-+		logit("krb5_cc_get_principal(): %.100s",
-+		    krb5_get_err_text(krb_context, problem));
-+		krb5_cc_close(krb_context, ccache);
-+		return 0;
-+	}
-+
-+	if ((problem = krb5_unparse_name(krb_context, principal, &name))) {
-+		logit("krb5_unparse_name(): %.100s",
-+		    krb5_get_err_text(krb_context, problem));
-+		krb5_free_principal(krb_context, principal);
-+		krb5_cc_close(krb_context, ccache);
-+		return 0;
-+	}
-+
-+
-+	if (strcmp(name,client->exportedname.value)!=0) {
-+		debug("Name in local credentials cache differs. Not storing");
-+		krb5_free_principal(krb_context, principal);
-+		krb5_cc_close(krb_context, ccache);
-+		krb5_free_unparsed_name(krb_context, name);
-+		return 0;
-+	}
-+	krb5_free_unparsed_name(krb_context, name);
-+
-+	/* Name matches, so lets get on with it! */
-+
-+	if ((problem = krb5_cc_initialize(krb_context, ccache, principal))) {
-+		logit("krb5_cc_initialize(): %.100s",
-+		    krb5_get_err_text(krb_context, problem));
-+		krb5_free_principal(krb_context, principal);
-+		krb5_cc_close(krb_context, ccache);
-+		return 0;
-+	}
-+
-+	krb5_free_principal(krb_context, principal);
-+
-+	if ((maj_status = gss_krb5_copy_ccache(&min_status, client->creds,
-+	    ccache))) {
-+		logit("gss_krb5_copy_ccache() failed. Sorry!");
-+		krb5_cc_close(krb_context, ccache);
-+		return 0;
-+	}
-+
-+	return 1;
-+}
-+
- ssh_gssapi_mech gssapi_kerberos_mech = {
- 	"toWM5Slw5Ew8Mqkay+al2g==",
- 	"Kerberos",
-@@ -191,7 +262,8 @@ ssh_gssapi_mech gssapi_kerberos_mech = {
- 	NULL,
- 	&ssh_gssapi_krb5_userok,
- 	NULL,
--	&ssh_gssapi_krb5_storecreds
-+	&ssh_gssapi_krb5_storecreds,
-+	&ssh_gssapi_krb5_updatecreds
- };
- 
- #endif /* KRB5 */
-diff --git a/gss-serv.c b/gss-serv.c
-index c719c13..380895e 100644
---- a/gss-serv.c
-+++ b/gss-serv.c
-@@ -1,7 +1,7 @@
- /* $OpenBSD: gss-serv.c,v 1.23 2011/08/01 19:18:15 markus Exp $ */
- 
- /*
-- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
-+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
-  *
-  * Redistribution and use in source and binary forms, with or without
-  * modification, are permitted provided that the following conditions
-@@ -45,15 +45,20 @@
- #include "channels.h"
- #include "session.h"
- #include "misc.h"
-+#include "servconf.h"
-+#include "uidswap.h"
- 
- #include "ssh-gss.h"
-+#include "monitor_wrap.h"
-+
-+extern ServerOptions options;
- 
- static ssh_gssapi_client gssapi_client =
-     { GSS_C_EMPTY_BUFFER, GSS_C_EMPTY_BUFFER,
--    GSS_C_NO_CREDENTIAL, NULL, {NULL, NULL, NULL}};
-+    GSS_C_NO_CREDENTIAL, GSS_C_NO_NAME,  NULL, {NULL, NULL, NULL}, 0, 0};
- 
- ssh_gssapi_mech gssapi_null_mech =
--    { NULL, NULL, {0, NULL}, NULL, NULL, NULL, NULL};
-+    { NULL, NULL, {0, NULL}, NULL, NULL, NULL, NULL, NULL};
- 
- #ifdef KRB5
- extern ssh_gssapi_mech gssapi_kerberos_mech;
-@@ -81,25 +86,32 @@ ssh_gssapi_acquire_cred(Gssctxt *ctx)
- 	char lname[MAXHOSTNAMELEN];
- 	gss_OID_set oidset;
- 
--	gss_create_empty_oid_set(&status, &oidset);
--	gss_add_oid_set_member(&status, ctx->oid, &oidset);
-+	if (options.gss_strict_acceptor) {
-+		gss_create_empty_oid_set(&status, &oidset);
-+		gss_add_oid_set_member(&status, ctx->oid, &oidset);
- 
--	if (gethostname(lname, MAXHOSTNAMELEN)) {
--		gss_release_oid_set(&status, &oidset);
--		return (-1);
--	}
-+		if (gethostname(lname, MAXHOSTNAMELEN)) {
-+			gss_release_oid_set(&status, &oidset);
-+			return (-1);
-+		}
-+
-+		if (GSS_ERROR(ssh_gssapi_import_name(ctx, lname))) {
-+			gss_release_oid_set(&status, &oidset);
-+			return (ctx->major);
-+		}
-+
-+		if ((ctx->major = gss_acquire_cred(&ctx->minor,
-+		    ctx->name, 0, oidset, GSS_C_ACCEPT, &ctx->creds, 
-+		    NULL, NULL)))
-+			ssh_gssapi_error(ctx);
- 
--	if (GSS_ERROR(ssh_gssapi_import_name(ctx, lname))) {
- 		gss_release_oid_set(&status, &oidset);
- 		return (ctx->major);
-+	} else {
-+		ctx->name = GSS_C_NO_NAME;
-+		ctx->creds = GSS_C_NO_CREDENTIAL;
- 	}
--
--	if ((ctx->major = gss_acquire_cred(&ctx->minor,
--	    ctx->name, 0, oidset, GSS_C_ACCEPT, &ctx->creds, NULL, NULL)))
--		ssh_gssapi_error(ctx);
--
--	gss_release_oid_set(&status, &oidset);
--	return (ctx->major);
-+	return GSS_S_COMPLETE;
- }
- 
- /* Privileged */
-@@ -114,6 +126,29 @@ ssh_gssapi_server_ctx(Gssctxt **ctx, gss_OID oid)
- }
- 
- /* Unprivileged */
-+char *
-+ssh_gssapi_server_mechanisms() {
-+	gss_OID_set	supported;
-+
-+	ssh_gssapi_supported_oids(&supported);
-+	return (ssh_gssapi_kex_mechs(supported, &ssh_gssapi_server_check_mech,
-+	    NULL, NULL));
-+}
-+
-+/* Unprivileged */
-+int
-+ssh_gssapi_server_check_mech(Gssctxt **dum, gss_OID oid, const char *data,
-+    const char *dummy) {
-+	Gssctxt *ctx = NULL;
-+	int res;
-+ 
-+	res = !GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctx, oid)));
-+	ssh_gssapi_delete_ctx(&ctx);
-+
-+	return (res);
-+}
-+
-+/* Unprivileged */
- void
- ssh_gssapi_supported_oids(gss_OID_set *oidset)
- {
-@@ -123,7 +158,9 @@ ssh_gssapi_supported_oids(gss_OID_set *oidset)
- 	gss_OID_set supported;
- 
- 	gss_create_empty_oid_set(&min_status, oidset);
--	gss_indicate_mechs(&min_status, &supported);
-+
-+	if (GSS_ERROR(gss_indicate_mechs(&min_status, &supported)))
-+		return;
- 
- 	while (supported_mechs[i]->name != NULL) {
- 		if (GSS_ERROR(gss_test_oid_set_member(&min_status,
-@@ -249,8 +286,48 @@ OM_uint32
- ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
- {
- 	int i = 0;
-+	int equal = 0;
-+	gss_name_t new_name = GSS_C_NO_NAME;
-+	gss_buffer_desc ename = GSS_C_EMPTY_BUFFER;
-+
-+	if (options.gss_store_rekey && client->used && ctx->client_creds) {
-+		if (client->mech->oid.length != ctx->oid->length ||
-+		    (memcmp(client->mech->oid.elements,
-+		     ctx->oid->elements, ctx->oid->length) !=0)) {
-+			debug("Rekeyed credentials have different mechanism");
-+			return GSS_S_COMPLETE;
-+		}
-+
-+		if ((ctx->major = gss_inquire_cred_by_mech(&ctx->minor, 
-+		    ctx->client_creds, ctx->oid, &new_name, 
-+		    NULL, NULL, NULL))) {
-+			ssh_gssapi_error(ctx);
-+			return (ctx->major);
-+		}
-+
-+		ctx->major = gss_compare_name(&ctx->minor, client->name, 
-+		    new_name, &equal);
- 
--	gss_buffer_desc ename;
-+		if (GSS_ERROR(ctx->major)) {
-+			ssh_gssapi_error(ctx);
-+			return (ctx->major);
-+		}
-+ 
-+		if (!equal) {
-+			debug("Rekeyed credentials have different name");
-+			return GSS_S_COMPLETE;
-+		}
-+
-+		debug("Marking rekeyed credentials for export");
-+
-+		gss_release_name(&ctx->minor, &client->name);
-+		gss_release_cred(&ctx->minor, &client->creds);
-+		client->name = new_name;
-+		client->creds = ctx->client_creds;
-+        	ctx->client_creds = GSS_C_NO_CREDENTIAL;
-+		client->updated = 1;
-+		return GSS_S_COMPLETE;
-+	}
- 
- 	client->mech = NULL;
- 
-@@ -265,6 +342,13 @@ ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
- 	if (client->mech == NULL)
- 		return GSS_S_FAILURE;
- 
-+	if (ctx->client_creds &&
-+	    (ctx->major = gss_inquire_cred_by_mech(&ctx->minor,
-+	     ctx->client_creds, ctx->oid, &client->name, NULL, NULL, NULL))) {
-+		ssh_gssapi_error(ctx);
-+		return (ctx->major);
-+	}
-+
- 	if ((ctx->major = gss_display_name(&ctx->minor, ctx->client,
- 	    &client->displayname, NULL))) {
- 		ssh_gssapi_error(ctx);
-@@ -282,6 +366,8 @@ ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
- 		return (ctx->major);
- 	}
- 
-+	gss_release_buffer(&ctx->minor, &ename);
-+
- 	/* We can't copy this structure, so we just move the pointer to it */
- 	client->creds = ctx->client_creds;
- 	ctx->client_creds = GSS_C_NO_CREDENTIAL;
-@@ -329,7 +415,7 @@ ssh_gssapi_do_child(char ***envp, u_int *envsizep)
- 
- /* Privileged */
- int
--ssh_gssapi_userok(char *user)
-+ssh_gssapi_userok(char *user, struct passwd *pw)
- {
- 	OM_uint32 lmin;
- 
-@@ -339,9 +425,11 @@ ssh_gssapi_userok(char *user)
- 		return 0;
- 	}
- 	if (gssapi_client.mech && gssapi_client.mech->userok)
--		if ((*gssapi_client.mech->userok)(&gssapi_client, user))
-+		if ((*gssapi_client.mech->userok)(&gssapi_client, user)) {
-+			gssapi_client.used = 1;
-+			gssapi_client.store.owner = pw;
- 			return 1;
--		else {
-+		} else {
- 			/* Destroy delegated credentials if userok fails */
- 			gss_release_buffer(&lmin, &gssapi_client.displayname);
- 			gss_release_buffer(&lmin, &gssapi_client.exportedname);
-@@ -354,14 +442,90 @@ ssh_gssapi_userok(char *user)
- 	return (0);
- }
- 
--/* Privileged */
--OM_uint32
--ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
-+/* These bits are only used for rekeying. The unpriviledged child is running 
-+ * as the user, the monitor is root.
-+ *
-+ * In the child, we want to :
-+ *    *) Ask the monitor to store our credentials into the store we specify
-+ *    *) If it succeeds, maybe do a PAM update
-+ */
-+
-+/* Stuff for PAM */
-+
-+#ifdef USE_PAM
-+static int ssh_gssapi_simple_conv(int n, const struct pam_message **msg, 
-+    struct pam_response **resp, void *data)
- {
--	ctx->major = gss_verify_mic(&ctx->minor, ctx->context,
--	    gssbuf, gssmic, NULL);
-+	return (PAM_CONV_ERR);
-+}
-+#endif
- 
--	return (ctx->major);
-+void
-+ssh_gssapi_rekey_creds() {
-+	int ok;
-+	int ret;
-+#ifdef USE_PAM
-+	pam_handle_t *pamh = NULL;
-+	struct pam_conv pamconv = {ssh_gssapi_simple_conv, NULL};
-+	char *envstr;
-+#endif
-+
-+	if (gssapi_client.store.filename == NULL && 
-+	    gssapi_client.store.envval == NULL &&
-+	    gssapi_client.store.envvar == NULL)
-+		return;
-+ 
-+	ok = PRIVSEP(ssh_gssapi_update_creds(&gssapi_client.store));
-+
-+	if (!ok)
-+		return;
-+
-+	debug("Rekeyed credentials stored successfully");
-+
-+	/* Actually managing to play with the ssh pam stack from here will
-+	 * be next to impossible. In any case, we may want different options
-+	 * for rekeying. So, use our own :)
-+	 */
-+#ifdef USE_PAM	
-+	if (!use_privsep) {
-+		debug("Not even going to try and do PAM with privsep disabled");
-+		return;
-+	}
-+
-+	ret = pam_start("sshd-rekey", gssapi_client.store.owner->pw_name,
-+ 	    &pamconv, &pamh);
-+	if (ret)
-+		return;
-+
-+	xasprintf(&envstr, "%s=%s", gssapi_client.store.envvar, 
-+	    gssapi_client.store.envval);
-+
-+	ret = pam_putenv(pamh, envstr);
-+	if (!ret)
-+		pam_setcred(pamh, PAM_REINITIALIZE_CRED);
-+	pam_end(pamh, PAM_SUCCESS);
-+#endif
-+}
-+
-+int 
-+ssh_gssapi_update_creds(ssh_gssapi_ccache *store) {
-+	int ok = 0;
-+
-+	/* Check we've got credentials to store */
-+	if (!gssapi_client.updated)
-+		return 0;
-+
-+	gssapi_client.updated = 0;
-+
-+	temporarily_use_uid(gssapi_client.store.owner);
-+	if (gssapi_client.mech && gssapi_client.mech->updatecreds)
-+		ok = (*gssapi_client.mech->updatecreds)(store, &gssapi_client);
-+	else
-+		debug("No update function for this mechanism");
-+
-+	restore_uid();
-+
-+	return ok;
- }
- 
- #endif
-diff --git a/kex.c b/kex.c
-index c65e28f..58349fc 100644
---- a/kex.c
-+++ b/kex.c
-@@ -50,6 +50,10 @@
- #include "monitor.h"
- #include "roaming.h"
- 
-+#ifdef GSSAPI
-+#include "ssh-gss.h"
-+#endif
-+
- #if OPENSSL_VERSION_NUMBER >= 0x00907000L
- # if defined(HAVE_EVP_SHA256)
- # define evp_ssh_sha256 EVP_sha256
-@@ -358,6 +362,20 @@ choose_kex(Kex *k, char *client, char *server)
-  		k->kex_type = KEX_ECDH_SHA2;
- 		k->evp_md = kex_ecdh_name_to_evpmd(k->name);
- #endif
-+#ifdef GSSAPI
-+	} else if (strncmp(k->name, KEX_GSS_GEX_SHA1_ID,
-+	    sizeof(KEX_GSS_GEX_SHA1_ID) - 1) == 0) {
-+		k->kex_type = KEX_GSS_GEX_SHA1;
-+		k->evp_md = EVP_sha1();
-+	} else if (strncmp(k->name, KEX_GSS_GRP1_SHA1_ID,
-+	    sizeof(KEX_GSS_GRP1_SHA1_ID) - 1) == 0) {
-+		k->kex_type = KEX_GSS_GRP1_SHA1;
-+		k->evp_md = EVP_sha1();
-+	} else if (strncmp(k->name, KEX_GSS_GRP14_SHA1_ID,
-+	    sizeof(KEX_GSS_GRP14_SHA1_ID) - 1) == 0) {
-+		k->kex_type = KEX_GSS_GRP14_SHA1;
-+		k->evp_md = EVP_sha1();
-+#endif
- 	} else
- 		fatal("bad kex alg %s", k->name);
- }
-diff --git a/kex.h b/kex.h
-index 7373d3c..fa50b2c 100644
---- a/kex.h
-+++ b/kex.h
-@@ -73,6 +73,9 @@ enum kex_exchange {
- 	KEX_DH_GEX_SHA1,
- 	KEX_DH_GEX_SHA256,
- 	KEX_ECDH_SHA2,
-+	KEX_GSS_GRP1_SHA1,
-+	KEX_GSS_GRP14_SHA1,
-+	KEX_GSS_GEX_SHA1,
- 	KEX_MAX
- };
- 
-@@ -129,6 +132,12 @@ struct Kex {
- 	sig_atomic_t done;
- 	int	flags;
- 	const EVP_MD *evp_md;
-+#ifdef GSSAPI
-+	int	gss_deleg_creds;
-+	int	gss_trust_dns;
-+	char    *gss_host;
-+	char	*gss_client;
-+#endif
- 	char	*client_version_string;
- 	char	*server_version_string;
- 	int	(*verify_host_key)(Key *);
-@@ -156,6 +165,11 @@ void	 kexgex_server(Kex *);
- void	 kexecdh_client(Kex *);
- void	 kexecdh_server(Kex *);
- 
-+#ifdef GSSAPI
-+void	kexgss_client(Kex *);
-+void	kexgss_server(Kex *);
-+#endif
-+
- void
- kex_dh_hash(char *, char *, char *, int, char *, int, u_char *, int,
-     BIGNUM *, BIGNUM *, BIGNUM *, u_char **, u_int *);
-diff --git a/kexgssc.c b/kexgssc.c
-new file mode 100644
-index 0000000..39be405
---- /dev/null
-+++ b/kexgssc.c
-@@ -0,0 +1,334 @@
-+/*
-+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
-+ *
-+ * Redistribution and use in source and binary forms, with or without
-+ * modification, are permitted provided that the following conditions
-+ * are met:
-+ * 1. Redistributions of source code must retain the above copyright
-+ *    notice, this list of conditions and the following disclaimer.
-+ * 2. Redistributions in binary form must reproduce the above copyright
-+ *    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.
-+ */
-+
-+#include "includes.h"
-+
-+#ifdef GSSAPI
-+
-+#include "includes.h"
-+
-+#include <openssl/crypto.h>
-+#include <openssl/bn.h>
-+
-+#include <string.h>
-+
-+#include "xmalloc.h"
-+#include "buffer.h"
-+#include "ssh2.h"
-+#include "key.h"
-+#include "cipher.h"
-+#include "kex.h"
-+#include "log.h"
-+#include "packet.h"
-+#include "dh.h"
-+
-+#include "ssh-gss.h"
-+
-+void
-+kexgss_client(Kex *kex) {
-+	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
-+	gss_buffer_desc recv_tok, gssbuf, msg_tok, *token_ptr;
-+	Gssctxt *ctxt;
-+	OM_uint32 maj_status, min_status, ret_flags;
-+	u_int klen, kout, slen = 0, hashlen, strlen;
-+	DH *dh; 
-+	BIGNUM *dh_server_pub = NULL;
-+	BIGNUM *shared_secret = NULL;
-+	BIGNUM *p = NULL;
-+	BIGNUM *g = NULL;	
-+	u_char *kbuf, *hash;
-+	u_char *serverhostkey = NULL;
-+	u_char *empty = "";
-+	char *msg;
-+	char *lang;
-+	int type = 0;
-+	int first = 1;
-+	int nbits = 0, min = DH_GRP_MIN, max = DH_GRP_MAX;
-+
-+	/* Initialise our GSSAPI world */	
-+	ssh_gssapi_build_ctx(&ctxt);
-+	if (ssh_gssapi_id_kex(ctxt, kex->name, kex->kex_type) 
-+	    == GSS_C_NO_OID)
-+		fatal("Couldn't identify host exchange");
-+
-+	if (ssh_gssapi_import_name(ctxt, kex->gss_host))
-+		fatal("Couldn't import hostname");
-+
-+	if (kex->gss_client && 
-+	    ssh_gssapi_client_identity(ctxt, kex->gss_client))
-+		fatal("Couldn't acquire client credentials");
-+
-+	switch (kex->kex_type) {
-+	case KEX_GSS_GRP1_SHA1:
-+		dh = dh_new_group1();
-+		break;
-+	case KEX_GSS_GRP14_SHA1:
-+		dh = dh_new_group14();
-+		break;
-+	case KEX_GSS_GEX_SHA1:
-+		debug("Doing group exchange\n");
-+		nbits = dh_estimate(kex->we_need * 8);
-+		packet_start(SSH2_MSG_KEXGSS_GROUPREQ);
-+		packet_put_int(min);
-+		packet_put_int(nbits);
-+		packet_put_int(max);
-+
-+		packet_send();
-+
-+		packet_read_expect(SSH2_MSG_KEXGSS_GROUP);
-+
-+		if ((p = BN_new()) == NULL)
-+			fatal("BN_new() failed");
-+		packet_get_bignum2(p);
-+		if ((g = BN_new()) == NULL)
-+			fatal("BN_new() failed");
-+		packet_get_bignum2(g);
-+		packet_check_eom();
-+
-+		if (BN_num_bits(p) < min || BN_num_bits(p) > max)
-+			fatal("GSSGRP_GEX group out of range: %d !< %d !< %d",
-+			    min, BN_num_bits(p), max);
-+
-+		dh = dh_new_group(g, p);
-+		break;
-+	default:
-+		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
-+	}
-+	
-+	/* Step 1 - e is dh->pub_key */
-+	dh_gen_key(dh, kex->we_need * 8);
-+
-+	/* This is f, we initialise it now to make life easier */
-+	dh_server_pub = BN_new();
-+	if (dh_server_pub == NULL)
-+		fatal("dh_server_pub == NULL");
-+
-+	token_ptr = GSS_C_NO_BUFFER;
-+			 
-+	do {
-+		debug("Calling gss_init_sec_context");
-+		
-+		maj_status = ssh_gssapi_init_ctx(ctxt,
-+		    kex->gss_deleg_creds, token_ptr, &send_tok,
-+		    &ret_flags);
-+
-+		if (GSS_ERROR(maj_status)) {
-+			if (send_tok.length != 0) {
-+				packet_start(SSH2_MSG_KEXGSS_CONTINUE);
-+				packet_put_string(send_tok.value,
-+				    send_tok.length);
-+			}
-+			fatal("gss_init_context failed");
-+		}
-+
-+		/* If we've got an old receive buffer get rid of it */
-+		if (token_ptr != GSS_C_NO_BUFFER)
-+			xfree(recv_tok.value);
-+
-+		if (maj_status == GSS_S_COMPLETE) {
-+			/* If mutual state flag is not true, kex fails */
-+			if (!(ret_flags & GSS_C_MUTUAL_FLAG))
-+				fatal("Mutual authentication failed");
-+
-+			/* If integ avail flag is not true kex fails */
-+			if (!(ret_flags & GSS_C_INTEG_FLAG))
-+				fatal("Integrity check failed");
-+		}
-+
-+		/* 
-+		 * If we have data to send, then the last message that we
-+		 * received cannot have been a 'complete'. 
-+		 */
-+		if (send_tok.length != 0) {
-+			if (first) {
-+				packet_start(SSH2_MSG_KEXGSS_INIT);
-+				packet_put_string(send_tok.value,
-+				    send_tok.length);
-+				packet_put_bignum2(dh->pub_key);
-+				first = 0;
-+			} else {
-+				packet_start(SSH2_MSG_KEXGSS_CONTINUE);
-+				packet_put_string(send_tok.value,
-+				    send_tok.length);
-+			}
-+			packet_send();
-+			gss_release_buffer(&min_status, &send_tok);
-+
-+			/* If we've sent them data, they should reply */
-+			do {	
-+				type = packet_read();
-+				if (type == SSH2_MSG_KEXGSS_HOSTKEY) {
-+					debug("Received KEXGSS_HOSTKEY");
-+					if (serverhostkey)
-+						fatal("Server host key received more than once");
-+					serverhostkey = 
-+					    packet_get_string(&slen);
-+				}
-+			} while (type == SSH2_MSG_KEXGSS_HOSTKEY);
-+
-+			switch (type) {
-+			case SSH2_MSG_KEXGSS_CONTINUE:
-+				debug("Received GSSAPI_CONTINUE");
-+				if (maj_status == GSS_S_COMPLETE) 
-+					fatal("GSSAPI Continue received from server when complete");
-+				recv_tok.value = packet_get_string(&strlen);
-+				recv_tok.length = strlen; 
-+				break;
-+			case SSH2_MSG_KEXGSS_COMPLETE:
-+				debug("Received GSSAPI_COMPLETE");
-+				packet_get_bignum2(dh_server_pub);
-+				msg_tok.value =  packet_get_string(&strlen);
-+				msg_tok.length = strlen; 
-+
-+				/* Is there a token included? */
-+				if (packet_get_char()) {
-+					recv_tok.value=
-+					    packet_get_string(&strlen);
-+					recv_tok.length = strlen;
-+					/* If we're already complete - protocol error */
-+					if (maj_status == GSS_S_COMPLETE)
-+						packet_disconnect("Protocol error: received token when complete");
-+					} else {
-+						/* No token included */
-+						if (maj_status != GSS_S_COMPLETE)
-+							packet_disconnect("Protocol error: did not receive final token");
-+				}
-+				break;
-+			case SSH2_MSG_KEXGSS_ERROR:
-+				debug("Received Error");
-+				maj_status = packet_get_int();
-+				min_status = packet_get_int();
-+				msg = packet_get_string(NULL);
-+				lang = packet_get_string(NULL);
-+				fatal("GSSAPI Error: \n%.400s",msg);
-+			default:
-+				packet_disconnect("Protocol error: didn't expect packet type %d",
-+		    		type);
-+			}
-+			token_ptr = &recv_tok;
-+		} else {
-+			/* No data, and not complete */
-+			if (maj_status != GSS_S_COMPLETE)
-+				fatal("Not complete, and no token output");
-+		}
-+	} while (maj_status & GSS_S_CONTINUE_NEEDED);
-+
-+	/* 
-+	 * We _must_ have received a COMPLETE message in reply from the 
-+	 * server, which will have set dh_server_pub and msg_tok 
-+	 */
-+
-+	if (type != SSH2_MSG_KEXGSS_COMPLETE)
-+		fatal("Didn't receive a SSH2_MSG_KEXGSS_COMPLETE when I expected it");
-+
-+	/* Check f in range [1, p-1] */
-+	if (!dh_pub_is_valid(dh, dh_server_pub))
-+		packet_disconnect("bad server public DH value");
-+
-+	/* compute K=f^x mod p */
-+	klen = DH_size(dh);
-+	kbuf = xmalloc(klen);
-+	kout = DH_compute_key(kbuf, dh_server_pub, dh);
-+	if (kout < 0)
-+		fatal("DH_compute_key: failed");
-+
-+	shared_secret = BN_new();
-+	if (shared_secret == NULL)
-+		fatal("kexgss_client: BN_new failed");
-+
-+	if (BN_bin2bn(kbuf, kout, shared_secret) == NULL)
-+		fatal("kexdh_client: BN_bin2bn failed");
-+
-+	memset(kbuf, 0, klen);
-+	xfree(kbuf);
-+
-+	switch (kex->kex_type) {
-+	case KEX_GSS_GRP1_SHA1:
-+	case KEX_GSS_GRP14_SHA1:
-+		kex_dh_hash( kex->client_version_string, 
-+		    kex->server_version_string,
-+		    buffer_ptr(&kex->my), buffer_len(&kex->my),
-+		    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
-+		    (serverhostkey ? serverhostkey : empty), slen,
-+		    dh->pub_key,	/* e */
-+		    dh_server_pub,	/* f */
-+		    shared_secret,	/* K */
-+		    &hash, &hashlen
-+		);
-+		break;
-+	case KEX_GSS_GEX_SHA1:
-+		kexgex_hash(
-+		    kex->evp_md,
-+		    kex->client_version_string,
-+		    kex->server_version_string,
-+		    buffer_ptr(&kex->my), buffer_len(&kex->my),
-+		    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
-+		    (serverhostkey ? serverhostkey : empty), slen,
-+ 		    min, nbits, max,
-+		    dh->p, dh->g,
-+		    dh->pub_key,
-+		    dh_server_pub,
-+		    shared_secret,
-+		    &hash, &hashlen
-+		);
-+		break;
-+	default:
-+		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
-+	}
-+
-+	gssbuf.value = hash;
-+	gssbuf.length = hashlen;
-+
-+	/* Verify that the hash matches the MIC we just got. */
-+	if (GSS_ERROR(ssh_gssapi_checkmic(ctxt, &gssbuf, &msg_tok)))
-+		packet_disconnect("Hash's MIC didn't verify");
-+
-+	xfree(msg_tok.value);
-+
-+	DH_free(dh);
-+	if (serverhostkey)
-+		xfree(serverhostkey);
-+	BN_clear_free(dh_server_pub);
-+
-+	/* save session id */
-+	if (kex->session_id == NULL) {
-+		kex->session_id_len = hashlen;
-+		kex->session_id = xmalloc(kex->session_id_len);
-+		memcpy(kex->session_id, hash, kex->session_id_len);
-+	}
-+
-+	if (kex->gss_deleg_creds)
-+		ssh_gssapi_credentials_updated(ctxt);
-+
-+	if (gss_kex_context == NULL)
-+		gss_kex_context = ctxt;
-+	else
-+		ssh_gssapi_delete_ctx(&ctxt);
-+
-+	kex_derive_keys(kex, hash, hashlen, shared_secret);
-+	BN_clear_free(shared_secret);
-+	kex_finish(kex);
-+}
-+
-+#endif /* GSSAPI */
-diff --git a/kexgsss.c b/kexgsss.c
-new file mode 100644
-index 0000000..0c3eeaa
---- /dev/null
-+++ b/kexgsss.c
-@@ -0,0 +1,288 @@
-+/*
-+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
-+ *
-+ * Redistribution and use in source and binary forms, with or without
-+ * modification, are permitted provided that the following conditions
-+ * are met:
-+ * 1. Redistributions of source code must retain the above copyright
-+ *    notice, this list of conditions and the following disclaimer.
-+ * 2. Redistributions in binary form must reproduce the above copyright
-+ *    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.
-+ */
-+
-+#include "includes.h"
-+
-+#ifdef GSSAPI
-+
-+#include <string.h>
-+
-+#include <openssl/crypto.h>
-+#include <openssl/bn.h>
-+
-+#include "xmalloc.h"
-+#include "buffer.h"
-+#include "ssh2.h"
-+#include "key.h"
-+#include "cipher.h"
-+#include "kex.h"
-+#include "log.h"
-+#include "packet.h"
-+#include "dh.h"
-+#include "ssh-gss.h"
-+#include "monitor_wrap.h"
-+#include "servconf.h"
-+
-+extern ServerOptions options;
-+
-+void
-+kexgss_server(Kex *kex)
-+{
-+	OM_uint32 maj_status, min_status;
-+	
-+	/* 
-+	 * Some GSSAPI implementations use the input value of ret_flags (an
-+ 	 * output variable) as a means of triggering mechanism specific 
-+ 	 * features. Initializing it to zero avoids inadvertently 
-+ 	 * activating this non-standard behaviour.
-+	 */
-+
-+	OM_uint32 ret_flags = 0;
-+	gss_buffer_desc gssbuf, recv_tok, msg_tok;
-+	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
-+	Gssctxt *ctxt = NULL;
-+	u_int slen, klen, kout, hashlen;
-+	u_char *kbuf, *hash;
-+	DH *dh;
-+	int min = -1, max = -1, nbits = -1;
-+	BIGNUM *shared_secret = NULL;
-+	BIGNUM *dh_client_pub = NULL;
-+	int type = 0;
-+	gss_OID oid;
-+	char *mechs;
-+
-+	/* Initialise GSSAPI */
-+
-+	/* If we're rekeying, privsep means that some of the private structures
-+	 * in the GSSAPI code are no longer available. This kludges them back
-+	 * into life
-+	 */
-+	if (!ssh_gssapi_oid_table_ok()) 
-+		if ((mechs = ssh_gssapi_server_mechanisms()))
-+			xfree(mechs);
-+
-+	debug2("%s: Identifying %s", __func__, kex->name);
-+	oid = ssh_gssapi_id_kex(NULL, kex->name, kex->kex_type);
-+	if (oid == GSS_C_NO_OID)
-+	   fatal("Unknown gssapi mechanism");
-+
-+	debug2("%s: Acquiring credentials", __func__);
-+
-+	if (GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctxt, oid))))
-+		fatal("Unable to acquire credentials for the server");
-+
-+	switch (kex->kex_type) {
-+	case KEX_GSS_GRP1_SHA1:
-+		dh = dh_new_group1();
-+		break;
-+	case KEX_GSS_GRP14_SHA1:
-+		dh = dh_new_group14();
-+		break;
-+	case KEX_GSS_GEX_SHA1:
-+		debug("Doing group exchange");
-+		packet_read_expect(SSH2_MSG_KEXGSS_GROUPREQ);
-+		min = packet_get_int();
-+		nbits = packet_get_int();
-+		max = packet_get_int();
-+		min = MAX(DH_GRP_MIN, min);
-+		max = MIN(DH_GRP_MAX, max);
-+		packet_check_eom();
-+		if (max < min || nbits < min || max < nbits)
-+			fatal("GSS_GEX, bad parameters: %d !< %d !< %d",
-+			    min, nbits, max);
-+		dh = PRIVSEP(choose_dh(min, nbits, max));
-+		if (dh == NULL)
-+			packet_disconnect("Protocol error: no matching group found");
-+
-+		packet_start(SSH2_MSG_KEXGSS_GROUP);
-+		packet_put_bignum2(dh->p);
-+		packet_put_bignum2(dh->g);
-+		packet_send();
-+
-+		packet_write_wait();
-+		break;
-+	default:
-+		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
-+	}
-+
-+	dh_gen_key(dh, kex->we_need * 8);
-+
-+	do {
-+		debug("Wait SSH2_MSG_GSSAPI_INIT");
-+		type = packet_read();
-+		switch(type) {
-+		case SSH2_MSG_KEXGSS_INIT:
-+			if (dh_client_pub != NULL) 
-+				fatal("Received KEXGSS_INIT after initialising");
-+			recv_tok.value = packet_get_string(&slen);
-+			recv_tok.length = slen; 
-+
-+			if ((dh_client_pub = BN_new()) == NULL)
-+				fatal("dh_client_pub == NULL");
-+
-+			packet_get_bignum2(dh_client_pub);
-+
-+			/* Send SSH_MSG_KEXGSS_HOSTKEY here, if we want */
-+			break;
-+		case SSH2_MSG_KEXGSS_CONTINUE:
-+			recv_tok.value = packet_get_string(&slen);
-+			recv_tok.length = slen; 
-+			break;
-+		default:
-+			packet_disconnect(
-+			    "Protocol error: didn't expect packet type %d",
-+			    type);
-+		}
-+
-+		maj_status = PRIVSEP(ssh_gssapi_accept_ctx(ctxt, &recv_tok, 
-+		    &send_tok, &ret_flags));
-+
-+		xfree(recv_tok.value);
-+
-+		if (maj_status != GSS_S_COMPLETE && send_tok.length == 0)
-+			fatal("Zero length token output when incomplete");
-+
-+		if (dh_client_pub == NULL)
-+			fatal("No client public key");
-+		
-+		if (maj_status & GSS_S_CONTINUE_NEEDED) {
-+			debug("Sending GSSAPI_CONTINUE");
-+			packet_start(SSH2_MSG_KEXGSS_CONTINUE);
-+			packet_put_string(send_tok.value, send_tok.length);
-+			packet_send();
-+			gss_release_buffer(&min_status, &send_tok);
-+		}
-+	} while (maj_status & GSS_S_CONTINUE_NEEDED);
-+
-+	if (GSS_ERROR(maj_status)) {
-+		if (send_tok.length > 0) {
-+			packet_start(SSH2_MSG_KEXGSS_CONTINUE);
-+			packet_put_string(send_tok.value, send_tok.length);
-+			packet_send();
-+		}
-+		fatal("accept_ctx died");
-+	}
-+
-+	if (!(ret_flags & GSS_C_MUTUAL_FLAG))
-+		fatal("Mutual Authentication flag wasn't set");
-+
-+	if (!(ret_flags & GSS_C_INTEG_FLAG))
-+		fatal("Integrity flag wasn't set");
-+	
-+	if (!dh_pub_is_valid(dh, dh_client_pub))
-+		packet_disconnect("bad client public DH value");
-+
-+	klen = DH_size(dh);
-+	kbuf = xmalloc(klen); 
-+	kout = DH_compute_key(kbuf, dh_client_pub, dh);
-+	if (kout < 0)
-+		fatal("DH_compute_key: failed");
-+
-+	shared_secret = BN_new();
-+	if (shared_secret == NULL)
-+		fatal("kexgss_server: BN_new failed");
-+
-+	if (BN_bin2bn(kbuf, kout, shared_secret) == NULL)
-+		fatal("kexgss_server: BN_bin2bn failed");
-+
-+	memset(kbuf, 0, klen);
-+	xfree(kbuf);
-+
-+	switch (kex->kex_type) {
-+	case KEX_GSS_GRP1_SHA1:
-+	case KEX_GSS_GRP14_SHA1:
-+		kex_dh_hash(
-+		    kex->client_version_string, kex->server_version_string,
-+		    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
-+		    buffer_ptr(&kex->my), buffer_len(&kex->my),
-+		    NULL, 0, /* Change this if we start sending host keys */
-+		    dh_client_pub, dh->pub_key, shared_secret,
-+		    &hash, &hashlen
-+		);
-+		break;
-+	case KEX_GSS_GEX_SHA1:
-+		kexgex_hash(
-+		    kex->evp_md,
-+		    kex->client_version_string, kex->server_version_string,
-+		    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
-+		    buffer_ptr(&kex->my), buffer_len(&kex->my),
-+		    NULL, 0,
-+		    min, nbits, max,
-+		    dh->p, dh->g,
-+		    dh_client_pub,
-+		    dh->pub_key,
-+		    shared_secret,
-+		    &hash, &hashlen
-+		);
-+		break;
-+	default:
-+		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
-+	}
-+
-+	BN_clear_free(dh_client_pub);
-+
-+	if (kex->session_id == NULL) {
-+		kex->session_id_len = hashlen;
-+		kex->session_id = xmalloc(kex->session_id_len);
-+		memcpy(kex->session_id, hash, kex->session_id_len);
-+	}
-+
-+	gssbuf.value = hash;
-+	gssbuf.length = hashlen;
-+
-+	if (GSS_ERROR(PRIVSEP(ssh_gssapi_sign(ctxt,&gssbuf,&msg_tok))))
-+		fatal("Couldn't get MIC");
-+
-+	packet_start(SSH2_MSG_KEXGSS_COMPLETE);
-+	packet_put_bignum2(dh->pub_key);
-+	packet_put_string(msg_tok.value,msg_tok.length);
-+
-+	if (send_tok.length != 0) {
-+		packet_put_char(1); /* true */
-+		packet_put_string(send_tok.value, send_tok.length);
-+	} else {
-+		packet_put_char(0); /* false */
-+	}
-+	packet_send();
-+
-+	gss_release_buffer(&min_status, &send_tok);
-+	gss_release_buffer(&min_status, &msg_tok);
-+
-+	if (gss_kex_context == NULL)
-+		gss_kex_context = ctxt;
-+	else 
-+		ssh_gssapi_delete_ctx(&ctxt);
-+
-+	DH_free(dh);
-+
-+	kex_derive_keys(kex, hash, hashlen, shared_secret);
-+	BN_clear_free(shared_secret);
-+	kex_finish(kex);
-+
-+	/* If this was a rekey, then save out any delegated credentials we
-+	 * just exchanged.  */
-+	if (options.gss_store_rekey)
-+		ssh_gssapi_rekey_creds();
-+}
-+#endif /* GSSAPI */
-diff --git a/key.c b/key.c
-index 498cf5a..fc65c29 100644
---- a/key.c
-+++ b/key.c
-@@ -971,6 +971,8 @@ key_ssh_name_from_type_nid(int type, int nid)
- 		}
- 		break;
- #endif /* OPENSSL_HAS_ECC */
-+	case KEY_NULL:
-+		return "null";
- 	}
- 	return "ssh-unknown";
- }
-@@ -1276,6 +1278,8 @@ key_type_from_name(char *name)
- 	    strcmp(name, "ecdsa-sha2-nistp521-cert-v01 at openssh.com") == 0) {
- 		return KEY_ECDSA_CERT;
- #endif
-+	} else if (strcmp(name, "null") == 0) {
-+		return KEY_NULL;
- 	}
- 
- 	debug2("key_type_from_name: unknown key type '%s'", name);
-diff --git a/key.h b/key.h
-index ec5ac5e..8b5c565 100644
---- a/key.h
-+++ b/key.h
-@@ -44,6 +44,7 @@ enum types {
- 	KEY_ECDSA_CERT,
- 	KEY_RSA_CERT_V00,
- 	KEY_DSA_CERT_V00,
-+	KEY_NULL,
- 	KEY_UNSPEC
- };
- enum fp_type {
-diff --git a/monitor.c b/monitor.c
-index a166fed..2d46b7b 100644
---- a/monitor.c
-+++ b/monitor.c
-@@ -180,6 +180,8 @@ int mm_answer_gss_setup_ctx(int, Buffer *);
- int mm_answer_gss_accept_ctx(int, Buffer *);
- int mm_answer_gss_userok(int, Buffer *);
- int mm_answer_gss_checkmic(int, Buffer *);
-+int mm_answer_gss_sign(int, Buffer *);
-+int mm_answer_gss_updatecreds(int, Buffer *);
- #endif
- 
- #ifdef SSH_AUDIT_EVENTS
-@@ -251,6 +253,7 @@ struct mon_table mon_dispatch_proto20[] = {
-     {MONITOR_REQ_GSSSTEP, MON_ISAUTH, mm_answer_gss_accept_ctx},
-     {MONITOR_REQ_GSSUSEROK, MON_AUTH, mm_answer_gss_userok},
-     {MONITOR_REQ_GSSCHECKMIC, MON_ISAUTH, mm_answer_gss_checkmic},
-+    {MONITOR_REQ_GSSSIGN, MON_ONCE, mm_answer_gss_sign},
- #endif
- #ifdef JPAKE
-     {MONITOR_REQ_JPAKE_GET_PWDATA, MON_ONCE, mm_answer_jpake_get_pwdata},
-@@ -263,6 +266,12 @@ struct mon_table mon_dispatch_proto20[] = {
- };
- 
- struct mon_table mon_dispatch_postauth20[] = {
-+#ifdef GSSAPI
-+    {MONITOR_REQ_GSSSETUP, 0, mm_answer_gss_setup_ctx},
-+    {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
-+    {MONITOR_REQ_GSSSIGN, 0, mm_answer_gss_sign},
-+    {MONITOR_REQ_GSSUPCREDS, 0, mm_answer_gss_updatecreds},
-+#endif
-     {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
-     {MONITOR_REQ_SIGN, 0, mm_answer_sign},
-     {MONITOR_REQ_PTY, 0, mm_answer_pty},
-@@ -371,6 +380,10 @@ monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor)
- 		/* Permit requests for moduli and signatures */
- 		monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
- 		monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
-+#ifdef GSSAPI
-+		/* and for the GSSAPI key exchange */
-+		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSETUP, 1);
-+#endif
- 	} else {
- 		mon_dispatch = mon_dispatch_proto15;
- 
-@@ -468,6 +481,10 @@ monitor_child_postauth(struct monitor *pmonitor)
- 		monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
- 		monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
- 		monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
-+#ifdef GSSAPI
-+		/* and for the GSSAPI key exchange */
-+		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSETUP, 1);
-+#endif		
- 	} else {
- 		mon_dispatch = mon_dispatch_postauth15;
- 		monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
-@@ -1802,6 +1819,13 @@ mm_get_kex(Buffer *m)
- 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
- 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
- 	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
-+#ifdef GSSAPI
-+	if (options.gss_keyex) {
-+		kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
-+		kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
-+		kex->kex[KEX_GSS_GEX_SHA1] = kexgss_server;
-+	}
-+#endif
- 	kex->server = 1;
- 	kex->hostkey_type = buffer_get_int(m);
- 	kex->kex_type = buffer_get_int(m);
-@@ -2008,6 +2032,9 @@ mm_answer_gss_setup_ctx(int sock, Buffer *m)
- 	OM_uint32 major;
- 	u_int len;
- 
-+	if (!options.gss_authentication && !options.gss_keyex)
-+		fatal("In GSSAPI monitor when GSSAPI is disabled");
-+
- 	goid.elements = buffer_get_string(m, &len);
- 	goid.length = len;
- 
-@@ -2035,6 +2062,9 @@ mm_answer_gss_accept_ctx(int sock, Buffer *m)
- 	OM_uint32 flags = 0; /* GSI needs this */
- 	u_int len;
- 
-+	if (!options.gss_authentication && !options.gss_keyex)
-+		fatal("In GSSAPI monitor when GSSAPI is disabled");
-+
- 	in.value = buffer_get_string(m, &len);
- 	in.length = len;
- 	major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
-@@ -2052,6 +2082,7 @@ mm_answer_gss_accept_ctx(int sock, Buffer *m)
- 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
- 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
- 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
-+		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSIGN, 1);
- 	}
- 	return (0);
- }
-@@ -2063,6 +2094,9 @@ mm_answer_gss_checkmic(int sock, Buffer *m)
- 	OM_uint32 ret;
- 	u_int len;
- 
-+	if (!options.gss_authentication && !options.gss_keyex)
-+		fatal("In GSSAPI monitor when GSSAPI is disabled");
-+
- 	gssbuf.value = buffer_get_string(m, &len);
- 	gssbuf.length = len;
- 	mic.value = buffer_get_string(m, &len);
-@@ -2089,7 +2123,11 @@ mm_answer_gss_userok(int sock, Buffer *m)
- {
- 	int authenticated;
- 
--	authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
-+	if (!options.gss_authentication && !options.gss_keyex)
-+		fatal("In GSSAPI monitor when GSSAPI is disabled");
-+
-+	authenticated = authctxt->valid && 
-+	    ssh_gssapi_userok(authctxt->user, authctxt->pw);
- 
- 	buffer_clear(m);
- 	buffer_put_int(m, authenticated);
-@@ -2102,6 +2140,74 @@ mm_answer_gss_userok(int sock, Buffer *m)
- 	/* Monitor loop will terminate if authenticated */
- 	return (authenticated);
- }
-+
-+int 
-+mm_answer_gss_sign(int socket, Buffer *m)
-+{
-+	gss_buffer_desc data;
-+	gss_buffer_desc hash = GSS_C_EMPTY_BUFFER;
-+	OM_uint32 major, minor;
-+	u_int len;
-+
-+	if (!options.gss_authentication && !options.gss_keyex)
-+		fatal("In GSSAPI monitor when GSSAPI is disabled");
-+
-+	data.value = buffer_get_string(m, &len);
-+	data.length = len;
-+	if (data.length != 20) 
-+		fatal("%s: data length incorrect: %d", __func__, 
-+		    (int) data.length);
-+
-+	/* Save the session ID on the first time around */
-+	if (session_id2_len == 0) {
-+		session_id2_len = data.length;
-+		session_id2 = xmalloc(session_id2_len);
-+		memcpy(session_id2, data.value, session_id2_len);
-+	}
-+	major = ssh_gssapi_sign(gsscontext, &data, &hash);
-+
-+	xfree(data.value);
-+
-+	buffer_clear(m);
-+	buffer_put_int(m, major);
-+	buffer_put_string(m, hash.value, hash.length);
-+
-+	mm_request_send(socket, MONITOR_ANS_GSSSIGN, m);
-+
-+	gss_release_buffer(&minor, &hash);
-+
-+	/* Turn on getpwnam permissions */
-+	monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
-+	
-+	/* And credential updating, for when rekeying */
-+	monitor_permit(mon_dispatch, MONITOR_REQ_GSSUPCREDS, 1);
-+
-+	return (0);
-+}
-+
-+int
-+mm_answer_gss_updatecreds(int socket, Buffer *m) {
-+	ssh_gssapi_ccache store;
-+	int ok;
-+
-+	store.filename = buffer_get_string(m, NULL);
-+	store.envvar   = buffer_get_string(m, NULL);
-+	store.envval   = buffer_get_string(m, NULL);
-+
-+	ok = ssh_gssapi_update_creds(&store);
-+
-+	xfree(store.filename);
-+	xfree(store.envvar);
-+	xfree(store.envval);
-+
-+	buffer_clear(m);
-+	buffer_put_int(m, ok);
-+
-+	mm_request_send(socket, MONITOR_ANS_GSSUPCREDS, m);
-+
-+	return(0);
-+}
-+
- #endif /* GSSAPI */
- 
- #ifdef JPAKE
-diff --git a/monitor.h b/monitor.h
-index 5e7d552..db0443f 100644
---- a/monitor.h
-+++ b/monitor.h
-@@ -53,6 +53,8 @@ enum monitor_reqtype {
- 	MONITOR_REQ_GSSSTEP, MONITOR_ANS_GSSSTEP,
- 	MONITOR_REQ_GSSUSEROK, MONITOR_ANS_GSSUSEROK,
- 	MONITOR_REQ_GSSCHECKMIC, MONITOR_ANS_GSSCHECKMIC,
-+	MONITOR_REQ_GSSSIGN, MONITOR_ANS_GSSSIGN,
-+	MONITOR_REQ_GSSUPCREDS, MONITOR_ANS_GSSUPCREDS,
- 	MONITOR_REQ_PAM_START,
- 	MONITOR_REQ_PAM_ACCOUNT, MONITOR_ANS_PAM_ACCOUNT,
- 	MONITOR_REQ_PAM_INIT_CTX, MONITOR_ANS_PAM_INIT_CTX,
-diff --git a/monitor_wrap.c b/monitor_wrap.c
-index 1f60658..fc6bbcd 100644
---- a/monitor_wrap.c
-+++ b/monitor_wrap.c
-@@ -1270,7 +1270,7 @@ mm_ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
- }
- 
- int
--mm_ssh_gssapi_userok(char *user)
-+mm_ssh_gssapi_userok(char *user, struct passwd *pw)
- {
- 	Buffer m;
- 	int authenticated = 0;
-@@ -1287,6 +1287,51 @@ mm_ssh_gssapi_userok(char *user)
- 	debug3("%s: user %sauthenticated",__func__, authenticated ? "" : "not ");
- 	return (authenticated);
- }
-+
-+OM_uint32
-+mm_ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_desc *data, gss_buffer_desc *hash)
-+{
-+	Buffer m;
-+	OM_uint32 major;
-+	u_int len;
-+
-+	buffer_init(&m);
-+	buffer_put_string(&m, data->value, data->length);
-+
-+	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSSIGN, &m);
-+	mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSSIGN, &m);
-+
-+	major = buffer_get_int(&m);
-+	hash->value = buffer_get_string(&m, &len);
-+	hash->length = len;
-+
-+	buffer_free(&m);
-+
-+	return(major);
-+}
-+
-+int
-+mm_ssh_gssapi_update_creds(ssh_gssapi_ccache *store)
-+{
-+	Buffer m;
-+	int ok;
-+
-+	buffer_init(&m);
-+
-+	buffer_put_cstring(&m, store->filename ? store->filename : "");
-+	buffer_put_cstring(&m, store->envvar ? store->envvar : "");
-+	buffer_put_cstring(&m, store->envval ? store->envval : "");
-+	
-+	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSUPCREDS, &m);
-+	mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSUPCREDS, &m);
-+
-+	ok = buffer_get_int(&m);
-+
-+	buffer_free(&m);
-+	
-+	return (ok);
-+}
-+
- #endif /* GSSAPI */
- 
- #ifdef JPAKE
-diff --git a/monitor_wrap.h b/monitor_wrap.h
-index 0c7f2e3..ec9b9b1 100644
---- a/monitor_wrap.h
-+++ b/monitor_wrap.h
-@@ -58,8 +58,10 @@ BIGNUM *mm_auth_rsa_generate_challenge(Key *);
- OM_uint32 mm_ssh_gssapi_server_ctx(Gssctxt **, gss_OID);
- OM_uint32 mm_ssh_gssapi_accept_ctx(Gssctxt *,
-    gss_buffer_desc *, gss_buffer_desc *, OM_uint32 *);
--int mm_ssh_gssapi_userok(char *user);
-+int mm_ssh_gssapi_userok(char *user, struct passwd *);
- OM_uint32 mm_ssh_gssapi_checkmic(Gssctxt *, gss_buffer_t, gss_buffer_t);
-+OM_uint32 mm_ssh_gssapi_sign(Gssctxt *, gss_buffer_t, gss_buffer_t);
-+int mm_ssh_gssapi_update_creds(ssh_gssapi_ccache *);
- #endif
- 
- #ifdef USE_PAM
-diff --git a/readconf.c b/readconf.c
-index 91dfa56..60befde 100644
---- a/readconf.c
-+++ b/readconf.c
-@@ -129,6 +129,8 @@ typedef enum {
- 	oClearAllForwardings, oNoHostAuthenticationForLocalhost,
- 	oEnableSSHKeysign, oRekeyLimit, oVerifyHostKeyDNS, oConnectTimeout,
- 	oAddressFamily, oGssAuthentication, oGssDelegateCreds,
-+	oGssTrustDns, oGssKeyEx, oGssClientIdentity, oGssRenewalRekey,
-+	oGssServerIdentity, 
- 	oServerAliveInterval, oServerAliveCountMax, oIdentitiesOnly,
- 	oSendEnv, oControlPath, oControlMaster, oControlPersist,
- 	oHashKnownHosts,
-@@ -169,10 +171,19 @@ static struct {
- 	{ "afstokenpassing", oUnsupported },
- #if defined(GSSAPI)
- 	{ "gssapiauthentication", oGssAuthentication },
-+	{ "gssapikeyexchange", oGssKeyEx },
- 	{ "gssapidelegatecredentials", oGssDelegateCreds },
-+	{ "gssapitrustdns", oGssTrustDns },
-+	{ "gssapiclientidentity", oGssClientIdentity },
-+	{ "gssapiserveridentity", oGssServerIdentity },
-+	{ "gssapirenewalforcesrekey", oGssRenewalRekey },
- #else
- 	{ "gssapiauthentication", oUnsupported },
-+	{ "gssapikeyexchange", oUnsupported },
- 	{ "gssapidelegatecredentials", oUnsupported },
-+	{ "gssapitrustdns", oUnsupported },
-+	{ "gssapiclientidentity", oUnsupported },
-+	{ "gssapirenewalforcesrekey", oUnsupported },
- #endif
- 	{ "fallbacktorsh", oDeprecated },
- 	{ "usersh", oDeprecated },
-@@ -482,10 +493,30 @@ parse_flag:
- 		intptr = &options->gss_authentication;
- 		goto parse_flag;
- 
-+	case oGssKeyEx:
-+		intptr = &options->gss_keyex;
-+		goto parse_flag;
-+
- 	case oGssDelegateCreds:
- 		intptr = &options->gss_deleg_creds;
- 		goto parse_flag;
- 
-+	case oGssTrustDns:
-+		intptr = &options->gss_trust_dns;
-+		goto parse_flag;
-+
-+	case oGssClientIdentity:
-+		charptr = &options->gss_client_identity;
-+		goto parse_string;
-+
-+	case oGssServerIdentity:
-+		charptr = &options->gss_server_identity;
-+		goto parse_string;
-+
-+	case oGssRenewalRekey:
-+		intptr = &options->gss_renewal_rekey;
-+		goto parse_flag;
-+
- 	case oBatchMode:
- 		intptr = &options->batch_mode;
- 		goto parse_flag;
-@@ -1138,7 +1169,12 @@ initialize_options(Options * options)
- 	options->pubkey_authentication = -1;
- 	options->challenge_response_authentication = -1;
- 	options->gss_authentication = -1;
-+	options->gss_keyex = -1;
- 	options->gss_deleg_creds = -1;
-+	options->gss_trust_dns = -1;
-+	options->gss_renewal_rekey = -1;
-+	options->gss_client_identity = NULL;
-+	options->gss_server_identity = NULL;
- 	options->password_authentication = -1;
- 	options->kbd_interactive_authentication = -1;
- 	options->kbd_interactive_devices = NULL;
-@@ -1238,8 +1274,14 @@ fill_default_options(Options * options)
- 		options->challenge_response_authentication = 1;
- 	if (options->gss_authentication == -1)
- 		options->gss_authentication = 0;
-+	if (options->gss_keyex == -1)
-+		options->gss_keyex = 0;
- 	if (options->gss_deleg_creds == -1)
- 		options->gss_deleg_creds = 0;
-+	if (options->gss_trust_dns == -1)
-+		options->gss_trust_dns = 0;
-+	if (options->gss_renewal_rekey == -1)
-+		options->gss_renewal_rekey = 0;
- 	if (options->password_authentication == -1)
- 		options->password_authentication = 1;
- 	if (options->kbd_interactive_authentication == -1)
-diff --git a/readconf.h b/readconf.h
-index 5944cff..617686f 100644
---- a/readconf.h
-+++ b/readconf.h
-@@ -47,7 +47,12 @@ typedef struct {
- 	int     challenge_response_authentication;
- 					/* Try S/Key or TIS, authentication. */
- 	int     gss_authentication;	/* Try GSS authentication */
-+	int     gss_keyex;		/* Try GSS key exchange */
- 	int     gss_deleg_creds;	/* Delegate GSS credentials */
-+	int	gss_trust_dns;		/* Trust DNS for GSS canonicalization */
-+	int	gss_renewal_rekey;	/* Credential renewal forces rekey */
-+	char    *gss_client_identity;   /* Principal to initiate GSSAPI with */
-+	char    *gss_server_identity;   /* GSSAPI target principal */
- 	int     password_authentication;	/* Try password
- 						 * authentication. */
- 	int     kbd_interactive_authentication; /* Try keyboard-interactive auth. */
-diff --git a/servconf.c b/servconf.c
-index 91986e5..756a3a2 100644
---- a/servconf.c
-+++ b/servconf.c
-@@ -97,7 +97,10 @@ initialize_server_options(ServerOptions *options)
- 	options->kerberos_ticket_cleanup = -1;
- 	options->kerberos_get_afs_token = -1;
- 	options->gss_authentication=-1;
-+	options->gss_keyex = -1;
- 	options->gss_cleanup_creds = -1;
-+	options->gss_strict_acceptor = -1;
-+	options->gss_store_rekey = -1;
- 	options->password_authentication = -1;
- 	options->kbd_interactive_authentication = -1;
- 	options->challenge_response_authentication = -1;
-@@ -225,8 +228,14 @@ fill_default_server_options(ServerOptions *options)
- 		options->kerberos_get_afs_token = 0;
- 	if (options->gss_authentication == -1)
- 		options->gss_authentication = 0;
-+	if (options->gss_keyex == -1)
-+		options->gss_keyex = 0;
- 	if (options->gss_cleanup_creds == -1)
- 		options->gss_cleanup_creds = 1;
-+	if (options->gss_strict_acceptor == -1)
-+		options->gss_strict_acceptor = 1;
-+	if (options->gss_store_rekey == -1)
-+		options->gss_store_rekey = 0;
- 	if (options->password_authentication == -1)
- 		options->password_authentication = 1;
- 	if (options->kbd_interactive_authentication == -1)
-@@ -318,7 +327,9 @@ typedef enum {
- 	sBanner, sUseDNS, sHostbasedAuthentication,
- 	sHostbasedUsesNameFromPacketOnly, sClientAliveInterval,
- 	sClientAliveCountMax, sAuthorizedKeysFile,
--	sGssAuthentication, sGssCleanupCreds, sAcceptEnv, sPermitTunnel,
-+ 	sGssAuthentication, sGssCleanupCreds, sGssStrictAcceptor,
-+ 	sGssKeyEx, sGssStoreRekey,
-+ 	sAcceptEnv, sPermitTunnel,
- 	sMatch, sPermitOpen, sForceCommand, sChrootDirectory,
- 	sUsePrivilegeSeparation, sAllowAgentForwarding,
- 	sZeroKnowledgePasswordAuthentication, sHostCertificate,
-@@ -382,10 +393,20 @@ static struct {
- #ifdef GSSAPI
- 	{ "gssapiauthentication", sGssAuthentication, SSHCFG_ALL },
- 	{ "gssapicleanupcredentials", sGssCleanupCreds, SSHCFG_GLOBAL },
-+	{ "gssapicleanupcreds", sGssCleanupCreds, SSHCFG_GLOBAL },
-+	{ "gssapistrictacceptorcheck", sGssStrictAcceptor, SSHCFG_GLOBAL },
-+	{ "gssapikeyexchange", sGssKeyEx, SSHCFG_GLOBAL },
-+	{ "gssapistorecredentialsonrekey", sGssStoreRekey, SSHCFG_GLOBAL },
- #else
- 	{ "gssapiauthentication", sUnsupported, SSHCFG_ALL },
- 	{ "gssapicleanupcredentials", sUnsupported, SSHCFG_GLOBAL },
-+	{ "gssapicleanupcreds", sUnsupported, SSHCFG_GLOBAL },
-+	{ "gssapistrictacceptorcheck", sUnsupported, SSHCFG_GLOBAL },
-+	{ "gssapikeyexchange", sUnsupported, SSHCFG_GLOBAL },
-+	{ "gssapistorecredentialsonrekey", sUnsupported, SSHCFG_GLOBAL },
- #endif
-+	{ "gssusesessionccache", sUnsupported, SSHCFG_GLOBAL },
-+	{ "gssapiusesessioncredcache", sUnsupported, SSHCFG_GLOBAL },
- 	{ "passwordauthentication", sPasswordAuthentication, SSHCFG_ALL },
- 	{ "kbdinteractiveauthentication", sKbdInteractiveAuthentication, SSHCFG_ALL },
- 	{ "challengeresponseauthentication", sChallengeResponseAuthentication, SSHCFG_GLOBAL },
-@@ -962,10 +983,22 @@ process_server_config_line(ServerOptions *options, char *line,
- 		intptr = &options->gss_authentication;
- 		goto parse_flag;
- 
-+	case sGssKeyEx:
-+		intptr = &options->gss_keyex;
-+		goto parse_flag;
-+
- 	case sGssCleanupCreds:
- 		intptr = &options->gss_cleanup_creds;
- 		goto parse_flag;
- 
-+	case sGssStrictAcceptor:
-+		intptr = &options->gss_strict_acceptor;
-+		goto parse_flag;
-+
-+	case sGssStoreRekey:
-+		intptr = &options->gss_store_rekey;
-+		goto parse_flag;
-+
- 	case sPasswordAuthentication:
- 		intptr = &options->password_authentication;
- 		goto parse_flag;
-@@ -1720,7 +1753,10 @@ dump_config(ServerOptions *o)
- #endif
- #ifdef GSSAPI
- 	dump_cfg_fmtint(sGssAuthentication, o->gss_authentication);
-+	dump_cfg_fmtint(sGssKeyEx, o->gss_keyex);
- 	dump_cfg_fmtint(sGssCleanupCreds, o->gss_cleanup_creds);
-+	dump_cfg_fmtint(sGssStrictAcceptor, o->gss_strict_acceptor);
-+	dump_cfg_fmtint(sGssStoreRekey, o->gss_store_rekey);
- #endif
- #ifdef JPAKE
- 	dump_cfg_fmtint(sZeroKnowledgePasswordAuthentication,
-diff --git a/servconf.h b/servconf.h
-index 89f38e2..a434c6f 100644
---- a/servconf.h
-+++ b/servconf.h
-@@ -103,7 +103,10 @@ typedef struct {
- 	int     kerberos_get_afs_token;		/* If true, try to get AFS token if
- 						 * authenticated with Kerberos. */
- 	int     gss_authentication;	/* If true, permit GSSAPI authentication */
-+	int     gss_keyex;		/* If true, permit GSSAPI key exchange */
- 	int     gss_cleanup_creds;	/* If true, destroy cred cache on logout */
-+	int 	gss_strict_acceptor;	/* If true, restrict the GSSAPI acceptor name */
-+	int 	gss_store_rekey;
- 	int     password_authentication;	/* If true, permit password
- 						 * authentication. */
- 	int     kbd_interactive_authentication;	/* If true, permit */
-diff --git a/ssh-gss.h b/ssh-gss.h
-index c29a1b7..31d5a08 100644
---- a/ssh-gss.h
-+++ b/ssh-gss.h
-@@ -1,6 +1,6 @@
- /* $OpenBSD: ssh-gss.h,v 1.10 2007/06/12 08:20:00 djm Exp $ */
- /*
-- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
-+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
-  *
-  * Redistribution and use in source and binary forms, with or without
-  * modification, are permitted provided that the following conditions
-@@ -60,10 +60,22 @@
- 
- #define SSH_GSS_OIDTYPE 0x06
- 
-+#define SSH2_MSG_KEXGSS_INIT                            30
-+#define SSH2_MSG_KEXGSS_CONTINUE                        31
-+#define SSH2_MSG_KEXGSS_COMPLETE                        32
-+#define SSH2_MSG_KEXGSS_HOSTKEY                         33
-+#define SSH2_MSG_KEXGSS_ERROR                           34
-+#define SSH2_MSG_KEXGSS_GROUPREQ			40
-+#define SSH2_MSG_KEXGSS_GROUP				41
-+#define KEX_GSS_GRP1_SHA1_ID				"gss-group1-sha1-"
-+#define KEX_GSS_GRP14_SHA1_ID				"gss-group14-sha1-"
-+#define KEX_GSS_GEX_SHA1_ID				"gss-gex-sha1-"
-+
- typedef struct {
- 	char *filename;
- 	char *envvar;
- 	char *envval;
-+	struct passwd *owner;
- 	void *data;
- } ssh_gssapi_ccache;
- 
-@@ -71,8 +83,11 @@ typedef struct {
- 	gss_buffer_desc displayname;
- 	gss_buffer_desc exportedname;
- 	gss_cred_id_t creds;
-+	gss_name_t name;
- 	struct ssh_gssapi_mech_struct *mech;
- 	ssh_gssapi_ccache store;
-+	int used;
-+	int updated;
- } ssh_gssapi_client;
- 
- typedef struct ssh_gssapi_mech_struct {
-@@ -83,6 +98,7 @@ typedef struct ssh_gssapi_mech_struct {
- 	int (*userok) (ssh_gssapi_client *, char *);
- 	int (*localname) (ssh_gssapi_client *, char **);
- 	void (*storecreds) (ssh_gssapi_client *);
-+	int (*updatecreds) (ssh_gssapi_ccache *, ssh_gssapi_client *);
- } ssh_gssapi_mech;
- 
- typedef struct {
-@@ -93,10 +109,11 @@ typedef struct {
- 	gss_OID		oid; /* client */
- 	gss_cred_id_t	creds; /* server */
- 	gss_name_t	client; /* server */
--	gss_cred_id_t	client_creds; /* server */
-+	gss_cred_id_t	client_creds; /* both */
- } Gssctxt;
- 
- extern ssh_gssapi_mech *supported_mechs[];
-+extern Gssctxt *gss_kex_context;
- 
- int  ssh_gssapi_check_oid(Gssctxt *, void *, size_t);
- void ssh_gssapi_set_oid_data(Gssctxt *, void *, size_t);
-@@ -116,16 +133,30 @@ void ssh_gssapi_build_ctx(Gssctxt **);
- void ssh_gssapi_delete_ctx(Gssctxt **);
- OM_uint32 ssh_gssapi_sign(Gssctxt *, gss_buffer_t, gss_buffer_t);
- void ssh_gssapi_buildmic(Buffer *, const char *, const char *, const char *);
--int ssh_gssapi_check_mechanism(Gssctxt **, gss_OID, const char *);
-+int ssh_gssapi_check_mechanism(Gssctxt **, gss_OID, const char *, const char *);
-+OM_uint32 ssh_gssapi_client_identity(Gssctxt *, const char *);
-+int ssh_gssapi_credentials_updated(Gssctxt *);
- 
- /* In the server */
-+typedef int ssh_gssapi_check_fn(Gssctxt **, gss_OID, const char *, 
-+    const char *);
-+char *ssh_gssapi_client_mechanisms(const char *, const char *);
-+char *ssh_gssapi_kex_mechs(gss_OID_set, ssh_gssapi_check_fn *, const char *,
-+    const char *);
-+gss_OID ssh_gssapi_id_kex(Gssctxt *, char *, int);
-+int ssh_gssapi_server_check_mech(Gssctxt **,gss_OID, const char *, 
-+    const char *);
- OM_uint32 ssh_gssapi_server_ctx(Gssctxt **, gss_OID);
--int ssh_gssapi_userok(char *name);
-+int ssh_gssapi_userok(char *name, struct passwd *);
- OM_uint32 ssh_gssapi_checkmic(Gssctxt *, gss_buffer_t, gss_buffer_t);
- void ssh_gssapi_do_child(char ***, u_int *);
- void ssh_gssapi_cleanup_creds(void);
- void ssh_gssapi_storecreds(void);
- 
-+char *ssh_gssapi_server_mechanisms(void);
-+int ssh_gssapi_oid_table_ok();
-+
-+int ssh_gssapi_update_creds(ssh_gssapi_ccache *store);
- #endif /* GSSAPI */
- 
- #endif /* _SSH_GSS_H */
-diff --git a/ssh_config b/ssh_config
-index 1893674..2c06ba7 100644
---- a/ssh_config
-+++ b/ssh_config
-@@ -26,6 +26,8 @@
- #   HostbasedAuthentication no
- #   GSSAPIAuthentication no
- #   GSSAPIDelegateCredentials no
-+#   GSSAPIKeyExchange no
-+#   GSSAPITrustDNS no
- #   BatchMode no
- #   CheckHostIP yes
- #   AddressFamily any
-diff --git a/ssh_config.5 b/ssh_config.5
-index a782d6f..9e1e9a6 100644
---- a/ssh_config.5
-+++ b/ssh_config.5
-@@ -527,11 +527,43 @@ Specifies whether user authentication based on GSSAPI is allowed.
- The default is
- .Dq no .
- Note that this option applies to protocol version 2 only.
-+.It Cm GSSAPIKeyExchange
-+Specifies whether key exchange based on GSSAPI may be used. When using
-+GSSAPI key exchange the server need not have a host key.
-+The default is
-+.Dq no .
-+Note that this option applies to protocol version 2 only.
-+.It Cm GSSAPIClientIdentity
-+If set, specifies the GSSAPI client identity that ssh should use when 
-+connecting to the server. The default is unset, which means that the default 
-+identity will be used.
-+.It Cm GSSAPIServerIdentity
-+If set, specifies the GSSAPI server identity that ssh should expect when 
-+connecting to the server. The default is unset, which means that the
-+expected GSSAPI server identity will be determined from the target
-+hostname.
- .It Cm GSSAPIDelegateCredentials
- Forward (delegate) credentials to the server.
- The default is
- .Dq no .
--Note that this option applies to protocol version 2 only.
-+Note that this option applies to protocol version 2 connections using GSSAPI.
-+.It Cm GSSAPIRenewalForcesRekey
-+If set to 
-+.Dq yes
-+then renewal of the client's GSSAPI credentials will force the rekeying of the
-+ssh connection. With a compatible server, this can delegate the renewed 
-+credentials to a session on the server.
-+The default is
-+.Dq no .
-+.It Cm GSSAPITrustDns
-+Set to 
-+.Dq yes to indicate that the DNS is trusted to securely canonicalize
-+the name of the host being connected to. If 
-+.Dq no, the hostname entered on the
-+command line will be passed untouched to the GSSAPI library.
-+The default is
-+.Dq no .
-+This option only applies to protocol version 2 connections using GSSAPI.
- .It Cm HashKnownHosts
- Indicates that
- .Xr ssh 1
-diff --git a/sshconnect2.c b/sshconnect2.c
-index c24b202..3ddef32 100644
---- a/sshconnect2.c
-+++ b/sshconnect2.c
-@@ -160,9 +160,34 @@ ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
- {
- 	Kex *kex;
- 
-+#ifdef GSSAPI
-+	char *orig = NULL, *gss = NULL;
-+	char *gss_host = NULL;
-+#endif
-+
- 	xxx_host = host;
- 	xxx_hostaddr = hostaddr;
- 
-+#ifdef GSSAPI
-+	if (options.gss_keyex) {
-+		/* Add the GSSAPI mechanisms currently supported on this 
-+		 * client to the key exchange algorithm proposal */
-+		orig = myproposal[PROPOSAL_KEX_ALGS];
-+
-+		if (options.gss_trust_dns)
-+			gss_host = (char *)get_canonical_hostname(1);
-+		else
-+			gss_host = host;
-+
-+		gss = ssh_gssapi_client_mechanisms(gss_host, options.gss_client_identity);
-+		if (gss) {
-+			debug("Offering GSSAPI proposal: %s", gss);
-+			xasprintf(&myproposal[PROPOSAL_KEX_ALGS],
-+			    "%s,%s", gss, orig);
-+		}
-+	}
-+#endif
-+
- 	if (options.ciphers == (char *)-1) {
- 		logit("No valid ciphers for protocol version 2 given, using defaults.");
- 		options.ciphers = NULL;
-@@ -197,6 +222,17 @@ ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
- 	if (options.kex_algorithms != NULL)
- 		myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
- 
-+#ifdef GSSAPI
-+	/* If we've got GSSAPI algorithms, then we also support the
-+	 * 'null' hostkey, as a last resort */
-+	if (options.gss_keyex && gss) {
-+		orig = myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS];
-+		xasprintf(&myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS], 
-+		    "%s,null", orig);
-+		xfree(gss);
-+	}
-+#endif
-+
- 	if (options.rekey_limit)
- 		packet_set_rekey_limit((u_int32_t)options.rekey_limit);
- 
-@@ -207,10 +243,30 @@ ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
- 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
- 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
- 	kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
-+#ifdef GSSAPI
-+	if (options.gss_keyex) {
-+		kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_client;
-+		kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_client;
-+		kex->kex[KEX_GSS_GEX_SHA1] = kexgss_client;
-+	}
-+#endif
- 	kex->client_version_string=client_version_string;
- 	kex->server_version_string=server_version_string;
- 	kex->verify_host_key=&verify_host_key_callback;
- 
-+#ifdef GSSAPI
-+	if (options.gss_keyex) {
-+		kex->gss_deleg_creds = options.gss_deleg_creds;
-+		kex->gss_trust_dns = options.gss_trust_dns;
-+		kex->gss_client = options.gss_client_identity;
-+		if (options.gss_server_identity) {
-+			kex->gss_host = options.gss_server_identity;
-+		} else {
-+			kex->gss_host = gss_host;
-+        }
-+	}
-+#endif
-+
- 	xxx_kex = kex;
- 
- 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
-@@ -305,6 +361,7 @@ void	input_gssapi_token(int type, u_int32_t, void *);
- void	input_gssapi_hash(int type, u_int32_t, void *);
- void	input_gssapi_error(int, u_int32_t, void *);
- void	input_gssapi_errtok(int, u_int32_t, void *);
-+int	userauth_gsskeyex(Authctxt *authctxt);
- #endif
- 
- void	userauth(Authctxt *, char *);
-@@ -320,6 +377,11 @@ static char *authmethods_get(void);
- 
- Authmethod authmethods[] = {
- #ifdef GSSAPI
-+	{"gssapi-keyex",
-+		userauth_gsskeyex,
-+		NULL,
-+		&options.gss_authentication,
-+		NULL},
- 	{"gssapi-with-mic",
- 		userauth_gssapi,
- 		NULL,
-@@ -626,19 +688,31 @@ userauth_gssapi(Authctxt *authctxt)
- 	static u_int mech = 0;
- 	OM_uint32 min;
- 	int ok = 0;
-+	const char *gss_host;
-+
-+	if (options.gss_server_identity)
-+		gss_host = options.gss_server_identity;
-+	else if (options.gss_trust_dns)
-+		gss_host = get_canonical_hostname(1);
-+	else
-+		gss_host = authctxt->host;
- 
- 	/* Try one GSSAPI method at a time, rather than sending them all at
- 	 * once. */
- 
- 	if (gss_supported == NULL)
--		gss_indicate_mechs(&min, &gss_supported);
-+		if (GSS_ERROR(gss_indicate_mechs(&min, &gss_supported))) {
-+			gss_supported = NULL;
-+			return 0;
-+		}
- 
- 	/* Check to see if the mechanism is usable before we offer it */
- 	while (mech < gss_supported->count && !ok) {
- 		/* My DER encoding requires length<128 */
- 		if (gss_supported->elements[mech].length < 128 &&
- 		    ssh_gssapi_check_mechanism(&gssctxt, 
--		    &gss_supported->elements[mech], authctxt->host)) {
-+		    &gss_supported->elements[mech], gss_host, 
-+                    options.gss_client_identity)) {
- 			ok = 1; /* Mechanism works */
- 		} else {
- 			mech++;
-@@ -735,8 +809,8 @@ input_gssapi_response(int type, u_int32_t plen, void *ctxt)
- {
- 	Authctxt *authctxt = ctxt;
- 	Gssctxt *gssctxt;
--	int oidlen;
--	char *oidv;
-+	u_int oidlen;
-+	u_char *oidv;
- 
- 	if (authctxt == NULL)
- 		fatal("input_gssapi_response: no authentication context");
-@@ -846,6 +920,48 @@ input_gssapi_error(int type, u_int32_t plen, void *ctxt)
- 	xfree(msg);
- 	xfree(lang);
- }
-+
-+int
-+userauth_gsskeyex(Authctxt *authctxt)
-+{
-+	Buffer b;
-+	gss_buffer_desc gssbuf;
-+	gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
-+	OM_uint32 ms;
-+
-+	static int attempt = 0;
-+	if (attempt++ >= 1)
-+		return (0);
-+
-+	if (gss_kex_context == NULL) {
-+		debug("No valid Key exchange context"); 
-+		return (0);
-+	}
-+
-+	ssh_gssapi_buildmic(&b, authctxt->server_user, authctxt->service,
-+	    "gssapi-keyex");
-+
-+	gssbuf.value = buffer_ptr(&b);
-+	gssbuf.length = buffer_len(&b);
-+
-+	if (GSS_ERROR(ssh_gssapi_sign(gss_kex_context, &gssbuf, &mic))) {
-+		buffer_free(&b);
-+		return (0);
-+	}
-+
-+	packet_start(SSH2_MSG_USERAUTH_REQUEST);
-+	packet_put_cstring(authctxt->server_user);
-+	packet_put_cstring(authctxt->service);
-+	packet_put_cstring(authctxt->method->name);
-+	packet_put_string(mic.value, mic.length);
-+	packet_send();
-+
-+	buffer_free(&b);
-+	gss_release_buffer(&ms, &mic);
-+
-+	return (1);
-+}
-+
- #endif /* GSSAPI */
- 
- int
-diff --git a/sshd.c b/sshd.c
-index cc10395..112a5f9 100644
---- a/sshd.c
-+++ b/sshd.c
-@@ -121,6 +121,10 @@
- #include "ssh-sandbox.h"
- #include "version.h"
- 
-+#ifdef USE_SECURITY_SESSION_API
-+#include <Security/AuthSession.h>
-+#endif
-+
- #ifdef LIBWRAP
- #include <tcpd.h>
- #include <syslog.h>
-@@ -1612,10 +1616,13 @@ main(int ac, char **av)
- 		logit("Disabling protocol version 1. Could not load host key");
- 		options.protocol &= ~SSH_PROTO_1;
- 	}
-+#ifndef GSSAPI
-+	/* The GSSAPI key exchange can run without a host key */
- 	if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
- 		logit("Disabling protocol version 2. Could not load host key");
- 		options.protocol &= ~SSH_PROTO_2;
- 	}
-+#endif
- 	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
- 		logit("sshd: no hostkeys available -- exiting.");
- 		exit(1);
-@@ -1944,6 +1951,60 @@ main(int ac, char **av)
- 	/* Log the connection. */
- 	verbose("Connection from %.500s port %d", remote_ip, remote_port);
- 
-+#ifdef USE_SECURITY_SESSION_API
-+	/*
-+	 * Create a new security session for use by the new user login if
-+	 * the current session is the root session or we are not launched
-+	 * by inetd (eg: debugging mode or server mode).  We do not
-+	 * necessarily need to create a session if we are launched from
-+	 * inetd because Panther xinetd will create a session for us.
-+	 *
-+	 * The only case where this logic will fail is if there is an
-+	 * inetd running in a non-root session which is not creating
-+	 * new sessions for us.  Then all the users will end up in the
-+	 * same session (bad).
-+	 *
-+	 * When the client exits, the session will be destroyed for us
-+	 * automatically.
-+	 *
-+	 * We must create the session before any credentials are stored
-+	 * (including AFS pags, which happens a few lines below).
-+	 */
-+	{
-+		OSStatus err = 0;
-+		SecuritySessionId sid = 0;
-+		SessionAttributeBits sattrs = 0;
-+
-+		err = SessionGetInfo(callerSecuritySession, &sid, &sattrs);
-+		if (err)
-+			error("SessionGetInfo() failed with error %.8X",
-+			    (unsigned) err);
-+		else
-+			debug("Current Session ID is %.8X / Session Attributes are %.8X",
-+			    (unsigned) sid, (unsigned) sattrs);
-+
-+		if (inetd_flag && !(sattrs & sessionIsRoot))
-+			debug("Running in inetd mode in a non-root session... "
-+			    "assuming inetd created the session for us.");
-+		else {
-+			debug("Creating new security session...");
-+			err = SessionCreate(0, sessionHasTTY | sessionIsRemote);
-+			if (err)
-+				error("SessionCreate() failed with error %.8X",
-+				    (unsigned) err);
-+
-+			err = SessionGetInfo(callerSecuritySession, &sid, 
-+			    &sattrs);
-+			if (err)
-+				error("SessionGetInfo() failed with error %.8X",
-+				    (unsigned) err);
-+			else
-+				debug("New Session ID is %.8X / Session Attributes are %.8X",
-+				    (unsigned) sid, (unsigned) sattrs);
-+		}
-+	}
-+#endif
-+
- 	/*
- 	 * We don't want to listen forever unless the other side
- 	 * successfully authenticates itself.  So we set up an alarm which is
-@@ -2325,6 +2386,48 @@ do_ssh2_kex(void)
- 
- 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
- 
-+#ifdef GSSAPI
-+	{
-+	char *orig;
-+	char *gss = NULL;
-+	char *newstr = NULL;
-+	orig = myproposal[PROPOSAL_KEX_ALGS];
-+
-+	/* 
-+	 * If we don't have a host key, then there's no point advertising
-+	 * the other key exchange algorithms
-+	 */
-+
-+	if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]) == 0)
-+		orig = NULL;
-+
-+	if (options.gss_keyex)
-+		gss = ssh_gssapi_server_mechanisms();
-+	else
-+		gss = NULL;
-+
-+	if (gss && orig)
-+		xasprintf(&newstr, "%s,%s", gss, orig);
-+	else if (gss)
-+		newstr = gss;
-+	else if (orig)
-+		newstr = orig;
-+
-+	/* 
-+	 * If we've got GSSAPI mechanisms, then we've got the 'null' host
-+	 * key alg, but we can't tell people about it unless its the only
-+  	 * host key algorithm we support
-+	 */
-+	if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0)
-+		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = "null";
-+
-+	if (newstr)
-+		myproposal[PROPOSAL_KEX_ALGS] = newstr;
-+	else
-+		fatal("No supported key exchange algorithms");
-+	}
-+#endif
-+
- 	/* start key exchange */
- 	kex = kex_setup(myproposal);
- 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
-@@ -2332,6 +2435,13 @@ do_ssh2_kex(void)
- 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
- 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
- 	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
-+#ifdef GSSAPI
-+	if (options.gss_keyex) {
-+		kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
-+		kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
-+		kex->kex[KEX_GSS_GEX_SHA1] = kexgss_server;
-+	}
-+#endif
- 	kex->server = 1;
- 	kex->client_version_string=client_version_string;
- 	kex->server_version_string=server_version_string;
-diff --git a/sshd_config b/sshd_config
-index 473e866..d02d7a7 100644
---- a/sshd_config
-+++ b/sshd_config
-@@ -75,6 +75,8 @@ AuthorizedKeysFile	.ssh/authorized_keys
- # GSSAPI options
- #GSSAPIAuthentication no
- #GSSAPICleanupCredentials yes
-+#GSSAPIStrictAcceptorCheck yes
-+#GSSAPIKeyExchange no
- 
- # Set this to 'yes' to enable PAM authentication, account processing, 
- # and session processing. If this is enabled, PAM authentication will 
-diff --git a/sshd_config.5 b/sshd_config.5
-index a6c3787..76c95aa 100644
---- a/sshd_config.5
-+++ b/sshd_config.5
-@@ -424,12 +424,40 @@ Specifies whether user authentication based on GSSAPI is allowed.
- The default is
- .Dq no .
- Note that this option applies to protocol version 2 only.
-+.It Cm GSSAPIKeyExchange
-+Specifies whether key exchange based on GSSAPI is allowed. GSSAPI key exchange
-+doesn't rely on ssh keys to verify host identity.
-+The default is
-+.Dq no .
-+Note that this option applies to protocol version 2 only.
- .It Cm GSSAPICleanupCredentials
- Specifies whether to automatically destroy the user's credentials cache
- on logout.
- The default is
- .Dq yes .
- Note that this option applies to protocol version 2 only.
-+.It Cm GSSAPIStrictAcceptorCheck
-+Determines whether to be strict about the identity of the GSSAPI acceptor 
-+a client authenticates against. If
-+.Dq yes
-+then the client must authenticate against the
-+.Pa host
-+service on the current hostname. If 
-+.Dq no
-+then the client may authenticate against any service key stored in the 
-+machine's default store. This facility is provided to assist with operation 
-+on multi homed machines. 
-+The default is
-+.Dq yes .
-+Note that this option applies only to protocol version 2 GSSAPI connections,
-+and setting it to 
-+.Dq no
-+may only work with recent Kerberos GSSAPI libraries.
-+.It Cm GSSAPIStoreCredentialsOnRekey
-+Controls whether the user's GSSAPI credentials should be updated following a 
-+successful connection rekeying. This option can be used to accepted renewed 
-+or updated credentials from a compatible client. The default is
-+.Dq no .
- .It Cm HostbasedAuthentication
- Specifies whether rhosts or /etc/hosts.equiv authentication together
- with successful public key client host authentication is allowed
--- 
-1.7.6.1
-

Added: trunk/dports/net/openssh/files/openssh-6.2p2-gsskex-all-20110125.patch
===================================================================
--- trunk/dports/net/openssh/files/openssh-6.2p2-gsskex-all-20110125.patch	                        (rev 0)
+++ trunk/dports/net/openssh/files/openssh-6.2p2-gsskex-all-20110125.patch	2013-07-20 16:53:18 UTC (rev 108349)
@@ -0,0 +1,2992 @@
+commit c2f0a172fa9eadec04b92296707764db7887b45e
+Author: Bryan Drewery <bryan at shatow.net>
+Date:   Sat May 25 10:33:10 2013 -0500
+
+    KEX PATCH
+
+diff --git ChangeLog.gssapi ChangeLog.gssapi
+new file mode 100644
+index 0000000..f117a33
+--- /dev/null
++++ ChangeLog.gssapi
+@@ -0,0 +1,113 @@
++20110101
++  - Finally update for OpenSSH 5.6p1
++  - Add GSSAPIServerIdentity option from Jim Basney
++ 
++20100308
++  - [ Makefile.in, key.c, key.h ]
++    Updates for OpenSSH 5.4p1
++  - [ servconf.c ]
++    Include GSSAPI options in the sshd -T configuration dump, and flag
++    some older configuration options as being unsupported. Thanks to Colin 
++    Watson.
++  -
++
++20100124
++  - [ sshconnect2.c ]
++    Adapt to deal with additional element in Authmethod structure. Thanks to
++    Colin Watson
++
++20090615
++  - [ gss-genr.c gss-serv.c kexgssc.c kexgsss.c monitor.c sshconnect2.c
++      sshd.c ]
++    Fix issues identified by Greg Hudson following a code review
++	Check return value of gss_indicate_mechs
++	Protect GSSAPI calls in monitor, so they can only be used if enabled
++	Check return values of bignum functions in key exchange
++	Use BN_clear_free to clear other side's DH value
++	Make ssh_gssapi_id_kex more robust
++	Only configure kex table pointers if GSSAPI is enabled
++	Don't leak mechanism list, or gss mechanism list
++	Cast data.length before printing
++	If serverkey isn't provided, use an empty string, rather than NULL
++
++20090201
++  - [ gss-genr.c gss-serv.c kex.h kexgssc.c readconf.c readconf.h ssh-gss.h
++      ssh_config.5 sshconnet2.c ]
++    Add support for the GSSAPIClientIdentity option, which allows the user
++    to specify which GSSAPI identity to use to contact a given server
++
++20080404
++  - [ gss-serv.c ]
++    Add code to actually implement GSSAPIStrictAcceptCheck, which had somehow
++    been omitted from a previous version of this patch. Reported by Borislav
++    Stoichkov
++
++20070317
++  - [ gss-serv-krb5.c ]
++    Remove C99ism, where new_ccname was being declared in the middle of a 
++    function
++
++20061220
++  - [ servconf.c ]
++    Make default for GSSAPIStrictAcceptorCheck be Yes, to match previous, and 
++    documented, behaviour. Reported by Dan Watson.
++
++20060910
++  - [ gss-genr.c kexgssc.c kexgsss.c kex.h monitor.c sshconnect2.c sshd.c
++      ssh-gss.h ]
++    add support for gss-group14-sha1 key exchange mechanisms
++  - [ gss-serv.c servconf.c servconf.h sshd_config sshd_config.5 ]
++    Add GSSAPIStrictAcceptorCheck option to allow the disabling of
++    acceptor principal checking on multi-homed machines.
++    <Bugzilla #928>
++  - [ sshd_config ssh_config ]
++    Add settings for GSSAPIKeyExchange and GSSAPITrustDNS to the sample
++    configuration files
++  - [ kexgss.c kegsss.c sshconnect2.c sshd.c ]
++    Code cleanup. Replace strlen/xmalloc/snprintf sequences with xasprintf()
++    Limit length of error messages displayed by client
++
++20060909
++  - [ gss-genr.c gss-serv.c ]
++    move ssh_gssapi_acquire_cred() and ssh_gssapi_server_ctx to be server
++    only, where they belong 
++    <Bugzilla #1225>
++
++20060829
++  - [ gss-serv-krb5.c ]
++    Fix CCAPI credentials cache name when creating KRB5CCNAME environment 
++    variable
++
++20060828
++  - [ gss-genr.c ]
++    Avoid Heimdal context freeing problem
++    <Fixed upstream 20060829>
++
++20060818
++  - [ gss-genr.c ssh-gss.h sshconnect2.c ]
++    Make sure that SPENGO is disabled 
++    <Bugzilla #1218 - Fixed upstream 20060818>
++
++20060421
++  - [ gssgenr.c, sshconnect2.c ]
++    a few type changes (signed versus unsigned, int versus size_t) to
++    fix compiler errors/warnings 
++    (from jbasney AT ncsa.uiuc.edu)
++  - [ kexgssc.c, sshconnect2.c ]
++    fix uninitialized variable warnings
++    (from jbasney AT ncsa.uiuc.edu)
++  - [ gssgenr.c ]
++    pass oid to gss_display_status (helpful when using GSSAPI mechglue)
++    (from jbasney AT ncsa.uiuc.edu)
++    <Bugzilla #1220 >
++  - [ gss-serv-krb5.c ]
++    #ifdef HAVE_GSSAPI_KRB5 should be #ifdef HAVE_GSSAPI_KRB5_H
++    (from jbasney AT ncsa.uiuc.edu)
++    <Fixed upstream 20060304>
++  - [ readconf.c, readconf.h, ssh_config.5, sshconnect2.c 
++    add client-side GssapiKeyExchange option
++    (from jbasney AT ncsa.uiuc.edu)
++  - [ sshconnect2.c ]
++    add support for GssapiTrustDns option for gssapi-with-mic
++    (from jbasney AT ncsa.uiuc.edu)
++    <gssapi-with-mic support is Bugzilla #1008>
+diff --git Makefile.in Makefile.in
+index d327787..dd0502e 100644
+--- Makefile.in
++++ Makefile.in
+@@ -72,6 +72,7 @@ LIBSSH_OBJS=authfd.o authfile.o bufaux.o bufbn.o buffer.o \
+ 	atomicio.o key.o dispatch.o kex.o mac.o uidswap.o uuencode.o misc.o \
+ 	monitor_fdpass.o rijndael.o ssh-dss.o ssh-ecdsa.o ssh-rsa.o dh.o \
+ 	kexdh.o kexgex.o kexdhc.o kexgexc.o bufec.o kexecdh.o kexecdhc.o \
++	kexgssc.o \
+ 	msg.o progressmeter.o dns.o entropy.o gss-genr.o umac.o umac128.o \
+ 	jpake.o schnorr.o ssh-pkcs11.o krl.o
+ 
+@@ -88,7 +89,7 @@ SSHDOBJS=sshd.o auth-rhosts.o auth-passwd.o auth-rsa.o auth-rh-rsa.o \
+ 	auth2-none.o auth2-passwd.o auth2-pubkey.o auth2-jpake.o \
+ 	monitor_mm.o monitor.o monitor_wrap.o kexdhs.o kexgexs.o kexecdhs.o \
+ 	auth-krb5.o \
+-	auth2-gss.o gss-serv.o gss-serv-krb5.o \
++	auth2-gss.o gss-serv.o gss-serv-krb5.o kexgsss.o\
+ 	loginrec.o auth-pam.o auth-shadow.o auth-sia.o md5crypt.o \
+ 	sftp-server.o sftp-common.o \
+ 	roaming_common.o roaming_serv.o \
+diff --git auth-krb5.c auth-krb5.c
+index 922c66c..91529ea 100644
+--- auth-krb5.c
++++ auth-krb5.c
+@@ -170,8 +170,13 @@ auth_krb5_password(Authctxt *authctxt, const char *password)
+ 
+ 	len = strlen(authctxt->krb5_ticket_file) + 6;
+ 	authctxt->krb5_ccname = xmalloc(len);
++#ifdef USE_CCAPI
++	snprintf(authctxt->krb5_ccname, len, "API:%s",
++	    authctxt->krb5_ticket_file);
++#else
+ 	snprintf(authctxt->krb5_ccname, len, "FILE:%s",
+ 	    authctxt->krb5_ticket_file);
++#endif
+ 
+ #ifdef USE_PAM
+ 	if (options.use_pam)
+@@ -226,15 +231,22 @@ krb5_cleanup_proc(Authctxt *authctxt)
+ #ifndef HEIMDAL
+ krb5_error_code
+ ssh_krb5_cc_gen(krb5_context ctx, krb5_ccache *ccache) {
+-	int tmpfd, ret, oerrno;
++	int ret, oerrno;
+ 	char ccname[40];
+ 	mode_t old_umask;
++#ifdef USE_CCAPI
++	char cctemplate[] = "API:krb5cc_%d";
++#else
++	char cctemplate[] = "FILE:/tmp/krb5cc_%d_XXXXXXXXXX";
++	int tmpfd;
++#endif
+ 
+ 	ret = snprintf(ccname, sizeof(ccname),
+-	    "FILE:/tmp/krb5cc_%d_XXXXXXXXXX", geteuid());
++	    cctemplate, geteuid());
+ 	if (ret < 0 || (size_t)ret >= sizeof(ccname))
+ 		return ENOMEM;
+ 
++#ifndef USE_CCAPI
+ 	old_umask = umask(0177);
+ 	tmpfd = mkstemp(ccname + strlen("FILE:"));
+ 	oerrno = errno;
+@@ -251,6 +263,7 @@ ssh_krb5_cc_gen(krb5_context ctx, krb5_ccache *ccache) {
+ 		return oerrno;
+ 	}
+ 	close(tmpfd);
++#endif
+ 
+ 	return (krb5_cc_resolve(ctx, ccname, ccache));
+ }
+diff --git auth2-gss.c auth2-gss.c
+index 93d576b..17d4a3a 100644
+--- auth2-gss.c
++++ auth2-gss.c
+@@ -1,7 +1,7 @@
+ /* $OpenBSD: auth2-gss.c,v 1.18 2012/12/02 20:34:09 djm Exp $ */
+ 
+ /*
+- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
++ * Copyright (c) 2001-2007 Simon Wilkinson. All rights reserved.
+  *
+  * Redistribution and use in source and binary forms, with or without
+  * modification, are permitted provided that the following conditions
+@@ -52,6 +52,40 @@ static void input_gssapi_mic(int type, u_int32_t plen, void *ctxt);
+ static void input_gssapi_exchange_complete(int type, u_int32_t plen, void *ctxt);
+ static void input_gssapi_errtok(int, u_int32_t, void *);
+ 
++/* 
++ * The 'gssapi_keyex' userauth mechanism.
++ */
++static int
++userauth_gsskeyex(Authctxt *authctxt)
++{
++	int authenticated = 0;
++	Buffer b;
++	gss_buffer_desc mic, gssbuf;
++	u_int len;
++
++	mic.value = packet_get_string(&len);
++	mic.length = len;
++
++	packet_check_eom();
++
++	ssh_gssapi_buildmic(&b, authctxt->user, authctxt->service,
++	    "gssapi-keyex");
++
++	gssbuf.value = buffer_ptr(&b);
++	gssbuf.length = buffer_len(&b);
++
++	/* gss_kex_context is NULL with privsep, so we can't check it here */
++	if (!GSS_ERROR(PRIVSEP(ssh_gssapi_checkmic(gss_kex_context, 
++	    &gssbuf, &mic))))
++		authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user,
++		    authctxt->pw));
++	
++	buffer_free(&b);
++	xfree(mic.value);
++
++	return (authenticated);
++}
++
+ /*
+  * We only support those mechanisms that we know about (ie ones that we know
+  * how to check local user kuserok and the like)
+@@ -244,7 +278,8 @@ input_gssapi_exchange_complete(int type, u_int32_t plen, void *ctxt)
+ 
+ 	packet_check_eom();
+ 
+-	authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user));
++	authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user,
++	    authctxt->pw));
+ 
+ 	authctxt->postponed = 0;
+ 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, NULL);
+@@ -279,7 +314,8 @@ input_gssapi_mic(int type, u_int32_t plen, void *ctxt)
+ 	gssbuf.length = buffer_len(&b);
+ 
+ 	if (!GSS_ERROR(PRIVSEP(ssh_gssapi_checkmic(gssctxt, &gssbuf, &mic))))
+-		authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user));
++		authenticated = 
++		    PRIVSEP(ssh_gssapi_userok(authctxt->user, authctxt->pw));
+ 	else
+ 		logit("GSSAPI MIC check failed");
+ 
+@@ -294,6 +330,12 @@ input_gssapi_mic(int type, u_int32_t plen, void *ctxt)
+ 	userauth_finish(authctxt, authenticated, "gssapi-with-mic", NULL);
+ }
+ 
++Authmethod method_gsskeyex = {
++	"gssapi-keyex",
++	userauth_gsskeyex,
++	&options.gss_authentication
++};
++
+ Authmethod method_gssapi = {
+ 	"gssapi-with-mic",
+ 	userauth_gssapi,
+diff --git auth2.c auth2.c
+index e367a10..d259400 100644
+--- auth2.c
++++ auth2.c
+@@ -69,6 +69,7 @@ extern Authmethod method_passwd;
+ extern Authmethod method_kbdint;
+ extern Authmethod method_hostbased;
+ #ifdef GSSAPI
++extern Authmethod method_gsskeyex;
+ extern Authmethod method_gssapi;
+ #endif
+ #ifdef JPAKE
+@@ -79,6 +80,7 @@ Authmethod *authmethods[] = {
+ 	&method_none,
+ 	&method_pubkey,
+ #ifdef GSSAPI
++	&method_gsskeyex,
+ 	&method_gssapi,
+ #endif
+ #ifdef JPAKE
+diff --git clientloop.c clientloop.c
+index c1d1d44..2ef816a 100644
+--- clientloop.c
++++ clientloop.c
+@@ -111,6 +111,10 @@
+ #include "msg.h"
+ #include "roaming.h"
+ 
++#ifdef GSSAPI
++#include "ssh-gss.h"
++#endif
++
+ /* import options */
+ extern Options options;
+ 
+@@ -1599,6 +1603,15 @@ client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
+ 		/* Do channel operations unless rekeying in progress. */
+ 		if (!rekeying) {
+ 			channel_after_select(readset, writeset);
++
++#ifdef GSSAPI
++			if (options.gss_renewal_rekey &&
++			    ssh_gssapi_credentials_updated(GSS_C_NO_CONTEXT)) {
++				debug("credentials updated - forcing rekey");
++				need_rekeying = 1;
++			}
++#endif
++
+ 			if (need_rekeying || packet_need_rekeying()) {
+ 				debug("need rekeying");
+ 				xxx_kex->done = 0;
+diff --git configure.ac configure.ac
+index 88dd29e..02f8e3f 100644
+--- configure.ac
++++ configure.ac
+@@ -533,6 +533,30 @@ main() { if (NSVersionOfRunTimeLibrary("System") >= (60 << 16))
+ 	    [Use tunnel device compatibility to OpenBSD])
+ 	AC_DEFINE([SSH_TUN_PREPEND_AF], [1],
+ 	    [Prepend the address family to IP tunnel traffic])
++	AC_MSG_CHECKING(if we have the Security Authorization Session API)
++	AC_TRY_COMPILE([#include <Security/AuthSession.h>],
++		[SessionCreate(0, 0);],
++		[ac_cv_use_security_session_api="yes"
++		 AC_DEFINE(USE_SECURITY_SESSION_API, 1, 
++			[platform has the Security Authorization Session API])
++		 LIBS="$LIBS -framework Security"
++		 AC_MSG_RESULT(yes)],
++		[ac_cv_use_security_session_api="no"
++		 AC_MSG_RESULT(no)])
++	AC_MSG_CHECKING(if we have an in-memory credentials cache)
++	AC_TRY_COMPILE(
++		[#include <Kerberos/Kerberos.h>],
++		[cc_context_t c;
++		 (void) cc_initialize (&c, 0, NULL, NULL);],
++		[AC_DEFINE(USE_CCAPI, 1, 
++			[platform uses an in-memory credentials cache])
++		 LIBS="$LIBS -framework Security"
++		 AC_MSG_RESULT(yes)
++		 if test "x$ac_cv_use_security_session_api" = "xno"; then
++			AC_MSG_ERROR(*** Need a security framework to use the credentials cache API ***)
++		fi],
++		[AC_MSG_RESULT(no)]
++	)
+ 	m4_pattern_allow([AU_IPv])
+ 	AC_CHECK_DECL([AU_IPv4], [], 
+ 	    AC_DEFINE([AU_IPv4], [0], [System only supports IPv4 audit records])
+diff --git gss-genr.c gss-genr.c
+index 842f385..f9b39cf 100644
+--- gss-genr.c
++++ gss-genr.c
+@@ -1,7 +1,7 @@
+ /* $OpenBSD: gss-genr.c,v 1.20 2009/06/22 05:39:28 dtucker Exp $ */
+ 
+ /*
+- * Copyright (c) 2001-2007 Simon Wilkinson. All rights reserved.
++ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
+  *
+  * Redistribution and use in source and binary forms, with or without
+  * modification, are permitted provided that the following conditions
+@@ -39,12 +39,167 @@
+ #include "buffer.h"
+ #include "log.h"
+ #include "ssh2.h"
++#include "cipher.h"
++#include "key.h"
++#include "kex.h"
++#include <openssl/evp.h>
+ 
+ #include "ssh-gss.h"
+ 
+ extern u_char *session_id2;
+ extern u_int session_id2_len;
+ 
++typedef struct {
++	char *encoded;
++	gss_OID oid;
++} ssh_gss_kex_mapping;
++
++/*
++ * XXX - It would be nice to find a more elegant way of handling the
++ * XXX   passing of the key exchange context to the userauth routines
++ */
++
++Gssctxt *gss_kex_context = NULL;
++
++static ssh_gss_kex_mapping *gss_enc2oid = NULL;
++
++int 
++ssh_gssapi_oid_table_ok() {
++	return (gss_enc2oid != NULL);
++}
++
++/*
++ * Return a list of the gss-group1-sha1 mechanisms supported by this program
++ *
++ * We test mechanisms to ensure that we can use them, to avoid starting
++ * a key exchange with a bad mechanism
++ */
++
++char *
++ssh_gssapi_client_mechanisms(const char *host, const char *client) {
++	gss_OID_set gss_supported;
++	OM_uint32 min_status;
++
++	if (GSS_ERROR(gss_indicate_mechs(&min_status, &gss_supported)))
++		return NULL;
++
++	return(ssh_gssapi_kex_mechs(gss_supported, ssh_gssapi_check_mechanism,
++	    host, client));
++}
++
++char *
++ssh_gssapi_kex_mechs(gss_OID_set gss_supported, ssh_gssapi_check_fn *check,
++    const char *host, const char *client) {
++	Buffer buf;
++	size_t i;
++	int oidpos, enclen;
++	char *mechs, *encoded;
++	u_char digest[EVP_MAX_MD_SIZE];
++	char deroid[2];
++	const EVP_MD *evp_md = EVP_md5();
++	EVP_MD_CTX md;
++
++	if (gss_enc2oid != NULL) {
++		for (i = 0; gss_enc2oid[i].encoded != NULL; i++)
++			xfree(gss_enc2oid[i].encoded);
++		xfree(gss_enc2oid);
++	}
++
++	gss_enc2oid = xmalloc(sizeof(ssh_gss_kex_mapping) *
++	    (gss_supported->count + 1));
++
++	buffer_init(&buf);
++
++	oidpos = 0;
++	for (i = 0; i < gss_supported->count; i++) {
++		if (gss_supported->elements[i].length < 128 &&
++		    (*check)(NULL, &(gss_supported->elements[i]), host, client)) {
++
++			deroid[0] = SSH_GSS_OIDTYPE;
++			deroid[1] = gss_supported->elements[i].length;
++
++			EVP_DigestInit(&md, evp_md);
++			EVP_DigestUpdate(&md, deroid, 2);
++			EVP_DigestUpdate(&md,
++			    gss_supported->elements[i].elements,
++			    gss_supported->elements[i].length);
++			EVP_DigestFinal(&md, digest, NULL);
++
++			encoded = xmalloc(EVP_MD_size(evp_md) * 2);
++			enclen = __b64_ntop(digest, EVP_MD_size(evp_md),
++			    encoded, EVP_MD_size(evp_md) * 2);
++
++			if (oidpos != 0)
++				buffer_put_char(&buf, ',');
++
++			buffer_append(&buf, KEX_GSS_GEX_SHA1_ID,
++			    sizeof(KEX_GSS_GEX_SHA1_ID) - 1);
++			buffer_append(&buf, encoded, enclen);
++			buffer_put_char(&buf, ',');
++			buffer_append(&buf, KEX_GSS_GRP1_SHA1_ID, 
++			    sizeof(KEX_GSS_GRP1_SHA1_ID) - 1);
++			buffer_append(&buf, encoded, enclen);
++			buffer_put_char(&buf, ',');
++			buffer_append(&buf, KEX_GSS_GRP14_SHA1_ID,
++			    sizeof(KEX_GSS_GRP14_SHA1_ID) - 1);
++			buffer_append(&buf, encoded, enclen);
++
++			gss_enc2oid[oidpos].oid = &(gss_supported->elements[i]);
++			gss_enc2oid[oidpos].encoded = encoded;
++			oidpos++;
++		}
++	}
++	gss_enc2oid[oidpos].oid = NULL;
++	gss_enc2oid[oidpos].encoded = NULL;
++
++	buffer_put_char(&buf, '\0');
++
++	mechs = xmalloc(buffer_len(&buf));
++	buffer_get(&buf, mechs, buffer_len(&buf));
++	buffer_free(&buf);
++
++	if (strlen(mechs) == 0) {
++		xfree(mechs);
++		mechs = NULL;
++	}
++	
++	return (mechs);
++}
++
++gss_OID
++ssh_gssapi_id_kex(Gssctxt *ctx, char *name, int kex_type) {
++	int i = 0;
++	
++	switch (kex_type) {
++	case KEX_GSS_GRP1_SHA1:
++		if (strlen(name) < sizeof(KEX_GSS_GRP1_SHA1_ID))
++			return GSS_C_NO_OID;
++		name += sizeof(KEX_GSS_GRP1_SHA1_ID) - 1;
++		break;
++	case KEX_GSS_GRP14_SHA1:
++		if (strlen(name) < sizeof(KEX_GSS_GRP14_SHA1_ID))
++			return GSS_C_NO_OID;
++		name += sizeof(KEX_GSS_GRP14_SHA1_ID) - 1;
++		break;
++	case KEX_GSS_GEX_SHA1:
++		if (strlen(name) < sizeof(KEX_GSS_GEX_SHA1_ID))
++			return GSS_C_NO_OID;
++		name += sizeof(KEX_GSS_GEX_SHA1_ID) - 1;
++		break;
++	default:
++		return GSS_C_NO_OID;
++	}
++
++	while (gss_enc2oid[i].encoded != NULL &&
++	    strcmp(name, gss_enc2oid[i].encoded) != 0)
++		i++;
++
++	if (gss_enc2oid[i].oid != NULL && ctx != NULL)
++		ssh_gssapi_set_oid(ctx, gss_enc2oid[i].oid);
++
++	return gss_enc2oid[i].oid;
++}
++
+ /* Check that the OID in a data stream matches that in the context */
+ int
+ ssh_gssapi_check_oid(Gssctxt *ctx, void *data, size_t len)
+@@ -197,7 +352,7 @@ ssh_gssapi_init_ctx(Gssctxt *ctx, int deleg_creds, gss_buffer_desc *recv_tok,
+ 	}
+ 
+ 	ctx->major = gss_init_sec_context(&ctx->minor,
+-	    GSS_C_NO_CREDENTIAL, &ctx->context, ctx->name, ctx->oid,
++	    ctx->client_creds, &ctx->context, ctx->name, ctx->oid,
+ 	    GSS_C_MUTUAL_FLAG | GSS_C_INTEG_FLAG | deleg_flag,
+ 	    0, NULL, recv_tok, NULL, send_tok, flags, NULL);
+ 
+@@ -227,8 +382,42 @@ ssh_gssapi_import_name(Gssctxt *ctx, const char *host)
+ }
+ 
+ OM_uint32
++ssh_gssapi_client_identity(Gssctxt *ctx, const char *name)
++{
++	gss_buffer_desc gssbuf;
++	gss_name_t gssname;
++	OM_uint32 status;
++	gss_OID_set oidset;
++
++	gssbuf.value = (void *) name;
++	gssbuf.length = strlen(gssbuf.value);
++
++	gss_create_empty_oid_set(&status, &oidset);
++	gss_add_oid_set_member(&status, ctx->oid, &oidset);
++
++	ctx->major = gss_import_name(&ctx->minor, &gssbuf,
++	    GSS_C_NT_USER_NAME, &gssname);
++
++	if (!ctx->major)
++		ctx->major = gss_acquire_cred(&ctx->minor, 
++		    gssname, 0, oidset, GSS_C_INITIATE, 
++		    &ctx->client_creds, NULL, NULL);
++
++	gss_release_name(&status, &gssname);
++	gss_release_oid_set(&status, &oidset);
++
++	if (ctx->major)
++		ssh_gssapi_error(ctx);
++
++	return(ctx->major);
++}
++
++OM_uint32
+ ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_t buffer, gss_buffer_t hash)
+ {
++	if (ctx == NULL) 
++		return -1;
++
+ 	if ((ctx->major = gss_get_mic(&ctx->minor, ctx->context,
+ 	    GSS_C_QOP_DEFAULT, buffer, hash)))
+ 		ssh_gssapi_error(ctx);
+@@ -236,6 +425,19 @@ ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_t buffer, gss_buffer_t hash)
+ 	return (ctx->major);
+ }
+ 
++/* Priviledged when used by server */
++OM_uint32
++ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
++{
++	if (ctx == NULL)
++		return -1;
++
++	ctx->major = gss_verify_mic(&ctx->minor, ctx->context,
++	    gssbuf, gssmic, NULL);
++
++	return (ctx->major);
++}
++
+ void
+ ssh_gssapi_buildmic(Buffer *b, const char *user, const char *service,
+     const char *context)
+@@ -249,11 +451,16 @@ ssh_gssapi_buildmic(Buffer *b, const char *user, const char *service,
+ }
+ 
+ int
+-ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host)
++ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host, 
++    const char *client)
+ {
+ 	gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
+ 	OM_uint32 major, minor;
+ 	gss_OID_desc spnego_oid = {6, (void *)"\x2B\x06\x01\x05\x05\x02"};
++	Gssctxt *intctx = NULL;
++
++	if (ctx == NULL)
++		ctx = &intctx;
+ 
+ 	/* RFC 4462 says we MUST NOT do SPNEGO */
+ 	if (oid->length == spnego_oid.length && 
+@@ -263,6 +470,10 @@ ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host)
+ 	ssh_gssapi_build_ctx(ctx);
+ 	ssh_gssapi_set_oid(*ctx, oid);
+ 	major = ssh_gssapi_import_name(*ctx, host);
++
++	if (!GSS_ERROR(major) && client)
++		major = ssh_gssapi_client_identity(*ctx, client);
++
+ 	if (!GSS_ERROR(major)) {
+ 		major = ssh_gssapi_init_ctx(*ctx, 0, GSS_C_NO_BUFFER, &token, 
+ 		    NULL);
+@@ -272,10 +483,67 @@ ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host)
+ 			    GSS_C_NO_BUFFER);
+ 	}
+ 
+-	if (GSS_ERROR(major)) 
++	if (GSS_ERROR(major) || intctx != NULL) 
+ 		ssh_gssapi_delete_ctx(ctx);
+ 
+ 	return (!GSS_ERROR(major));
+ }
+ 
++int
++ssh_gssapi_credentials_updated(Gssctxt *ctxt) {
++	static gss_name_t saved_name = GSS_C_NO_NAME;
++	static OM_uint32 saved_lifetime = 0;
++	static gss_OID saved_mech = GSS_C_NO_OID;
++	static gss_name_t name;
++	static OM_uint32 last_call = 0;
++	OM_uint32 lifetime, now, major, minor;
++	int equal;
++	gss_cred_usage_t usage = GSS_C_INITIATE;
++	
++	now = time(NULL);
++
++	if (ctxt) {
++		debug("Rekey has happened - updating saved versions");
++
++		if (saved_name != GSS_C_NO_NAME)
++			gss_release_name(&minor, &saved_name);
++
++		major = gss_inquire_cred(&minor, GSS_C_NO_CREDENTIAL,
++		    &saved_name, &saved_lifetime, NULL, NULL);
++
++		if (!GSS_ERROR(major)) {
++			saved_mech = ctxt->oid;
++		        saved_lifetime+= now;
++		} else {
++			/* Handle the error */
++		}
++		return 0;
++	}
++
++	if (now - last_call < 10)
++		return 0;
++
++	last_call = now;
++
++	if (saved_mech == GSS_C_NO_OID)
++		return 0;
++	
++	major = gss_inquire_cred(&minor, GSS_C_NO_CREDENTIAL, 
++	    &name, &lifetime, NULL, NULL);
++	if (major == GSS_S_CREDENTIALS_EXPIRED)
++		return 0;
++	else if (GSS_ERROR(major))
++		return 0;
++
++	major = gss_compare_name(&minor, saved_name, name, &equal);
++	gss_release_name(&minor, &name);
++	if (GSS_ERROR(major))
++		return 0;
++
++	if (equal && (saved_lifetime < lifetime + now - 10))
++		return 1;
++
++	return 0;
++}
++
+ #endif /* GSSAPI */
+diff --git gss-serv-krb5.c gss-serv-krb5.c
+index 5a625ac..e7170ee 100644
+--- gss-serv-krb5.c
++++ gss-serv-krb5.c
+@@ -1,7 +1,7 @@
+ /* $OpenBSD: gss-serv-krb5.c,v 1.7 2006/08/03 03:34:42 deraadt Exp $ */
+ 
+ /*
+- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
++ * Copyright (c) 2001-2007 Simon Wilkinson. All rights reserved.
+  *
+  * Redistribution and use in source and binary forms, with or without
+  * modification, are permitted provided that the following conditions
+@@ -120,6 +120,7 @@ ssh_gssapi_krb5_storecreds(ssh_gssapi_client *client)
+ 	krb5_principal princ;
+ 	OM_uint32 maj_status, min_status;
+ 	int len;
++	const char *new_ccname;
+ 
+ 	if (client->creds == NULL) {
+ 		debug("No credentials stored");
+@@ -168,11 +169,16 @@ ssh_gssapi_krb5_storecreds(ssh_gssapi_client *client)
+ 		return;
+ 	}
+ 
+-	client->store.filename = xstrdup(krb5_cc_get_name(krb_context, ccache));
++	new_ccname = krb5_cc_get_name(krb_context, ccache);
++
+ 	client->store.envvar = "KRB5CCNAME";
+-	len = strlen(client->store.filename) + 6;
+-	client->store.envval = xmalloc(len);
+-	snprintf(client->store.envval, len, "FILE:%s", client->store.filename);
++#ifdef USE_CCAPI
++	xasprintf(&client->store.envval, "API:%s", new_ccname);
++	client->store.filename = NULL;
++#else
++	xasprintf(&client->store.envval, "FILE:%s", new_ccname);
++	client->store.filename = xstrdup(new_ccname);
++#endif
+ 
+ #ifdef USE_PAM
+ 	if (options.use_pam)
+@@ -184,6 +190,71 @@ ssh_gssapi_krb5_storecreds(ssh_gssapi_client *client)
+ 	return;
+ }
+ 
++int
++ssh_gssapi_krb5_updatecreds(ssh_gssapi_ccache *store, 
++    ssh_gssapi_client *client)
++{
++	krb5_ccache ccache = NULL;
++	krb5_principal principal = NULL;
++	char *name = NULL;
++	krb5_error_code problem;
++	OM_uint32 maj_status, min_status;
++
++   	if ((problem = krb5_cc_resolve(krb_context, store->envval, &ccache))) {
++                logit("krb5_cc_resolve(): %.100s",
++                    krb5_get_err_text(krb_context, problem));
++                return 0;
++       	}
++	
++	/* Find out who the principal in this cache is */
++	if ((problem = krb5_cc_get_principal(krb_context, ccache, 
++	    &principal))) {
++		logit("krb5_cc_get_principal(): %.100s",
++		    krb5_get_err_text(krb_context, problem));
++		krb5_cc_close(krb_context, ccache);
++		return 0;
++	}
++
++	if ((problem = krb5_unparse_name(krb_context, principal, &name))) {
++		logit("krb5_unparse_name(): %.100s",
++		    krb5_get_err_text(krb_context, problem));
++		krb5_free_principal(krb_context, principal);
++		krb5_cc_close(krb_context, ccache);
++		return 0;
++	}
++
++
++	if (strcmp(name,client->exportedname.value)!=0) {
++		debug("Name in local credentials cache differs. Not storing");
++		krb5_free_principal(krb_context, principal);
++		krb5_cc_close(krb_context, ccache);
++		krb5_free_unparsed_name(krb_context, name);
++		return 0;
++	}
++	krb5_free_unparsed_name(krb_context, name);
++
++	/* Name matches, so lets get on with it! */
++
++	if ((problem = krb5_cc_initialize(krb_context, ccache, principal))) {
++		logit("krb5_cc_initialize(): %.100s",
++		    krb5_get_err_text(krb_context, problem));
++		krb5_free_principal(krb_context, principal);
++		krb5_cc_close(krb_context, ccache);
++		return 0;
++	}
++
++	krb5_free_principal(krb_context, principal);
++
++	if ((maj_status = gss_krb5_copy_ccache(&min_status, client->creds,
++	    ccache))) {
++		logit("gss_krb5_copy_ccache() failed. Sorry!");
++		krb5_cc_close(krb_context, ccache);
++		return 0;
++	}
++
++	return 1;
++}
++
+ ssh_gssapi_mech gssapi_kerberos_mech = {
+ 	"toWM5Slw5Ew8Mqkay+al2g==",
+ 	"Kerberos",
+@@ -191,7 +262,8 @@ ssh_gssapi_mech gssapi_kerberos_mech = {
+ 	NULL,
+ 	&ssh_gssapi_krb5_userok,
+ 	NULL,
+-	&ssh_gssapi_krb5_storecreds
++	&ssh_gssapi_krb5_storecreds,
++	&ssh_gssapi_krb5_updatecreds
+ };
+ 
+ #endif /* KRB5 */
+diff --git gss-serv.c gss-serv.c
+index c719c13..380895e 100644
+--- gss-serv.c
++++ gss-serv.c
+@@ -1,7 +1,7 @@
+ /* $OpenBSD: gss-serv.c,v 1.23 2011/08/01 19:18:15 markus Exp $ */
+ 
+ /*
+- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
++ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
+  *
+  * Redistribution and use in source and binary forms, with or without
+  * modification, are permitted provided that the following conditions
+@@ -45,15 +45,20 @@
+ #include "channels.h"
+ #include "session.h"
+ #include "misc.h"
++#include "servconf.h"
++#include "uidswap.h"
+ 
+ #include "ssh-gss.h"
++#include "monitor_wrap.h"
++
++extern ServerOptions options;
+ 
+ static ssh_gssapi_client gssapi_client =
+     { GSS_C_EMPTY_BUFFER, GSS_C_EMPTY_BUFFER,
+-    GSS_C_NO_CREDENTIAL, NULL, {NULL, NULL, NULL}};
++    GSS_C_NO_CREDENTIAL, GSS_C_NO_NAME,  NULL, {NULL, NULL, NULL}, 0, 0};
+ 
+ ssh_gssapi_mech gssapi_null_mech =
+-    { NULL, NULL, {0, NULL}, NULL, NULL, NULL, NULL};
++    { NULL, NULL, {0, NULL}, NULL, NULL, NULL, NULL, NULL};
+ 
+ #ifdef KRB5
+ extern ssh_gssapi_mech gssapi_kerberos_mech;
+@@ -81,25 +86,32 @@ ssh_gssapi_acquire_cred(Gssctxt *ctx)
+ 	char lname[MAXHOSTNAMELEN];
+ 	gss_OID_set oidset;
+ 
+-	gss_create_empty_oid_set(&status, &oidset);
+-	gss_add_oid_set_member(&status, ctx->oid, &oidset);
++	if (options.gss_strict_acceptor) {
++		gss_create_empty_oid_set(&status, &oidset);
++		gss_add_oid_set_member(&status, ctx->oid, &oidset);
+ 
+-	if (gethostname(lname, MAXHOSTNAMELEN)) {
+-		gss_release_oid_set(&status, &oidset);
+-		return (-1);
+-	}
++		if (gethostname(lname, MAXHOSTNAMELEN)) {
++			gss_release_oid_set(&status, &oidset);
++			return (-1);
++		}
++
++		if (GSS_ERROR(ssh_gssapi_import_name(ctx, lname))) {
++			gss_release_oid_set(&status, &oidset);
++			return (ctx->major);
++		}
++
++		if ((ctx->major = gss_acquire_cred(&ctx->minor,
++		    ctx->name, 0, oidset, GSS_C_ACCEPT, &ctx->creds, 
++		    NULL, NULL)))
++			ssh_gssapi_error(ctx);
+ 
+-	if (GSS_ERROR(ssh_gssapi_import_name(ctx, lname))) {
+ 		gss_release_oid_set(&status, &oidset);
+ 		return (ctx->major);
++	} else {
++		ctx->name = GSS_C_NO_NAME;
++		ctx->creds = GSS_C_NO_CREDENTIAL;
+ 	}
+-
+-	if ((ctx->major = gss_acquire_cred(&ctx->minor,
+-	    ctx->name, 0, oidset, GSS_C_ACCEPT, &ctx->creds, NULL, NULL)))
+-		ssh_gssapi_error(ctx);
+-
+-	gss_release_oid_set(&status, &oidset);
+-	return (ctx->major);
++	return GSS_S_COMPLETE;
+ }
+ 
+ /* Privileged */
+@@ -114,6 +126,29 @@ ssh_gssapi_server_ctx(Gssctxt **ctx, gss_OID oid)
+ }
+ 
+ /* Unprivileged */
++char *
++ssh_gssapi_server_mechanisms() {
++	gss_OID_set	supported;
++
++	ssh_gssapi_supported_oids(&supported);
++	return (ssh_gssapi_kex_mechs(supported, &ssh_gssapi_server_check_mech,
++	    NULL, NULL));
++}
++
++/* Unprivileged */
++int
++ssh_gssapi_server_check_mech(Gssctxt **dum, gss_OID oid, const char *data,
++    const char *dummy) {
++	Gssctxt *ctx = NULL;
++	int res;
++ 
++	res = !GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctx, oid)));
++	ssh_gssapi_delete_ctx(&ctx);
++
++	return (res);
++}
++
++/* Unprivileged */
+ void
+ ssh_gssapi_supported_oids(gss_OID_set *oidset)
+ {
+@@ -123,7 +158,9 @@ ssh_gssapi_supported_oids(gss_OID_set *oidset)
+ 	gss_OID_set supported;
+ 
+ 	gss_create_empty_oid_set(&min_status, oidset);
+-	gss_indicate_mechs(&min_status, &supported);
++
++	if (GSS_ERROR(gss_indicate_mechs(&min_status, &supported)))
++		return;
+ 
+ 	while (supported_mechs[i]->name != NULL) {
+ 		if (GSS_ERROR(gss_test_oid_set_member(&min_status,
+@@ -249,8 +286,48 @@ OM_uint32
+ ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
+ {
+ 	int i = 0;
++	int equal = 0;
++	gss_name_t new_name = GSS_C_NO_NAME;
++	gss_buffer_desc ename = GSS_C_EMPTY_BUFFER;
++
++	if (options.gss_store_rekey && client->used && ctx->client_creds) {
++		if (client->mech->oid.length != ctx->oid->length ||
++		    (memcmp(client->mech->oid.elements,
++		     ctx->oid->elements, ctx->oid->length) !=0)) {
++			debug("Rekeyed credentials have different mechanism");
++			return GSS_S_COMPLETE;
++		}
++
++		if ((ctx->major = gss_inquire_cred_by_mech(&ctx->minor, 
++		    ctx->client_creds, ctx->oid, &new_name, 
++		    NULL, NULL, NULL))) {
++			ssh_gssapi_error(ctx);
++			return (ctx->major);
++		}
++
++		ctx->major = gss_compare_name(&ctx->minor, client->name, 
++		    new_name, &equal);
+ 
+-	gss_buffer_desc ename;
++		if (GSS_ERROR(ctx->major)) {
++			ssh_gssapi_error(ctx);
++			return (ctx->major);
++		}
++ 
++		if (!equal) {
++			debug("Rekeyed credentials have different name");
++			return GSS_S_COMPLETE;
++		}
++
++		debug("Marking rekeyed credentials for export");
++
++		gss_release_name(&ctx->minor, &client->name);
++		gss_release_cred(&ctx->minor, &client->creds);
++		client->name = new_name;
++		client->creds = ctx->client_creds;
++        	ctx->client_creds = GSS_C_NO_CREDENTIAL;
++		client->updated = 1;
++		return GSS_S_COMPLETE;
++	}
+ 
+ 	client->mech = NULL;
+ 
+@@ -265,6 +342,13 @@ ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
+ 	if (client->mech == NULL)
+ 		return GSS_S_FAILURE;
+ 
++	if (ctx->client_creds &&
++	    (ctx->major = gss_inquire_cred_by_mech(&ctx->minor,
++	     ctx->client_creds, ctx->oid, &client->name, NULL, NULL, NULL))) {
++		ssh_gssapi_error(ctx);
++		return (ctx->major);
++	}
++
+ 	if ((ctx->major = gss_display_name(&ctx->minor, ctx->client,
+ 	    &client->displayname, NULL))) {
+ 		ssh_gssapi_error(ctx);
+@@ -282,6 +366,8 @@ ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
+ 		return (ctx->major);
+ 	}
+ 
++	gss_release_buffer(&ctx->minor, &ename);
++
+ 	/* We can't copy this structure, so we just move the pointer to it */
+ 	client->creds = ctx->client_creds;
+ 	ctx->client_creds = GSS_C_NO_CREDENTIAL;
+@@ -329,7 +415,7 @@ ssh_gssapi_do_child(char ***envp, u_int *envsizep)
+ 
+ /* Privileged */
+ int
+-ssh_gssapi_userok(char *user)
++ssh_gssapi_userok(char *user, struct passwd *pw)
+ {
+ 	OM_uint32 lmin;
+ 
+@@ -339,9 +425,11 @@ ssh_gssapi_userok(char *user)
+ 		return 0;
+ 	}
+ 	if (gssapi_client.mech && gssapi_client.mech->userok)
+-		if ((*gssapi_client.mech->userok)(&gssapi_client, user))
++		if ((*gssapi_client.mech->userok)(&gssapi_client, user)) {
++			gssapi_client.used = 1;
++			gssapi_client.store.owner = pw;
+ 			return 1;
+-		else {
++		} else {
+ 			/* Destroy delegated credentials if userok fails */
+ 			gss_release_buffer(&lmin, &gssapi_client.displayname);
+ 			gss_release_buffer(&lmin, &gssapi_client.exportedname);
+@@ -354,14 +442,90 @@ ssh_gssapi_userok(char *user)
+ 	return (0);
+ }
+ 
+-/* Privileged */
+-OM_uint32
+-ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
++/* These bits are only used for rekeying. The unpriviledged child is running 
++ * as the user, the monitor is root.
++ *
++ * In the child, we want to :
++ *    *) Ask the monitor to store our credentials into the store we specify
++ *    *) If it succeeds, maybe do a PAM update
++ */
++
++/* Stuff for PAM */
++
++#ifdef USE_PAM
++static int ssh_gssapi_simple_conv(int n, const struct pam_message **msg, 
++    struct pam_response **resp, void *data)
+ {
+-	ctx->major = gss_verify_mic(&ctx->minor, ctx->context,
+-	    gssbuf, gssmic, NULL);
++	return (PAM_CONV_ERR);
++}
++#endif
+ 
+-	return (ctx->major);
++void
++ssh_gssapi_rekey_creds() {
++	int ok;
++	int ret;
++#ifdef USE_PAM
++	pam_handle_t *pamh = NULL;
++	struct pam_conv pamconv = {ssh_gssapi_simple_conv, NULL};
++	char *envstr;
++#endif
++
++	if (gssapi_client.store.filename == NULL && 
++	    gssapi_client.store.envval == NULL &&
++	    gssapi_client.store.envvar == NULL)
++		return;
++ 
++	ok = PRIVSEP(ssh_gssapi_update_creds(&gssapi_client.store));
++
++	if (!ok)
++		return;
++
++	debug("Rekeyed credentials stored successfully");
++
++	/* Actually managing to play with the ssh pam stack from here will
++	 * be next to impossible. In any case, we may want different options
++	 * for rekeying. So, use our own :)
++	 */
++#ifdef USE_PAM	
++	if (!use_privsep) {
++		debug("Not even going to try and do PAM with privsep disabled");
++		return;
++	}
++
++	ret = pam_start("sshd-rekey", gssapi_client.store.owner->pw_name,
++ 	    &pamconv, &pamh);
++	if (ret)
++		return;
++
++	xasprintf(&envstr, "%s=%s", gssapi_client.store.envvar, 
++	    gssapi_client.store.envval);
++
++	ret = pam_putenv(pamh, envstr);
++	if (!ret)
++		pam_setcred(pamh, PAM_REINITIALIZE_CRED);
++	pam_end(pamh, PAM_SUCCESS);
++#endif
++}
++
++int 
++ssh_gssapi_update_creds(ssh_gssapi_ccache *store) {
++	int ok = 0;
++
++	/* Check we've got credentials to store */
++	if (!gssapi_client.updated)
++		return 0;
++
++	gssapi_client.updated = 0;
++
++	temporarily_use_uid(gssapi_client.store.owner);
++	if (gssapi_client.mech && gssapi_client.mech->updatecreds)
++		ok = (*gssapi_client.mech->updatecreds)(store, &gssapi_client);
++	else
++		debug("No update function for this mechanism");
++
++	restore_uid();
++
++	return ok;
+ }
+ 
+ #endif
+diff --git kex.c kex.c
+index 57a79dd..f9e7a9c 100644
+--- kex.c
++++ kex.c
+@@ -50,6 +50,10 @@
+ #include "monitor.h"
+ #include "roaming.h"
+ 
++#ifdef GSSAPI
++#include "ssh-gss.h"
++#endif
++
+ #if OPENSSL_VERSION_NUMBER >= 0x00907000L
+ # if defined(HAVE_EVP_SHA256)
+ # define evp_ssh_sha256 EVP_sha256
+@@ -369,6 +373,20 @@ choose_kex(Kex *k, char *client, char *server)
+  		k->kex_type = KEX_ECDH_SHA2;
+ 		k->evp_md = kex_ecdh_name_to_evpmd(k->name);
+ #endif
++#ifdef GSSAPI
++	} else if (strncmp(k->name, KEX_GSS_GEX_SHA1_ID,
++	    sizeof(KEX_GSS_GEX_SHA1_ID) - 1) == 0) {
++		k->kex_type = KEX_GSS_GEX_SHA1;
++		k->evp_md = EVP_sha1();
++	} else if (strncmp(k->name, KEX_GSS_GRP1_SHA1_ID,
++	    sizeof(KEX_GSS_GRP1_SHA1_ID) - 1) == 0) {
++		k->kex_type = KEX_GSS_GRP1_SHA1;
++		k->evp_md = EVP_sha1();
++	} else if (strncmp(k->name, KEX_GSS_GRP14_SHA1_ID,
++	    sizeof(KEX_GSS_GRP14_SHA1_ID) - 1) == 0) {
++		k->kex_type = KEX_GSS_GRP14_SHA1;
++		k->evp_md = EVP_sha1();
++#endif
+ 	} else
+ 		fatal("bad kex alg %s", k->name);
+ }
+diff --git kex.h kex.h
+index 46731fa..8013ab8 100644
+--- kex.h
++++ kex.h
+@@ -73,6 +73,9 @@ enum kex_exchange {
+ 	KEX_DH_GEX_SHA1,
+ 	KEX_DH_GEX_SHA256,
+ 	KEX_ECDH_SHA2,
++	KEX_GSS_GRP1_SHA1,
++	KEX_GSS_GRP14_SHA1,
++	KEX_GSS_GEX_SHA1,
+ 	KEX_MAX
+ };
+ 
+@@ -131,6 +134,12 @@ struct Kex {
+ 	sig_atomic_t done;
+ 	int	flags;
+ 	const EVP_MD *evp_md;
++#ifdef GSSAPI
++	int	gss_deleg_creds;
++	int	gss_trust_dns;
++	char    *gss_host;
++	char	*gss_client;
++#endif
+ 	char	*client_version_string;
+ 	char	*server_version_string;
+ 	int	(*verify_host_key)(Key *);
+@@ -158,6 +167,11 @@ void	 kexgex_server(Kex *);
+ void	 kexecdh_client(Kex *);
+ void	 kexecdh_server(Kex *);
+ 
++#ifdef GSSAPI
++void	kexgss_client(Kex *);
++void	kexgss_server(Kex *);
++#endif
++
+ void
+ kex_dh_hash(char *, char *, char *, int, char *, int, u_char *, int,
+     BIGNUM *, BIGNUM *, BIGNUM *, u_char **, u_int *);
+diff --git kexgssc.c kexgssc.c
+new file mode 100644
+index 0000000..39be405
+--- /dev/null
++++ kexgssc.c
+@@ -0,0 +1,334 @@
++/*
++ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
++ *
++ * Redistribution and use in source and binary forms, with or without
++ * modification, are permitted provided that the following conditions
++ * are met:
++ * 1. Redistributions of source code must retain the above copyright
++ *    notice, this list of conditions and the following disclaimer.
++ * 2. Redistributions in binary form must reproduce the above copyright
++ *    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.
++ */
++
++#include "includes.h"
++
++#ifdef GSSAPI
++
++#include "includes.h"
++
++#include <openssl/crypto.h>
++#include <openssl/bn.h>
++
++#include <string.h>
++
++#include "xmalloc.h"
++#include "buffer.h"
++#include "ssh2.h"
++#include "key.h"
++#include "cipher.h"
++#include "kex.h"
++#include "log.h"
++#include "packet.h"
++#include "dh.h"
++
++#include "ssh-gss.h"
++
++void
++kexgss_client(Kex *kex) {
++	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
++	gss_buffer_desc recv_tok, gssbuf, msg_tok, *token_ptr;
++	Gssctxt *ctxt;
++	OM_uint32 maj_status, min_status, ret_flags;
++	u_int klen, kout, slen = 0, hashlen, strlen;
++	DH *dh; 
++	BIGNUM *dh_server_pub = NULL;
++	BIGNUM *shared_secret = NULL;
++	BIGNUM *p = NULL;
++	BIGNUM *g = NULL;	
++	u_char *kbuf, *hash;
++	u_char *serverhostkey = NULL;
++	u_char *empty = "";
++	char *msg;
++	char *lang;
++	int type = 0;
++	int first = 1;
++	int nbits = 0, min = DH_GRP_MIN, max = DH_GRP_MAX;
++
++	/* Initialise our GSSAPI world */	
++	ssh_gssapi_build_ctx(&ctxt);
++	if (ssh_gssapi_id_kex(ctxt, kex->name, kex->kex_type) 
++	    == GSS_C_NO_OID)
++		fatal("Couldn't identify host exchange");
++
++	if (ssh_gssapi_import_name(ctxt, kex->gss_host))
++		fatal("Couldn't import hostname");
++
++	if (kex->gss_client && 
++	    ssh_gssapi_client_identity(ctxt, kex->gss_client))
++		fatal("Couldn't acquire client credentials");
++
++	switch (kex->kex_type) {
++	case KEX_GSS_GRP1_SHA1:
++		dh = dh_new_group1();
++		break;
++	case KEX_GSS_GRP14_SHA1:
++		dh = dh_new_group14();
++		break;
++	case KEX_GSS_GEX_SHA1:
++		debug("Doing group exchange\n");
++		nbits = dh_estimate(kex->we_need * 8);
++		packet_start(SSH2_MSG_KEXGSS_GROUPREQ);
++		packet_put_int(min);
++		packet_put_int(nbits);
++		packet_put_int(max);
++
++		packet_send();
++
++		packet_read_expect(SSH2_MSG_KEXGSS_GROUP);
++
++		if ((p = BN_new()) == NULL)
++			fatal("BN_new() failed");
++		packet_get_bignum2(p);
++		if ((g = BN_new()) == NULL)
++			fatal("BN_new() failed");
++		packet_get_bignum2(g);
++		packet_check_eom();
++
++		if (BN_num_bits(p) < min || BN_num_bits(p) > max)
++			fatal("GSSGRP_GEX group out of range: %d !< %d !< %d",
++			    min, BN_num_bits(p), max);
++
++		dh = dh_new_group(g, p);
++		break;
++	default:
++		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
++	}
++	
++	/* Step 1 - e is dh->pub_key */
++	dh_gen_key(dh, kex->we_need * 8);
++
++	/* This is f, we initialise it now to make life easier */
++	dh_server_pub = BN_new();
++	if (dh_server_pub == NULL)
++		fatal("dh_server_pub == NULL");
++
++	token_ptr = GSS_C_NO_BUFFER;
++			 
++	do {
++		debug("Calling gss_init_sec_context");
++		
++		maj_status = ssh_gssapi_init_ctx(ctxt,
++		    kex->gss_deleg_creds, token_ptr, &send_tok,
++		    &ret_flags);
++
++		if (GSS_ERROR(maj_status)) {
++			if (send_tok.length != 0) {
++				packet_start(SSH2_MSG_KEXGSS_CONTINUE);
++				packet_put_string(send_tok.value,
++				    send_tok.length);
++			}
++			fatal("gss_init_context failed");
++		}
++
++		/* If we've got an old receive buffer get rid of it */
++		if (token_ptr != GSS_C_NO_BUFFER)
++			xfree(recv_tok.value);
++
++		if (maj_status == GSS_S_COMPLETE) {
++			/* If mutual state flag is not true, kex fails */
++			if (!(ret_flags & GSS_C_MUTUAL_FLAG))
++				fatal("Mutual authentication failed");
++
++			/* If integ avail flag is not true kex fails */
++			if (!(ret_flags & GSS_C_INTEG_FLAG))
++				fatal("Integrity check failed");
++		}
++
++		/* 
++		 * If we have data to send, then the last message that we
++		 * received cannot have been a 'complete'. 
++		 */
++		if (send_tok.length != 0) {
++			if (first) {
++				packet_start(SSH2_MSG_KEXGSS_INIT);
++				packet_put_string(send_tok.value,
++				    send_tok.length);
++				packet_put_bignum2(dh->pub_key);
++				first = 0;
++			} else {
++				packet_start(SSH2_MSG_KEXGSS_CONTINUE);
++				packet_put_string(send_tok.value,
++				    send_tok.length);
++			}
++			packet_send();
++			gss_release_buffer(&min_status, &send_tok);
++
++			/* If we've sent them data, they should reply */
++			do {	
++				type = packet_read();
++				if (type == SSH2_MSG_KEXGSS_HOSTKEY) {
++					debug("Received KEXGSS_HOSTKEY");
++					if (serverhostkey)
++						fatal("Server host key received more than once");
++					serverhostkey = 
++					    packet_get_string(&slen);
++				}
++			} while (type == SSH2_MSG_KEXGSS_HOSTKEY);
++
++			switch (type) {
++			case SSH2_MSG_KEXGSS_CONTINUE:
++				debug("Received GSSAPI_CONTINUE");
++				if (maj_status == GSS_S_COMPLETE) 
++					fatal("GSSAPI Continue received from server when complete");
++				recv_tok.value = packet_get_string(&strlen);
++				recv_tok.length = strlen; 
++				break;
++			case SSH2_MSG_KEXGSS_COMPLETE:
++				debug("Received GSSAPI_COMPLETE");
++				packet_get_bignum2(dh_server_pub);
++				msg_tok.value =  packet_get_string(&strlen);
++				msg_tok.length = strlen; 
++
++				/* Is there a token included? */
++				if (packet_get_char()) {
++					recv_tok.value=
++					    packet_get_string(&strlen);
++					recv_tok.length = strlen;
++					/* If we're already complete - protocol error */
++					if (maj_status == GSS_S_COMPLETE)
++						packet_disconnect("Protocol error: received token when complete");
++					} else {
++						/* No token included */
++						if (maj_status != GSS_S_COMPLETE)
++							packet_disconnect("Protocol error: did not receive final token");
++				}
++				break;
++			case SSH2_MSG_KEXGSS_ERROR:
++				debug("Received Error");
++				maj_status = packet_get_int();
++				min_status = packet_get_int();
++				msg = packet_get_string(NULL);
++				lang = packet_get_string(NULL);
++				fatal("GSSAPI Error: \n%.400s",msg);
++			default:
++				packet_disconnect("Protocol error: didn't expect packet type %d",
++		    		type);
++			}
++			token_ptr = &recv_tok;
++		} else {
++			/* No data, and not complete */
++			if (maj_status != GSS_S_COMPLETE)
++				fatal("Not complete, and no token output");
++		}
++	} while (maj_status & GSS_S_CONTINUE_NEEDED);
++
++	/* 
++	 * We _must_ have received a COMPLETE message in reply from the 
++	 * server, which will have set dh_server_pub and msg_tok 
++	 */
++
++	if (type != SSH2_MSG_KEXGSS_COMPLETE)
++		fatal("Didn't receive a SSH2_MSG_KEXGSS_COMPLETE when I expected it");
++
++	/* Check f in range [1, p-1] */
++	if (!dh_pub_is_valid(dh, dh_server_pub))
++		packet_disconnect("bad server public DH value");
++
++	/* compute K=f^x mod p */
++	klen = DH_size(dh);
++	kbuf = xmalloc(klen);
++	kout = DH_compute_key(kbuf, dh_server_pub, dh);
++	if (kout < 0)
++		fatal("DH_compute_key: failed");
++
++	shared_secret = BN_new();
++	if (shared_secret == NULL)
++		fatal("kexgss_client: BN_new failed");
++
++	if (BN_bin2bn(kbuf, kout, shared_secret) == NULL)
++		fatal("kexdh_client: BN_bin2bn failed");
++
++	memset(kbuf, 0, klen);
++	xfree(kbuf);
++
++	switch (kex->kex_type) {
++	case KEX_GSS_GRP1_SHA1:
++	case KEX_GSS_GRP14_SHA1:
++		kex_dh_hash( kex->client_version_string, 
++		    kex->server_version_string,
++		    buffer_ptr(&kex->my), buffer_len(&kex->my),
++		    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
++		    (serverhostkey ? serverhostkey : empty), slen,
++		    dh->pub_key,	/* e */
++		    dh_server_pub,	/* f */
++		    shared_secret,	/* K */
++		    &hash, &hashlen
++		);
++		break;
++	case KEX_GSS_GEX_SHA1:
++		kexgex_hash(
++		    kex->evp_md,
++		    kex->client_version_string,
++		    kex->server_version_string,
++		    buffer_ptr(&kex->my), buffer_len(&kex->my),
++		    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
++		    (serverhostkey ? serverhostkey : empty), slen,
++ 		    min, nbits, max,
++		    dh->p, dh->g,
++		    dh->pub_key,
++		    dh_server_pub,
++		    shared_secret,
++		    &hash, &hashlen
++		);
++		break;
++	default:
++		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
++	}
++
++	gssbuf.value = hash;
++	gssbuf.length = hashlen;
++
++	/* Verify that the hash matches the MIC we just got. */
++	if (GSS_ERROR(ssh_gssapi_checkmic(ctxt, &gssbuf, &msg_tok)))
++		packet_disconnect("Hash's MIC didn't verify");
++
++	xfree(msg_tok.value);
++
++	DH_free(dh);
++	if (serverhostkey)
++		xfree(serverhostkey);
++	BN_clear_free(dh_server_pub);
++
++	/* save session id */
++	if (kex->session_id == NULL) {
++		kex->session_id_len = hashlen;
++		kex->session_id = xmalloc(kex->session_id_len);
++		memcpy(kex->session_id, hash, kex->session_id_len);
++	}
++
++	if (kex->gss_deleg_creds)
++		ssh_gssapi_credentials_updated(ctxt);
++
++	if (gss_kex_context == NULL)
++		gss_kex_context = ctxt;
++	else
++		ssh_gssapi_delete_ctx(&ctxt);
++
++	kex_derive_keys(kex, hash, hashlen, shared_secret);
++	BN_clear_free(shared_secret);
++	kex_finish(kex);
++}
++
++#endif /* GSSAPI */
+diff --git kexgsss.c kexgsss.c
+new file mode 100644
+index 0000000..0c3eeaa
+--- /dev/null
++++ kexgsss.c
+@@ -0,0 +1,288 @@
++/*
++ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
++ *
++ * Redistribution and use in source and binary forms, with or without
++ * modification, are permitted provided that the following conditions
++ * are met:
++ * 1. Redistributions of source code must retain the above copyright
++ *    notice, this list of conditions and the following disclaimer.
++ * 2. Redistributions in binary form must reproduce the above copyright
++ *    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.
++ */
++
++#include "includes.h"
++
++#ifdef GSSAPI
++
++#include <string.h>
++
++#include <openssl/crypto.h>
++#include <openssl/bn.h>
++
++#include "xmalloc.h"
++#include "buffer.h"
++#include "ssh2.h"
++#include "key.h"
++#include "cipher.h"
++#include "kex.h"
++#include "log.h"
++#include "packet.h"
++#include "dh.h"
++#include "ssh-gss.h"
++#include "monitor_wrap.h"
++#include "servconf.h"
++
++extern ServerOptions options;
++
++void
++kexgss_server(Kex *kex)
++{
++	OM_uint32 maj_status, min_status;
++	
++	/* 
++	 * Some GSSAPI implementations use the input value of ret_flags (an
++ 	 * output variable) as a means of triggering mechanism specific 
++ 	 * features. Initializing it to zero avoids inadvertently 
++ 	 * activating this non-standard behaviour.
++	 */
++
++	OM_uint32 ret_flags = 0;
++	gss_buffer_desc gssbuf, recv_tok, msg_tok;
++	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
++	Gssctxt *ctxt = NULL;
++	u_int slen, klen, kout, hashlen;
++	u_char *kbuf, *hash;
++	DH *dh;
++	int min = -1, max = -1, nbits = -1;
++	BIGNUM *shared_secret = NULL;
++	BIGNUM *dh_client_pub = NULL;
++	int type = 0;
++	gss_OID oid;
++	char *mechs;
++
++	/* Initialise GSSAPI */
++
++	/* If we're rekeying, privsep means that some of the private structures
++	 * in the GSSAPI code are no longer available. This kludges them back
++	 * into life
++	 */
++	if (!ssh_gssapi_oid_table_ok()) 
++		if ((mechs = ssh_gssapi_server_mechanisms()))
++			xfree(mechs);
++
++	debug2("%s: Identifying %s", __func__, kex->name);
++	oid = ssh_gssapi_id_kex(NULL, kex->name, kex->kex_type);
++	if (oid == GSS_C_NO_OID)
++	   fatal("Unknown gssapi mechanism");
++
++	debug2("%s: Acquiring credentials", __func__);
++
++	if (GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctxt, oid))))
++		fatal("Unable to acquire credentials for the server");
++
++	switch (kex->kex_type) {
++	case KEX_GSS_GRP1_SHA1:
++		dh = dh_new_group1();
++		break;
++	case KEX_GSS_GRP14_SHA1:
++		dh = dh_new_group14();
++		break;
++	case KEX_GSS_GEX_SHA1:
++		debug("Doing group exchange");
++		packet_read_expect(SSH2_MSG_KEXGSS_GROUPREQ);
++		min = packet_get_int();
++		nbits = packet_get_int();
++		max = packet_get_int();
++		min = MAX(DH_GRP_MIN, min);
++		max = MIN(DH_GRP_MAX, max);
++		packet_check_eom();
++		if (max < min || nbits < min || max < nbits)
++			fatal("GSS_GEX, bad parameters: %d !< %d !< %d",
++			    min, nbits, max);
++		dh = PRIVSEP(choose_dh(min, nbits, max));
++		if (dh == NULL)
++			packet_disconnect("Protocol error: no matching group found");
++
++		packet_start(SSH2_MSG_KEXGSS_GROUP);
++		packet_put_bignum2(dh->p);
++		packet_put_bignum2(dh->g);
++		packet_send();
++
++		packet_write_wait();
++		break;
++	default:
++		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
++	}
++
++	dh_gen_key(dh, kex->we_need * 8);
++
++	do {
++		debug("Wait SSH2_MSG_GSSAPI_INIT");
++		type = packet_read();
++		switch(type) {
++		case SSH2_MSG_KEXGSS_INIT:
++			if (dh_client_pub != NULL) 
++				fatal("Received KEXGSS_INIT after initialising");
++			recv_tok.value = packet_get_string(&slen);
++			recv_tok.length = slen; 
++
++			if ((dh_client_pub = BN_new()) == NULL)
++				fatal("dh_client_pub == NULL");
++
++			packet_get_bignum2(dh_client_pub);
++
++			/* Send SSH_MSG_KEXGSS_HOSTKEY here, if we want */
++			break;
++		case SSH2_MSG_KEXGSS_CONTINUE:
++			recv_tok.value = packet_get_string(&slen);
++			recv_tok.length = slen; 
++			break;
++		default:
++			packet_disconnect(
++			    "Protocol error: didn't expect packet type %d",
++			    type);
++		}
++
++		maj_status = PRIVSEP(ssh_gssapi_accept_ctx(ctxt, &recv_tok, 
++		    &send_tok, &ret_flags));
++
++		xfree(recv_tok.value);
++
++		if (maj_status != GSS_S_COMPLETE && send_tok.length == 0)
++			fatal("Zero length token output when incomplete");
++
++		if (dh_client_pub == NULL)
++			fatal("No client public key");
++		
++		if (maj_status & GSS_S_CONTINUE_NEEDED) {
++			debug("Sending GSSAPI_CONTINUE");
++			packet_start(SSH2_MSG_KEXGSS_CONTINUE);
++			packet_put_string(send_tok.value, send_tok.length);
++			packet_send();
++			gss_release_buffer(&min_status, &send_tok);
++		}
++	} while (maj_status & GSS_S_CONTINUE_NEEDED);
++
++	if (GSS_ERROR(maj_status)) {
++		if (send_tok.length > 0) {
++			packet_start(SSH2_MSG_KEXGSS_CONTINUE);
++			packet_put_string(send_tok.value, send_tok.length);
++			packet_send();
++		}
++		fatal("accept_ctx died");
++	}
++
++	if (!(ret_flags & GSS_C_MUTUAL_FLAG))
++		fatal("Mutual Authentication flag wasn't set");
++
++	if (!(ret_flags & GSS_C_INTEG_FLAG))
++		fatal("Integrity flag wasn't set");
++	
++	if (!dh_pub_is_valid(dh, dh_client_pub))
++		packet_disconnect("bad client public DH value");
++
++	klen = DH_size(dh);
++	kbuf = xmalloc(klen); 
++	kout = DH_compute_key(kbuf, dh_client_pub, dh);
++	if (kout < 0)
++		fatal("DH_compute_key: failed");
++
++	shared_secret = BN_new();
++	if (shared_secret == NULL)
++		fatal("kexgss_server: BN_new failed");
++
++	if (BN_bin2bn(kbuf, kout, shared_secret) == NULL)
++		fatal("kexgss_server: BN_bin2bn failed");
++
++	memset(kbuf, 0, klen);
++	xfree(kbuf);
++
++	switch (kex->kex_type) {
++	case KEX_GSS_GRP1_SHA1:
++	case KEX_GSS_GRP14_SHA1:
++		kex_dh_hash(
++		    kex->client_version_string, kex->server_version_string,
++		    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
++		    buffer_ptr(&kex->my), buffer_len(&kex->my),
++		    NULL, 0, /* Change this if we start sending host keys */
++		    dh_client_pub, dh->pub_key, shared_secret,
++		    &hash, &hashlen
++		);
++		break;
++	case KEX_GSS_GEX_SHA1:
++		kexgex_hash(
++		    kex->evp_md,
++		    kex->client_version_string, kex->server_version_string,
++		    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
++		    buffer_ptr(&kex->my), buffer_len(&kex->my),
++		    NULL, 0,
++		    min, nbits, max,
++		    dh->p, dh->g,
++		    dh_client_pub,
++		    dh->pub_key,
++		    shared_secret,
++		    &hash, &hashlen
++		);
++		break;
++	default:
++		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
++	}
++
++	BN_clear_free(dh_client_pub);
++
++	if (kex->session_id == NULL) {
++		kex->session_id_len = hashlen;
++		kex->session_id = xmalloc(kex->session_id_len);
++		memcpy(kex->session_id, hash, kex->session_id_len);
++	}
++
++	gssbuf.value = hash;
++	gssbuf.length = hashlen;
++
++	if (GSS_ERROR(PRIVSEP(ssh_gssapi_sign(ctxt,&gssbuf,&msg_tok))))
++		fatal("Couldn't get MIC");
++
++	packet_start(SSH2_MSG_KEXGSS_COMPLETE);
++	packet_put_bignum2(dh->pub_key);
++	packet_put_string(msg_tok.value,msg_tok.length);
++
++	if (send_tok.length != 0) {
++		packet_put_char(1); /* true */
++		packet_put_string(send_tok.value, send_tok.length);
++	} else {
++		packet_put_char(0); /* false */
++	}
++	packet_send();
++
++	gss_release_buffer(&min_status, &send_tok);
++	gss_release_buffer(&min_status, &msg_tok);
++
++	if (gss_kex_context == NULL)
++		gss_kex_context = ctxt;
++	else 
++		ssh_gssapi_delete_ctx(&ctxt);
++
++	DH_free(dh);
++
++	kex_derive_keys(kex, hash, hashlen, shared_secret);
++	BN_clear_free(shared_secret);
++	kex_finish(kex);
++
++	/* If this was a rekey, then save out any delegated credentials we
++	 * just exchanged.  */
++	if (options.gss_store_rekey)
++		ssh_gssapi_rekey_creds();
++}
++#endif /* GSSAPI */
+diff --git key.c key.c
+index 4cc5c5d..fdfed5c 100644
+--- key.c
++++ key.c
+@@ -976,6 +976,8 @@ key_ssh_name_from_type_nid(int type, int nid)
+ 		}
+ 		break;
+ #endif /* OPENSSL_HAS_ECC */
++	case KEY_NULL:
++		return "null";
+ 	}
+ 	return "ssh-unknown";
+ }
+@@ -1281,6 +1283,8 @@ key_type_from_name(char *name)
+ 	    strcmp(name, "ecdsa-sha2-nistp521-cert-v01 at openssh.com") == 0) {
+ 		return KEY_ECDSA_CERT;
+ #endif
++	} else if (strcmp(name, "null") == 0) {
++		return KEY_NULL;
+ 	}
+ 
+ 	debug2("key_type_from_name: unknown key type '%s'", name);
+diff --git key.h key.h
+index ebdf456..4beaf20 100644
+--- key.h
++++ key.h
+@@ -44,6 +44,7 @@ enum types {
+ 	KEY_ECDSA_CERT,
+ 	KEY_RSA_CERT_V00,
+ 	KEY_DSA_CERT_V00,
++	KEY_NULL,
+ 	KEY_UNSPEC
+ };
+ enum fp_type {
+diff --git monitor.c monitor.c
+index 8006b83..d7a782f 100644
+--- monitor.c
++++ monitor.c
+@@ -180,6 +180,8 @@ int mm_answer_gss_setup_ctx(int, Buffer *);
+ int mm_answer_gss_accept_ctx(int, Buffer *);
+ int mm_answer_gss_userok(int, Buffer *);
+ int mm_answer_gss_checkmic(int, Buffer *);
++int mm_answer_gss_sign(int, Buffer *);
++int mm_answer_gss_updatecreds(int, Buffer *);
+ #endif
+ 
+ #ifdef SSH_AUDIT_EVENTS
+@@ -252,6 +254,7 @@ struct mon_table mon_dispatch_proto20[] = {
+     {MONITOR_REQ_GSSSTEP, MON_ISAUTH, mm_answer_gss_accept_ctx},
+     {MONITOR_REQ_GSSUSEROK, MON_AUTH, mm_answer_gss_userok},
+     {MONITOR_REQ_GSSCHECKMIC, MON_ISAUTH, mm_answer_gss_checkmic},
++    {MONITOR_REQ_GSSSIGN, MON_ONCE, mm_answer_gss_sign},
+ #endif
+ #ifdef JPAKE
+     {MONITOR_REQ_JPAKE_GET_PWDATA, MON_ONCE, mm_answer_jpake_get_pwdata},
+@@ -264,6 +267,12 @@ struct mon_table mon_dispatch_proto20[] = {
+ };
+ 
+ struct mon_table mon_dispatch_postauth20[] = {
++#ifdef GSSAPI
++    {MONITOR_REQ_GSSSETUP, 0, mm_answer_gss_setup_ctx},
++    {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
++    {MONITOR_REQ_GSSSIGN, 0, mm_answer_gss_sign},
++    {MONITOR_REQ_GSSUPCREDS, 0, mm_answer_gss_updatecreds},
++#endif
+     {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
+     {MONITOR_REQ_SIGN, 0, mm_answer_sign},
+     {MONITOR_REQ_PTY, 0, mm_answer_pty},
+@@ -372,6 +381,10 @@ monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor)
+ 		/* Permit requests for moduli and signatures */
+ 		monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
+ 		monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
++#ifdef GSSAPI
++		/* and for the GSSAPI key exchange */
++		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSETUP, 1);
++#endif
+ 	} else {
+ 		mon_dispatch = mon_dispatch_proto15;
+ 
+@@ -487,6 +500,10 @@ monitor_child_postauth(struct monitor *pmonitor)
+ 		monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
+ 		monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
+ 		monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
++#ifdef GSSAPI
++		/* and for the GSSAPI key exchange */
++		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSETUP, 1);
++#endif		
+ 	} else {
+ 		mon_dispatch = mon_dispatch_postauth15;
+ 		monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
+@@ -1836,6 +1853,13 @@ mm_get_kex(Buffer *m)
+ 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
+ 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
+ 	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
++#ifdef GSSAPI
++	if (options.gss_keyex) {
++		kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
++		kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
++		kex->kex[KEX_GSS_GEX_SHA1] = kexgss_server;
++	}
++#endif
+ 	kex->server = 1;
+ 	kex->hostkey_type = buffer_get_int(m);
+ 	kex->kex_type = buffer_get_int(m);
+@@ -2042,6 +2066,9 @@ mm_answer_gss_setup_ctx(int sock, Buffer *m)
+ 	OM_uint32 major;
+ 	u_int len;
+ 
++	if (!options.gss_authentication && !options.gss_keyex)
++		fatal("In GSSAPI monitor when GSSAPI is disabled");
++
+ 	goid.elements = buffer_get_string(m, &len);
+ 	goid.length = len;
+ 
+@@ -2069,6 +2096,9 @@ mm_answer_gss_accept_ctx(int sock, Buffer *m)
+ 	OM_uint32 flags = 0; /* GSI needs this */
+ 	u_int len;
+ 
++	if (!options.gss_authentication && !options.gss_keyex)
++		fatal("In GSSAPI monitor when GSSAPI is disabled");
++
+ 	in.value = buffer_get_string(m, &len);
+ 	in.length = len;
+ 	major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
+@@ -2086,6 +2116,7 @@ mm_answer_gss_accept_ctx(int sock, Buffer *m)
+ 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
+ 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
+ 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
++		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSIGN, 1);
+ 	}
+ 	return (0);
+ }
+@@ -2097,6 +2128,9 @@ mm_answer_gss_checkmic(int sock, Buffer *m)
+ 	OM_uint32 ret;
+ 	u_int len;
+ 
++	if (!options.gss_authentication && !options.gss_keyex)
++		fatal("In GSSAPI monitor when GSSAPI is disabled");
++
+ 	gssbuf.value = buffer_get_string(m, &len);
+ 	gssbuf.length = len;
+ 	mic.value = buffer_get_string(m, &len);
+@@ -2123,7 +2157,11 @@ mm_answer_gss_userok(int sock, Buffer *m)
+ {
+ 	int authenticated;
+ 
+-	authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
++	if (!options.gss_authentication && !options.gss_keyex)
++		fatal("In GSSAPI monitor when GSSAPI is disabled");
++
++	authenticated = authctxt->valid && 
++	    ssh_gssapi_userok(authctxt->user, authctxt->pw);
+ 
+ 	buffer_clear(m);
+ 	buffer_put_int(m, authenticated);
+@@ -2136,6 +2174,74 @@ mm_answer_gss_userok(int sock, Buffer *m)
+ 	/* Monitor loop will terminate if authenticated */
+ 	return (authenticated);
+ }
++
++int 
++mm_answer_gss_sign(int socket, Buffer *m)
++{
++	gss_buffer_desc data;
++	gss_buffer_desc hash = GSS_C_EMPTY_BUFFER;
++	OM_uint32 major, minor;
++	u_int len;
++
++	if (!options.gss_authentication && !options.gss_keyex)
++		fatal("In GSSAPI monitor when GSSAPI is disabled");
++
++	data.value = buffer_get_string(m, &len);
++	data.length = len;
++	if (data.length != 20) 
++		fatal("%s: data length incorrect: %d", __func__, 
++		    (int) data.length);
++
++	/* Save the session ID on the first time around */
++	if (session_id2_len == 0) {
++		session_id2_len = data.length;
++		session_id2 = xmalloc(session_id2_len);
++		memcpy(session_id2, data.value, session_id2_len);
++	}
++	major = ssh_gssapi_sign(gsscontext, &data, &hash);
++
++	xfree(data.value);
++
++	buffer_clear(m);
++	buffer_put_int(m, major);
++	buffer_put_string(m, hash.value, hash.length);
++
++	mm_request_send(socket, MONITOR_ANS_GSSSIGN, m);
++
++	gss_release_buffer(&minor, &hash);
++
++	/* Turn on getpwnam permissions */
++	monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
++	
++	/* And credential updating, for when rekeying */
++	monitor_permit(mon_dispatch, MONITOR_REQ_GSSUPCREDS, 1);
++
++	return (0);
++}
++
++int
++mm_answer_gss_updatecreds(int socket, Buffer *m) {
++	ssh_gssapi_ccache store;
++	int ok;
++
++	store.filename = buffer_get_string(m, NULL);
++	store.envvar   = buffer_get_string(m, NULL);
++	store.envval   = buffer_get_string(m, NULL);
++
++	ok = ssh_gssapi_update_creds(&store);
++
++	xfree(store.filename);
++	xfree(store.envvar);
++	xfree(store.envval);
++
++	buffer_clear(m);
++	buffer_put_int(m, ok);
++
++	mm_request_send(socket, MONITOR_ANS_GSSUPCREDS, m);
++
++	return(0);
++}
++
+ #endif /* GSSAPI */
+ 
+ #ifdef JPAKE
+diff --git monitor.h monitor.h
+index 2caa469..d4dbc5a 100644
+--- monitor.h
++++ monitor.h
+@@ -62,6 +62,9 @@ enum monitor_reqtype {
+ 	MONITOR_REQ_JPAKE_KEY_CONFIRM = 58, MONITOR_ANS_JPAKE_KEY_CONFIRM = 59,
+ 	MONITOR_REQ_JPAKE_CHECK_CONFIRM = 60, MONITOR_ANS_JPAKE_CHECK_CONFIRM = 61,
+ 
++	MONITOR_REQ_GSSSIGN = 62, MONITOR_ANS_GSSSIGN = 63,
++	MONITOR_REQ_GSSUPCREDS = 64, MONITOR_ANS_GSSUPCREDS = 65,
++
+ 	MONITOR_REQ_PAM_START = 100,
+ 	MONITOR_REQ_PAM_ACCOUNT = 102, MONITOR_ANS_PAM_ACCOUNT = 103,
+ 	MONITOR_REQ_PAM_INIT_CTX = 104, MONITOR_ANS_PAM_INIT_CTX = 105,
+diff --git monitor_wrap.c monitor_wrap.c
+index ea654a7..ed8dbda 100644
+--- monitor_wrap.c
++++ monitor_wrap.c
+@@ -1271,7 +1271,7 @@ mm_ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
+ }
+ 
+ int
+-mm_ssh_gssapi_userok(char *user)
++mm_ssh_gssapi_userok(char *user, struct passwd *pw)
+ {
+ 	Buffer m;
+ 	int authenticated = 0;
+@@ -1288,6 +1288,51 @@ mm_ssh_gssapi_userok(char *user)
+ 	debug3("%s: user %sauthenticated",__func__, authenticated ? "" : "not ");
+ 	return (authenticated);
+ }
++
++OM_uint32
++mm_ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_desc *data, gss_buffer_desc *hash)
++{
++	Buffer m;
++	OM_uint32 major;
++	u_int len;
++
++	buffer_init(&m);
++	buffer_put_string(&m, data->value, data->length);
++
++	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSSIGN, &m);
++	mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSSIGN, &m);
++
++	major = buffer_get_int(&m);
++	hash->value = buffer_get_string(&m, &len);
++	hash->length = len;
++
++	buffer_free(&m);
++
++	return(major);
++}
++
++int
++mm_ssh_gssapi_update_creds(ssh_gssapi_ccache *store)
++{
++	Buffer m;
++	int ok;
++
++	buffer_init(&m);
++
++	buffer_put_cstring(&m, store->filename ? store->filename : "");
++	buffer_put_cstring(&m, store->envvar ? store->envvar : "");
++	buffer_put_cstring(&m, store->envval ? store->envval : "");
++	
++	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSUPCREDS, &m);
++	mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSUPCREDS, &m);
++
++	ok = buffer_get_int(&m);
++
++	buffer_free(&m);
++	
++	return (ok);
++}
++
+ #endif /* GSSAPI */
+ 
+ #ifdef JPAKE
+diff --git monitor_wrap.h monitor_wrap.h
+index 0c7f2e3..ec9b9b1 100644
+--- monitor_wrap.h
++++ monitor_wrap.h
+@@ -58,8 +58,10 @@ BIGNUM *mm_auth_rsa_generate_challenge(Key *);
+ OM_uint32 mm_ssh_gssapi_server_ctx(Gssctxt **, gss_OID);
+ OM_uint32 mm_ssh_gssapi_accept_ctx(Gssctxt *,
+    gss_buffer_desc *, gss_buffer_desc *, OM_uint32 *);
+-int mm_ssh_gssapi_userok(char *user);
++int mm_ssh_gssapi_userok(char *user, struct passwd *);
+ OM_uint32 mm_ssh_gssapi_checkmic(Gssctxt *, gss_buffer_t, gss_buffer_t);
++OM_uint32 mm_ssh_gssapi_sign(Gssctxt *, gss_buffer_t, gss_buffer_t);
++int mm_ssh_gssapi_update_creds(ssh_gssapi_ccache *);
+ #endif
+ 
+ #ifdef USE_PAM
+diff --git readconf.c readconf.c
+index 36265e4..375ca32 100644
+--- readconf.c
++++ readconf.c
+@@ -129,6 +129,8 @@ typedef enum {
+ 	oClearAllForwardings, oNoHostAuthenticationForLocalhost,
+ 	oEnableSSHKeysign, oRekeyLimit, oVerifyHostKeyDNS, oConnectTimeout,
+ 	oAddressFamily, oGssAuthentication, oGssDelegateCreds,
++	oGssTrustDns, oGssKeyEx, oGssClientIdentity, oGssRenewalRekey,
++	oGssServerIdentity, 
+ 	oServerAliveInterval, oServerAliveCountMax, oIdentitiesOnly,
+ 	oSendEnv, oControlPath, oControlMaster, oControlPersist,
+ 	oHashKnownHosts,
+@@ -169,10 +171,19 @@ static struct {
+ 	{ "afstokenpassing", oUnsupported },
+ #if defined(GSSAPI)
+ 	{ "gssapiauthentication", oGssAuthentication },
++	{ "gssapikeyexchange", oGssKeyEx },
+ 	{ "gssapidelegatecredentials", oGssDelegateCreds },
++	{ "gssapitrustdns", oGssTrustDns },
++	{ "gssapiclientidentity", oGssClientIdentity },
++	{ "gssapiserveridentity", oGssServerIdentity },
++	{ "gssapirenewalforcesrekey", oGssRenewalRekey },
+ #else
+ 	{ "gssapiauthentication", oUnsupported },
++	{ "gssapikeyexchange", oUnsupported },
+ 	{ "gssapidelegatecredentials", oUnsupported },
++	{ "gssapitrustdns", oUnsupported },
++	{ "gssapiclientidentity", oUnsupported },
++	{ "gssapirenewalforcesrekey", oUnsupported },
+ #endif
+ 	{ "fallbacktorsh", oDeprecated },
+ 	{ "usersh", oDeprecated },
+@@ -503,10 +514,30 @@ parse_flag:
+ 		intptr = &options->gss_authentication;
+ 		goto parse_flag;
+ 
++	case oGssKeyEx:
++		intptr = &options->gss_keyex;
++		goto parse_flag;
++
+ 	case oGssDelegateCreds:
+ 		intptr = &options->gss_deleg_creds;
+ 		goto parse_flag;
+ 
++	case oGssTrustDns:
++		intptr = &options->gss_trust_dns;
++		goto parse_flag;
++
++	case oGssClientIdentity:
++		charptr = &options->gss_client_identity;
++		goto parse_string;
++
++	case oGssServerIdentity:
++		charptr = &options->gss_server_identity;
++		goto parse_string;
++
++	case oGssRenewalRekey:
++		intptr = &options->gss_renewal_rekey;
++		goto parse_flag;
++
+ 	case oBatchMode:
+ 		intptr = &options->batch_mode;
+ 		goto parse_flag;
+@@ -1158,7 +1189,12 @@ initialize_options(Options * options)
+ 	options->pubkey_authentication = -1;
+ 	options->challenge_response_authentication = -1;
+ 	options->gss_authentication = -1;
++	options->gss_keyex = -1;
+ 	options->gss_deleg_creds = -1;
++	options->gss_trust_dns = -1;
++	options->gss_renewal_rekey = -1;
++	options->gss_client_identity = NULL;
++	options->gss_server_identity = NULL;
+ 	options->password_authentication = -1;
+ 	options->kbd_interactive_authentication = -1;
+ 	options->kbd_interactive_devices = NULL;
+@@ -1258,8 +1294,14 @@ fill_default_options(Options * options)
+ 		options->challenge_response_authentication = 1;
+ 	if (options->gss_authentication == -1)
+ 		options->gss_authentication = 0;
++	if (options->gss_keyex == -1)
++		options->gss_keyex = 0;
+ 	if (options->gss_deleg_creds == -1)
+ 		options->gss_deleg_creds = 0;
++	if (options->gss_trust_dns == -1)
++		options->gss_trust_dns = 0;
++	if (options->gss_renewal_rekey == -1)
++		options->gss_renewal_rekey = 0;
+ 	if (options->password_authentication == -1)
+ 		options->password_authentication = 1;
+ 	if (options->kbd_interactive_authentication == -1)
+diff --git readconf.h readconf.h
+index 8416489..0835cb6 100644
+--- readconf.h
++++ readconf.h
+@@ -48,7 +48,12 @@ typedef struct {
+ 	int     challenge_response_authentication;
+ 					/* Try S/Key or TIS, authentication. */
+ 	int     gss_authentication;	/* Try GSS authentication */
++	int     gss_keyex;		/* Try GSS key exchange */
+ 	int     gss_deleg_creds;	/* Delegate GSS credentials */
++	int	gss_trust_dns;		/* Trust DNS for GSS canonicalization */
++	int	gss_renewal_rekey;	/* Credential renewal forces rekey */
++	char    *gss_client_identity;   /* Principal to initiate GSSAPI with */
++	char    *gss_server_identity;   /* GSSAPI target principal */
+ 	int     password_authentication;	/* Try password
+ 						 * authentication. */
+ 	int     kbd_interactive_authentication; /* Try keyboard-interactive auth. */
+diff --git servconf.c servconf.c
+index b2a60fd..cdc0293 100644
+--- servconf.c
++++ servconf.c
+@@ -102,7 +102,10 @@ initialize_server_options(ServerOptions *options)
+ 	options->kerberos_ticket_cleanup = -1;
+ 	options->kerberos_get_afs_token = -1;
+ 	options->gss_authentication=-1;
++	options->gss_keyex = -1;
+ 	options->gss_cleanup_creds = -1;
++	options->gss_strict_acceptor = -1;
++	options->gss_store_rekey = -1;
+ 	options->password_authentication = -1;
+ 	options->kbd_interactive_authentication = -1;
+ 	options->challenge_response_authentication = -1;
+@@ -233,8 +236,14 @@ fill_default_server_options(ServerOptions *options)
+ 		options->kerberos_get_afs_token = 0;
+ 	if (options->gss_authentication == -1)
+ 		options->gss_authentication = 0;
++	if (options->gss_keyex == -1)
++		options->gss_keyex = 0;
+ 	if (options->gss_cleanup_creds == -1)
+ 		options->gss_cleanup_creds = 1;
++	if (options->gss_strict_acceptor == -1)
++		options->gss_strict_acceptor = 1;
++	if (options->gss_store_rekey == -1)
++		options->gss_store_rekey = 0;
+ 	if (options->password_authentication == -1)
+ 		options->password_authentication = 1;
+ 	if (options->kbd_interactive_authentication == -1)
+@@ -327,7 +336,9 @@ typedef enum {
+ 	sBanner, sUseDNS, sHostbasedAuthentication,
+ 	sHostbasedUsesNameFromPacketOnly, sClientAliveInterval,
+ 	sClientAliveCountMax, sAuthorizedKeysFile,
+-	sGssAuthentication, sGssCleanupCreds, sAcceptEnv, sPermitTunnel,
++	sGssAuthentication, sGssCleanupCreds, sGssStrictAcceptor,
++	sGssKeyEx, sGssStoreRekey,
++	sAcceptEnv, sPermitTunnel,
+ 	sMatch, sPermitOpen, sForceCommand, sChrootDirectory,
+ 	sUsePrivilegeSeparation, sAllowAgentForwarding,
+ 	sZeroKnowledgePasswordAuthentication, sHostCertificate,
+@@ -393,10 +404,20 @@ static struct {
+ #ifdef GSSAPI
+ 	{ "gssapiauthentication", sGssAuthentication, SSHCFG_ALL },
+ 	{ "gssapicleanupcredentials", sGssCleanupCreds, SSHCFG_GLOBAL },
++	{ "gssapicleanupcreds", sGssCleanupCreds, SSHCFG_GLOBAL },
++	{ "gssapistrictacceptorcheck", sGssStrictAcceptor, SSHCFG_GLOBAL },
++	{ "gssapikeyexchange", sGssKeyEx, SSHCFG_GLOBAL },
++	{ "gssapistorecredentialsonrekey", sGssStoreRekey, SSHCFG_GLOBAL },
+ #else
+ 	{ "gssapiauthentication", sUnsupported, SSHCFG_ALL },
+ 	{ "gssapicleanupcredentials", sUnsupported, SSHCFG_GLOBAL },
++	{ "gssapicleanupcreds", sUnsupported, SSHCFG_GLOBAL },
++	{ "gssapistrictacceptorcheck", sUnsupported, SSHCFG_GLOBAL },
++	{ "gssapikeyexchange", sUnsupported, SSHCFG_GLOBAL },
++	{ "gssapistorecredentialsonrekey", sUnsupported, SSHCFG_GLOBAL },
+ #endif
++	{ "gssusesessionccache", sUnsupported, SSHCFG_GLOBAL },
++	{ "gssapiusesessioncredcache", sUnsupported, SSHCFG_GLOBAL },
+ 	{ "passwordauthentication", sPasswordAuthentication, SSHCFG_ALL },
+ 	{ "kbdinteractiveauthentication", sKbdInteractiveAuthentication, SSHCFG_ALL },
+ 	{ "challengeresponseauthentication", sChallengeResponseAuthentication, SSHCFG_GLOBAL },
+@@ -1049,10 +1070,22 @@ process_server_config_line(ServerOptions *options, char *line,
+ 		intptr = &options->gss_authentication;
+ 		goto parse_flag;
+ 
++	case sGssKeyEx:
++		intptr = &options->gss_keyex;
++		goto parse_flag;
++
+ 	case sGssCleanupCreds:
+ 		intptr = &options->gss_cleanup_creds;
+ 		goto parse_flag;
+ 
++	case sGssStrictAcceptor:
++		intptr = &options->gss_strict_acceptor;
++		goto parse_flag;
++
++	case sGssStoreRekey:
++		intptr = &options->gss_store_rekey;
++		goto parse_flag;
++
+ 	case sPasswordAuthentication:
+ 		intptr = &options->password_authentication;
+ 		goto parse_flag;
+@@ -1927,7 +1960,10 @@ dump_config(ServerOptions *o)
+ #endif
+ #ifdef GSSAPI
+ 	dump_cfg_fmtint(sGssAuthentication, o->gss_authentication);
++	dump_cfg_fmtint(sGssKeyEx, o->gss_keyex);
+ 	dump_cfg_fmtint(sGssCleanupCreds, o->gss_cleanup_creds);
++	dump_cfg_fmtint(sGssStrictAcceptor, o->gss_strict_acceptor);
++	dump_cfg_fmtint(sGssStoreRekey, o->gss_store_rekey);
+ #endif
+ #ifdef JPAKE
+ 	dump_cfg_fmtint(sZeroKnowledgePasswordAuthentication,
+diff --git servconf.h servconf.h
+index 870c709..06e21a9 100644
+--- servconf.h
++++ servconf.h
+@@ -110,7 +110,10 @@ typedef struct {
+ 	int     kerberos_get_afs_token;		/* If true, try to get AFS token if
+ 						 * authenticated with Kerberos. */
+ 	int     gss_authentication;	/* If true, permit GSSAPI authentication */
++	int     gss_keyex;		/* If true, permit GSSAPI key exchange */
+ 	int     gss_cleanup_creds;	/* If true, destroy cred cache on logout */
++	int 	gss_strict_acceptor;	/* If true, restrict the GSSAPI acceptor name */
++	int 	gss_store_rekey;
+ 	int     password_authentication;	/* If true, permit password
+ 						 * authentication. */
+ 	int     kbd_interactive_authentication;	/* If true, permit */
+diff --git ssh-gss.h ssh-gss.h
+index 077e13c..bc6e8f9 100644
+--- ssh-gss.h
++++ ssh-gss.h
+@@ -1,6 +1,6 @@
+ /* $OpenBSD: ssh-gss.h,v 1.10 2007/06/12 08:20:00 djm Exp $ */
+ /*
+- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
++ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
+  *
+  * Redistribution and use in source and binary forms, with or without
+  * modification, are permitted provided that the following conditions
+@@ -61,10 +61,22 @@
+ 
+ #define SSH_GSS_OIDTYPE 0x06
+ 
++#define SSH2_MSG_KEXGSS_INIT                            30
++#define SSH2_MSG_KEXGSS_CONTINUE                        31
++#define SSH2_MSG_KEXGSS_COMPLETE                        32
++#define SSH2_MSG_KEXGSS_HOSTKEY                         33
++#define SSH2_MSG_KEXGSS_ERROR                           34
++#define SSH2_MSG_KEXGSS_GROUPREQ			40
++#define SSH2_MSG_KEXGSS_GROUP				41
++#define KEX_GSS_GRP1_SHA1_ID				"gss-group1-sha1-"
++#define KEX_GSS_GRP14_SHA1_ID				"gss-group14-sha1-"
++#define KEX_GSS_GEX_SHA1_ID				"gss-gex-sha1-"
++
+ typedef struct {
+ 	char *filename;
+ 	char *envvar;
+ 	char *envval;
++	struct passwd *owner;
+ 	void *data;
+ } ssh_gssapi_ccache;
+ 
+@@ -72,8 +84,11 @@ typedef struct {
+ 	gss_buffer_desc displayname;
+ 	gss_buffer_desc exportedname;
+ 	gss_cred_id_t creds;
++	gss_name_t name;
+ 	struct ssh_gssapi_mech_struct *mech;
+ 	ssh_gssapi_ccache store;
++	int used;
++	int updated;
+ } ssh_gssapi_client;
+ 
+ typedef struct ssh_gssapi_mech_struct {
+@@ -84,6 +99,7 @@ typedef struct ssh_gssapi_mech_struct {
+ 	int (*userok) (ssh_gssapi_client *, char *);
+ 	int (*localname) (ssh_gssapi_client *, char **);
+ 	void (*storecreds) (ssh_gssapi_client *);
++	int (*updatecreds) (ssh_gssapi_ccache *, ssh_gssapi_client *);
+ } ssh_gssapi_mech;
+ 
+ typedef struct {
+@@ -94,10 +110,11 @@ typedef struct {
+ 	gss_OID		oid; /* client */
+ 	gss_cred_id_t	creds; /* server */
+ 	gss_name_t	client; /* server */
+-	gss_cred_id_t	client_creds; /* server */
++	gss_cred_id_t	client_creds; /* both */
+ } Gssctxt;
+ 
+ extern ssh_gssapi_mech *supported_mechs[];
++extern Gssctxt *gss_kex_context;
+ 
+ int  ssh_gssapi_check_oid(Gssctxt *, void *, size_t);
+ void ssh_gssapi_set_oid_data(Gssctxt *, void *, size_t);
+@@ -117,16 +134,30 @@ void ssh_gssapi_build_ctx(Gssctxt **);
+ void ssh_gssapi_delete_ctx(Gssctxt **);
+ OM_uint32 ssh_gssapi_sign(Gssctxt *, gss_buffer_t, gss_buffer_t);
+ void ssh_gssapi_buildmic(Buffer *, const char *, const char *, const char *);
+-int ssh_gssapi_check_mechanism(Gssctxt **, gss_OID, const char *);
++int ssh_gssapi_check_mechanism(Gssctxt **, gss_OID, const char *, const char *);
++OM_uint32 ssh_gssapi_client_identity(Gssctxt *, const char *);
++int ssh_gssapi_credentials_updated(Gssctxt *);
+ 
+ /* In the server */
++typedef int ssh_gssapi_check_fn(Gssctxt **, gss_OID, const char *, 
++    const char *);
++char *ssh_gssapi_client_mechanisms(const char *, const char *);
++char *ssh_gssapi_kex_mechs(gss_OID_set, ssh_gssapi_check_fn *, const char *,
++    const char *);
++gss_OID ssh_gssapi_id_kex(Gssctxt *, char *, int);
++int ssh_gssapi_server_check_mech(Gssctxt **,gss_OID, const char *, 
++    const char *);
+ OM_uint32 ssh_gssapi_server_ctx(Gssctxt **, gss_OID);
+-int ssh_gssapi_userok(char *name);
++int ssh_gssapi_userok(char *name, struct passwd *);
+ OM_uint32 ssh_gssapi_checkmic(Gssctxt *, gss_buffer_t, gss_buffer_t);
+ void ssh_gssapi_do_child(char ***, u_int *);
+ void ssh_gssapi_cleanup_creds(void);
+ void ssh_gssapi_storecreds(void);
+ 
++char *ssh_gssapi_server_mechanisms(void);
++int ssh_gssapi_oid_table_ok();
++
++int ssh_gssapi_update_creds(ssh_gssapi_ccache *store);
+ #endif /* GSSAPI */
+ 
+ #endif /* _SSH_GSS_H */
+diff --git ssh_config ssh_config
+index 1893674..2c06ba7 100644
+--- ssh_config
++++ ssh_config
+@@ -26,6 +26,8 @@
+ #   HostbasedAuthentication no
+ #   GSSAPIAuthentication no
+ #   GSSAPIDelegateCredentials no
++#   GSSAPIKeyExchange no
++#   GSSAPITrustDNS no
+ #   BatchMode no
+ #   CheckHostIP yes
+ #   AddressFamily any
+diff --git ssh_config.5 ssh_config.5
+index 269529c..bd3a712 100644
+--- ssh_config.5
++++ ssh_config.5
+@@ -530,11 +530,43 @@ Specifies whether user authentication based on GSSAPI is allowed.
+ The default is
+ .Dq no .
+ Note that this option applies to protocol version 2 only.
++.It Cm GSSAPIKeyExchange
++Specifies whether key exchange based on GSSAPI may be used. When using
++GSSAPI key exchange the server need not have a host key.
++The default is
++.Dq no .
++Note that this option applies to protocol version 2 only.
++.It Cm GSSAPIClientIdentity
++If set, specifies the GSSAPI client identity that ssh should use when 
++connecting to the server. The default is unset, which means that the default 
++identity will be used.
++.It Cm GSSAPIServerIdentity
++If set, specifies the GSSAPI server identity that ssh should expect when 
++connecting to the server. The default is unset, which means that the
++expected GSSAPI server identity will be determined from the target
++hostname.
+ .It Cm GSSAPIDelegateCredentials
+ Forward (delegate) credentials to the server.
+ The default is
+ .Dq no .
+-Note that this option applies to protocol version 2 only.
++Note that this option applies to protocol version 2 connections using GSSAPI.
++.It Cm GSSAPIRenewalForcesRekey
++If set to 
++.Dq yes
++then renewal of the client's GSSAPI credentials will force the rekeying of the
++ssh connection. With a compatible server, this can delegate the renewed 
++credentials to a session on the server.
++The default is
++.Dq no .
++.It Cm GSSAPITrustDns
++Set to 
++.Dq yes to indicate that the DNS is trusted to securely canonicalize
++the name of the host being connected to. If 
++.Dq no, the hostname entered on the
++command line will be passed untouched to the GSSAPI library.
++The default is
++.Dq no .
++This option only applies to protocol version 2 connections using GSSAPI.
+ .It Cm HashKnownHosts
+ Indicates that
+ .Xr ssh 1
+diff --git sshconnect2.c sshconnect2.c
+index 58015c0..1aa8523 100644
+--- sshconnect2.c
++++ sshconnect2.c
+@@ -160,9 +160,34 @@ ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
+ {
+ 	Kex *kex;
+ 
++#ifdef GSSAPI
++	char *orig = NULL, *gss = NULL;
++	char *gss_host = NULL;
++#endif
++
+ 	xxx_host = host;
+ 	xxx_hostaddr = hostaddr;
+ 
++#ifdef GSSAPI
++	if (options.gss_keyex) {
++		/* Add the GSSAPI mechanisms currently supported on this 
++		 * client to the key exchange algorithm proposal */
++		orig = myproposal[PROPOSAL_KEX_ALGS];
++
++		if (options.gss_trust_dns)
++			gss_host = (char *)get_canonical_hostname(1);
++		else
++			gss_host = host;
++
++		gss = ssh_gssapi_client_mechanisms(gss_host, options.gss_client_identity);
++		if (gss) {
++			debug("Offering GSSAPI proposal: %s", gss);
++			xasprintf(&myproposal[PROPOSAL_KEX_ALGS],
++			    "%s,%s", gss, orig);
++		}
++	}
++#endif
++
+ 	if (options.ciphers == (char *)-1) {
+ 		logit("No valid ciphers for protocol version 2 given, using defaults.");
+ 		options.ciphers = NULL;
+@@ -197,6 +222,17 @@ ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
+ 	if (options.kex_algorithms != NULL)
+ 		myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
+ 
++#ifdef GSSAPI
++	/* If we've got GSSAPI algorithms, then we also support the
++	 * 'null' hostkey, as a last resort */
++	if (options.gss_keyex && gss) {
++		orig = myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS];
++		xasprintf(&myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS], 
++		    "%s,null", orig);
++		xfree(gss);
++	}
++#endif
++
+ 	if (options.rekey_limit)
+ 		packet_set_rekey_limit((u_int32_t)options.rekey_limit);
+ 
+@@ -207,10 +243,30 @@ ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
+ 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
+ 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
+ 	kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
++#ifdef GSSAPI
++	if (options.gss_keyex) {
++		kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_client;
++		kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_client;
++		kex->kex[KEX_GSS_GEX_SHA1] = kexgss_client;
++	}
++#endif
+ 	kex->client_version_string=client_version_string;
+ 	kex->server_version_string=server_version_string;
+ 	kex->verify_host_key=&verify_host_key_callback;
+ 
++#ifdef GSSAPI
++	if (options.gss_keyex) {
++		kex->gss_deleg_creds = options.gss_deleg_creds;
++		kex->gss_trust_dns = options.gss_trust_dns;
++		kex->gss_client = options.gss_client_identity;
++		if (options.gss_server_identity) {
++			kex->gss_host = options.gss_server_identity;
++		} else {
++			kex->gss_host = gss_host;
++        }
++	}
++#endif
++
+ 	xxx_kex = kex;
+ 
+ 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
+@@ -306,6 +362,7 @@ void	input_gssapi_token(int type, u_int32_t, void *);
+ void	input_gssapi_hash(int type, u_int32_t, void *);
+ void	input_gssapi_error(int, u_int32_t, void *);
+ void	input_gssapi_errtok(int, u_int32_t, void *);
++int	userauth_gsskeyex(Authctxt *authctxt);
+ #endif
+ 
+ void	userauth(Authctxt *, char *);
+@@ -321,6 +378,11 @@ static char *authmethods_get(void);
+ 
+ Authmethod authmethods[] = {
+ #ifdef GSSAPI
++	{"gssapi-keyex",
++		userauth_gsskeyex,
++		NULL,
++		&options.gss_authentication,
++		NULL},
+ 	{"gssapi-with-mic",
+ 		userauth_gssapi,
+ 		NULL,
+@@ -627,19 +689,31 @@ userauth_gssapi(Authctxt *authctxt)
+ 	static u_int mech = 0;
+ 	OM_uint32 min;
+ 	int ok = 0;
++	const char *gss_host;
++
++	if (options.gss_server_identity)
++		gss_host = options.gss_server_identity;
++	else if (options.gss_trust_dns)
++		gss_host = get_canonical_hostname(1);
++	else
++		gss_host = authctxt->host;
+ 
+ 	/* Try one GSSAPI method at a time, rather than sending them all at
+ 	 * once. */
+ 
+ 	if (gss_supported == NULL)
+-		gss_indicate_mechs(&min, &gss_supported);
++		if (GSS_ERROR(gss_indicate_mechs(&min, &gss_supported))) {
++			gss_supported = NULL;
++			return 0;
++		}
+ 
+ 	/* Check to see if the mechanism is usable before we offer it */
+ 	while (mech < gss_supported->count && !ok) {
+ 		/* My DER encoding requires length<128 */
+ 		if (gss_supported->elements[mech].length < 128 &&
+ 		    ssh_gssapi_check_mechanism(&gssctxt, 
+-		    &gss_supported->elements[mech], authctxt->host)) {
++		    &gss_supported->elements[mech], gss_host, 
++                    options.gss_client_identity)) {
+ 			ok = 1; /* Mechanism works */
+ 		} else {
+ 			mech++;
+@@ -736,8 +810,8 @@ input_gssapi_response(int type, u_int32_t plen, void *ctxt)
+ {
+ 	Authctxt *authctxt = ctxt;
+ 	Gssctxt *gssctxt;
+-	int oidlen;
+-	char *oidv;
++	u_int oidlen;
++	u_char *oidv;
+ 
+ 	if (authctxt == NULL)
+ 		fatal("input_gssapi_response: no authentication context");
+@@ -847,6 +921,48 @@ input_gssapi_error(int type, u_int32_t plen, void *ctxt)
+ 	xfree(msg);
+ 	xfree(lang);
+ }
++
++int
++userauth_gsskeyex(Authctxt *authctxt)
++{
++	Buffer b;
++	gss_buffer_desc gssbuf;
++	gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
++	OM_uint32 ms;
++
++	static int attempt = 0;
++	if (attempt++ >= 1)
++		return (0);
++
++	if (gss_kex_context == NULL) {
++		debug("No valid Key exchange context"); 
++		return (0);
++	}
++
++	ssh_gssapi_buildmic(&b, authctxt->server_user, authctxt->service,
++	    "gssapi-keyex");
++
++	gssbuf.value = buffer_ptr(&b);
++	gssbuf.length = buffer_len(&b);
++
++	if (GSS_ERROR(ssh_gssapi_sign(gss_kex_context, &gssbuf, &mic))) {
++		buffer_free(&b);
++		return (0);
++	}
++
++	packet_start(SSH2_MSG_USERAUTH_REQUEST);
++	packet_put_cstring(authctxt->server_user);
++	packet_put_cstring(authctxt->service);
++	packet_put_cstring(authctxt->method->name);
++	packet_put_string(mic.value, mic.length);
++	packet_send();
++
++	buffer_free(&b);
++	gss_release_buffer(&ms, &mic);
++
++	return (1);
++}
++
+ #endif /* GSSAPI */
+ 
+ int
+diff --git sshd.c sshd.c
+index 3e9d176..d8faaeb 100644
+--- sshd.c
++++ sshd.c
+@@ -121,6 +121,10 @@
+ #include "ssh-sandbox.h"
+ #include "version.h"
+ 
++#ifdef USE_SECURITY_SESSION_API
++#include <Security/AuthSession.h>
++#endif
++
+ #ifdef LIBWRAP
+ #include <tcpd.h>
+ #include <syslog.h>
+@@ -1645,10 +1649,13 @@ main(int ac, char **av)
+ 		logit("Disabling protocol version 1. Could not load host key");
+ 		options.protocol &= ~SSH_PROTO_1;
+ 	}
++#ifndef GSSAPI
++	/* The GSSAPI key exchange can run without a host key */
+ 	if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
+ 		logit("Disabling protocol version 2. Could not load host key");
+ 		options.protocol &= ~SSH_PROTO_2;
+ 	}
++#endif
+ 	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
+ 		logit("sshd: no hostkeys available -- exiting.");
+ 		exit(1);
+@@ -1976,6 +1983,60 @@ main(int ac, char **av)
+ 	/* Log the connection. */
+ 	verbose("Connection from %.500s port %d", remote_ip, remote_port);
+ 
++#ifdef USE_SECURITY_SESSION_API
++	/*
++	 * Create a new security session for use by the new user login if
++	 * the current session is the root session or we are not launched
++	 * by inetd (eg: debugging mode or server mode).  We do not
++	 * necessarily need to create a session if we are launched from
++	 * inetd because Panther xinetd will create a session for us.
++	 *
++	 * The only case where this logic will fail is if there is an
++	 * inetd running in a non-root session which is not creating
++	 * new sessions for us.  Then all the users will end up in the
++	 * same session (bad).
++	 *
++	 * When the client exits, the session will be destroyed for us
++	 * automatically.
++	 *
++	 * We must create the session before any credentials are stored
++	 * (including AFS pags, which happens a few lines below).
++	 */
++	{
++		OSStatus err = 0;
++		SecuritySessionId sid = 0;
++		SessionAttributeBits sattrs = 0;
++
++		err = SessionGetInfo(callerSecuritySession, &sid, &sattrs);
++		if (err)
++			error("SessionGetInfo() failed with error %.8X",
++			    (unsigned) err);
++		else
++			debug("Current Session ID is %.8X / Session Attributes are %.8X",
++			    (unsigned) sid, (unsigned) sattrs);
++
++		if (inetd_flag && !(sattrs & sessionIsRoot))
++			debug("Running in inetd mode in a non-root session... "
++			    "assuming inetd created the session for us.");
++		else {
++			debug("Creating new security session...");
++			err = SessionCreate(0, sessionHasTTY | sessionIsRemote);
++			if (err)
++				error("SessionCreate() failed with error %.8X",
++				    (unsigned) err);
++
++			err = SessionGetInfo(callerSecuritySession, &sid, 
++			    &sattrs);
++			if (err)
++				error("SessionGetInfo() failed with error %.8X",
++				    (unsigned) err);
++			else
++				debug("New Session ID is %.8X / Session Attributes are %.8X",
++				    (unsigned) sid, (unsigned) sattrs);
++		}
++	}
++#endif
++
+ 	/*
+ 	 * We don't want to listen forever unless the other side
+ 	 * successfully authenticates itself.  So we set up an alarm which is
+@@ -2357,6 +2418,48 @@ do_ssh2_kex(void)
+ 
+ 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
+ 
++#ifdef GSSAPI
++	{
++	char *orig;
++	char *gss = NULL;
++	char *newstr = NULL;
++	orig = myproposal[PROPOSAL_KEX_ALGS];
++
++	/* 
++	 * If we don't have a host key, then there's no point advertising
++	 * the other key exchange algorithms
++	 */
++
++	if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]) == 0)
++		orig = NULL;
++
++	if (options.gss_keyex)
++		gss = ssh_gssapi_server_mechanisms();
++	else
++		gss = NULL;
++
++	if (gss && orig)
++		xasprintf(&newstr, "%s,%s", gss, orig);
++	else if (gss)
++		newstr = gss;
++	else if (orig)
++		newstr = orig;
++
++	/* 
++	 * If we've got GSSAPI mechanisms, then we've got the 'null' host
++	 * key alg, but we can't tell people about it unless its the only
++  	 * host key algorithm we support
++	 */
++	if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0)
++		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = "null";
++
++	if (newstr)
++		myproposal[PROPOSAL_KEX_ALGS] = newstr;
++	else
++		fatal("No supported key exchange algorithms");
++	}
++#endif
++
+ 	/* start key exchange */
+ 	kex = kex_setup(myproposal);
+ 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
+@@ -2364,6 +2467,13 @@ do_ssh2_kex(void)
+ 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
+ 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
+ 	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
++#ifdef GSSAPI
++	if (options.gss_keyex) {
++		kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
++		kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
++		kex->kex[KEX_GSS_GEX_SHA1] = kexgss_server;
++	}
++#endif
+ 	kex->server = 1;
+ 	kex->client_version_string=client_version_string;
+ 	kex->server_version_string=server_version_string;
+diff --git sshd_config sshd_config
+index 9cd2fdd..1af2afd 100644
+--- sshd_config
++++ sshd_config
+@@ -80,6 +80,8 @@ AuthorizedKeysFile	.ssh/authorized_keys
+ # GSSAPI options
+ #GSSAPIAuthentication no
+ #GSSAPICleanupCredentials yes
++#GSSAPIStrictAcceptorCheck yes
++#GSSAPIKeyExchange no
+ 
+ # Set this to 'yes' to enable PAM authentication, account processing, 
+ # and session processing. If this is enabled, PAM authentication will 
+diff --git sshd_config.5 sshd_config.5
+index cfa4806..935bb62 100644
+--- sshd_config.5
++++ sshd_config.5
+@@ -481,12 +481,40 @@ Specifies whether user authentication based on GSSAPI is allowed.
+ The default is
+ .Dq no .
+ Note that this option applies to protocol version 2 only.
++.It Cm GSSAPIKeyExchange
++Specifies whether key exchange based on GSSAPI is allowed. GSSAPI key exchange
++doesn't rely on ssh keys to verify host identity.
++The default is
++.Dq no .
++Note that this option applies to protocol version 2 only.
+ .It Cm GSSAPICleanupCredentials
+ Specifies whether to automatically destroy the user's credentials cache
+ on logout.
+ The default is
+ .Dq yes .
+ Note that this option applies to protocol version 2 only.
++.It Cm GSSAPIStrictAcceptorCheck
++Determines whether to be strict about the identity of the GSSAPI acceptor 
++a client authenticates against. If
++.Dq yes
++then the client must authenticate against the
++.Pa host
++service on the current hostname. If 
++.Dq no
++then the client may authenticate against any service key stored in the 
++machine's default store. This facility is provided to assist with operation 
++on multi homed machines. 
++The default is
++.Dq yes .
++Note that this option applies only to protocol version 2 GSSAPI connections,
++and setting it to 
++.Dq no
++may only work with recent Kerberos GSSAPI libraries.
++.It Cm GSSAPIStoreCredentialsOnRekey
++Controls whether the user's GSSAPI credentials should be updated following a 
++successful connection rekeying. This option can be used to accepted renewed 
++or updated credentials from a compatible client. The default is
++.Dq no .
+ .It Cm HostbasedAuthentication
+ Specifies whether rhosts or /etc/hosts.equiv authentication together
+ with successful public key client host authentication is allowed
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.macosforge.org/pipermail/macports-changes/attachments/20130720/591c3a9f/attachment-0001.html>


More information about the macports-changes mailing list