[112514] trunk/dports/net/openssh

sean at macports.org sean at macports.org
Thu Oct 24 21:14:15 PDT 2013


Revision: 112514
          https://trac.macports.org/changeset/112514
Author:   sean at macports.org
Date:     2013-10-24 21:14:14 -0700 (Thu, 24 Oct 2013)
Log Message:
-----------
openssh: update to 6.3p1 fixes #40804

Modified Paths:
--------------
    trunk/dports/net/openssh/Portfile
    trunk/dports/net/openssh/files/0002-Apple-keychain-integration-other-changes.patch

Added Paths:
-----------
    trunk/dports/net/openssh/files/openssh-6.3p1-gsskex-all-20130920.patch

Removed Paths:
-------------
    trunk/dports/net/openssh/files/openssh-6.2p2-gsskex-all-20110125.patch

Modified: trunk/dports/net/openssh/Portfile
===================================================================
--- trunk/dports/net/openssh/Portfile	2013-10-24 21:47:52 UTC (rev 112513)
+++ trunk/dports/net/openssh/Portfile	2013-10-25 04:14:14 UTC (rev 112514)
@@ -4,8 +4,7 @@
 PortSystem          1.0
 
 name                openssh
-version             6.2p2
-revision            3
+version             6.3p1
 
 categories          net
 platforms           darwin
@@ -29,8 +28,8 @@
 homepage            http://www.openbsd.org/openssh/
 
 checksums           ${distfiles} \
-                    rmd160  1fab1ae5f2db71b6f9e8bbbab574334c3985bd2d \
-                    sha256  7f29b9d2ad672ae0f9e1dcbff871fc5c2e60a194e90c766432e32161b842313b
+                    rmd160  df9e0946a1775c0e78669447f044724fdfc11e49 \
+                    sha256  aea575ededd3ebd45c05d42d0a87af22c79131a847ea440c54e3fdd223f5a420
 
 master_sites        openbsd:OpenSSH/portable \
                     http://mirror.mcs.anl.gov/openssh/portable/ \
@@ -101,12 +100,12 @@
 
 variant hpn conflicts gsskex description {Apply high performance patch} {
     # http://www.psc.edu/index.php/hpn-ssh
-    patch_sites-append      http://distfiles.gentoo.org/distfiles/:hpn
-    set hpn_patchfile       ${distname}-hpn14v1.diff.gz
-    patchfiles-append       ${hpn_patchfile}:hpn
+    patch_sites-append      sourceforge:hpnssh
+    set hpn_patchfile       ${distname}-hpnssh14v2.diff.gz
+    patchfiles-append       ${hpn_patchfile}
     checksums-append        ${hpn_patchfile} \
-                            rmd160  6e1593e58b093d0908a98f3bba5c3b187eabffc8 \
-                            sha256  5243c76ceecb2fd0934d87fd9c33604ff0241c00156e456bf5b7e40e407d8c90
+                            rmd160  8af79c3f63609da96d04b8e162f2b53cf7543be9 \
+                            sha256  23ae9307b58629ccf76a8ed5d9cf7215a45d6b7533d6b17eef17279fb9c48dca
 }
 
 variant gsskex conflicts hpn requires kerberos5 description "Add OpenSSH GSSAPI key exchange patch" {
@@ -116,8 +115,8 @@
                             "-D_UTMPX_COMPAT -D__APPLE_LAUNCHD__ -D__APPLE_MEMBERSHIP__" \
                             "-D__APPLE_XSAN__"]
     use_autoreconf          yes
-    patchfiles-append       openssh-6.2p2-gsskex-all-20110125.patch \
-                            0002-Apple-keychain-integration-other-changes.patch
+    patchfiles-append       0002-Apple-keychain-integration-other-changes.patch \
+                            openssh-6.3p1-gsskex-all-20130920.patch
     configure.args-append   --with-4in6 \
                             --with-audit=bsm \
                             --with-keychain=apple \
@@ -179,4 +178,6 @@
     fi"
 
 livecheck.type      regex
+# remove this after they update to p2 since there is a typo in the webpage
+livecheck.version   6.3p2
 livecheck.regex     OpenSSH ((\[5-9\].\[0-9\])(p\[0-9\]))

Modified: trunk/dports/net/openssh/files/0002-Apple-keychain-integration-other-changes.patch
===================================================================
--- trunk/dports/net/openssh/files/0002-Apple-keychain-integration-other-changes.patch	2013-10-24 21:47:52 UTC (rev 112513)
+++ trunk/dports/net/openssh/files/0002-Apple-keychain-integration-other-changes.patch	2013-10-25 04:14:14 UTC (rev 112514)
@@ -1,7 +1,26 @@
-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 @@
+# HG changeset patch
+# User Sean Farley <sean.michael.farley at gmail.com>
+# Date 1382624667 -28800
+#      Thu Oct 24 22:24:27 2013 +0800
+# Node ID dd6d51b7e12be5fab94a8779e890c5558e4d4001
+# Parent  86a3bc5c8ff689a291e86950a3d8fd327f42b870
+partial import
+
+
+wiggled scp
+
+
+wiggled readconf
+
+
+wiggled readconf.c
+
+diff --git a/Makefile.in b/Makefile.in
+--- a/Makefile.in
++++ b/Makefile.in
+@@ -56,10 +56,11 @@
+ PERL=@PERL@
+ SED=@SED@
  ENT=@ENT@
  XAUTH_PATH=@XAUTH_PATH@
  LDFLAGS=-L. -Lopenbsd-compat/ @LDFLAGS@
@@ -9,7 +28,11 @@
  EXEEXT=@EXEEXT@
  MANFMT=@MANFMT@
  
-@@ -96,6 +97,8 @@
+ TARGETS=ssh$(EXEEXT) sshd$(EXEEXT) ssh-add$(EXEEXT) ssh-keygen$(EXEEXT) ssh-keyscan${EXEEXT} ssh-keysign${EXEEXT} ssh-pkcs11-helper$(EXEEXT) ssh-agent$(EXEEXT) scp$(EXEEXT) sftp-server$(EXEEXT) sftp$(EXEEXT)
+ 
+@@ -93,10 +94,12 @@
+ 	sftp-server.o sftp-common.o \
+ 	roaming_common.o roaming_serv.o \
  	sandbox-null.o sandbox-rlimit.o sandbox-systrace.o sandbox-darwin.o \
  	sandbox-seccomp-filter.o
  
@@ -18,7 +41,11 @@
  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 @@
+ 
+ CONFIGFILES=sshd_config.out ssh_config.out moduli.out
+@@ -127,10 +130,11 @@
+ all: $(CONFIGFILES) $(MANPAGES) $(TARGETS)
+ 
  $(LIBSSH_OBJS): Makefile.in config.h
  $(SSHOBJS): Makefile.in config.h
  $(SSHDOBJS): Makefile.in config.h
@@ -26,7 +53,11 @@
  
  .c.o:
  	$(CC) $(CFLAGS) $(CPPFLAGS) -c $<
-@@ -141,8 +145,8 @@
+ 
+ LIBCOMPAT=openbsd-compat/libopenbsd-compat.a
+@@ -140,24 +144,24 @@
+ 
+ libssh.a: $(LIBSSH_OBJS)
  	$(AR) rv $@ $(LIBSSH_OBJS)
  	$(RANLIB) $@
  
@@ -37,7 +68,7 @@
  
  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)
  
@@ -53,7 +84,11 @@
  
  ssh-keygen$(EXEEXT): $(LIBCOMPAT) libssh.a ssh-keygen.o
  	$(LD) -o $@ ssh-keygen.o $(LDFLAGS) -lssh -lopenbsd-compat $(LIBS)
-@@ -265,7 +269,7 @@
+ 
+ ssh-keysign$(EXEEXT): $(LIBCOMPAT) libssh.a ssh-keysign.o roaming_dummy.o readconf.o
+@@ -265,11 +269,11 @@
+ 	$(INSTALL) -m 0755 $(STRIP_OPT) ssh-add$(EXEEXT) $(DESTDIR)$(bindir)/ssh-add$(EXEEXT)
+ 	$(INSTALL) -m 0755 $(STRIP_OPT) ssh-agent$(EXEEXT) $(DESTDIR)$(bindir)/ssh-agent$(EXEEXT)
  	$(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)
@@ -62,11 +97,14 @@
  	$(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 @@
+ 	$(INSTALL) -m 644 ssh.1.out $(DESTDIR)$(mandir)/$(mansubdir)1/ssh.1
+ 	$(INSTALL) -m 644 scp.1.out $(DESTDIR)$(mandir)/$(mansubdir)1/scp.1
+diff --git a/audit-bsm.c b/audit-bsm.c
+--- a/audit-bsm.c
++++ b/audit-bsm.c
+@@ -261,11 +261,16 @@
+ 	uid_t		uid = -1;
+ 	gid_t		gid = -1;
  	pid_t		pid = getpid();
  	AuditInfoTermID	tid = ssh_bsm_tid;
  
@@ -80,12 +118,15 @@
  		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);
+ 
+ 	rc = (typ == 0) ? 0 : -1;
+diff --git a/auth-pam.c b/auth-pam.c
+--- a/auth-pam.c
++++ b/auth-pam.c
+@@ -789,14 +789,15 @@
+ 				**echo_on = 0;
+ 				ctxt->pam_done = 1;
+ 				free(msg);
  				return (0);
  			}
 -			error("PAM: %s for %s%.100s from %.100s", msg,
@@ -98,10 +139,14 @@
  			/* 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 @@
+ 			**echo_on = 0;
+ 			free(msg);
+diff --git a/auth.c b/auth.c
+--- a/auth.c
++++ b/auth.c
+@@ -209,11 +209,11 @@
+ 			return 0;
+ 		}
  	}
  	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
  		/* Get the user's group access list (primary and supplementary) */
@@ -110,11 +155,14 @@
  			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 @@
+ 		}
+ 
+diff --git a/authfd.c b/authfd.c
+--- a/authfd.c
++++ b/authfd.c
+@@ -687,10 +687,33 @@
+ 	type = buffer_get_char(&msg);
+ 	buffer_free(&msg);
  	return decode_reply(type);
  }
  
@@ -144,10 +192,14 @@
  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 @@
+ 	switch (type) {
+ 	case SSH_AGENT_FAILURE:
+diff --git a/authfd.h b/authfd.h
+--- a/authfd.h
++++ b/authfd.h
+@@ -47,10 +47,13 @@
+ /* add key with constraints */
+ #define SSH_AGENTC_ADD_RSA_ID_CONSTRAINED	24
  #define SSH2_AGENTC_ADD_ID_CONSTRAINED		25
  #define SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED 26
  
@@ -157,10 +209,14 @@
  #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 @@
+ /* extended failure messages */
+ #define SSH2_AGENT_FAILURE			30
+diff --git a/config.h.in b/config.h.in
+--- a/config.h.in
++++ b/config.h.in
+@@ -75,10 +75,22 @@
+ #undef BROKEN_SNPRINTF
+ 
  /* FreeBSD strnvis does not do what we need */
  #undef BROKEN_STRNVIS
  
@@ -179,11 +235,14 @@
  /* 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 @@
+ /* updwtmpx is broken (if present) */
+ #undef BROKEN_UPDWTMPX
+diff --git a/configure.ac b/configure.ac
+--- a/configure.ac
++++ b/configure.ac
+@@ -4548,14 +4548,44 @@
+ #ifdef HAVE_LASTLOG_H
+ #include <lastlog.h>
  #endif
  	])
  
@@ -224,13 +283,15 @@
  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 @@
+ 	TEST_SSH_IPV6=yes
+ fi
+diff --git a/groupaccess.c b/groupaccess.c
+--- a/groupaccess.c
++++ b/groupaccess.c
+@@ -32,62 +32,107 @@
+ #include <unistd.h>
  #include <stdarg.h>
+ #include <stdlib.h>
  #include <string.h>
  
 +#ifdef __APPLE_MEMBERSHIP__
@@ -279,17 +340,17 @@
  	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));
++	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
+ #endif
+-
+-	groups_bygid = xcalloc(ngroups, sizeof(*groups_bygid));
  	groups_byname = xcalloc(ngroups, sizeof(*groups_byname));
 -
 -	if (getgrouplist(user, base, groups_bygid, &ngroups) == -1)
@@ -297,14 +358,17 @@
 +#ifndef __APPLE_MEMBERSHIP__
 +	if (getgrouplist(pw->pw_name, pw->pw_gid, groups_bygid, &ngroups) == -1) {
 +	    logit("getgrouplist: groups list too small");
-+		xfree(groups_bygid);
++		free(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 @@
+ 	free(groups_bygid);
+ 	return (ngroups = j);
+ }
+ 
  /*
   * Return 1 if one of user's groups is contained in groups.
   * Return 0 otherwise.  Use match_pattern() for string comparison.
@@ -337,10 +401,14 @@
  	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 @@
+ /*
+  * Return 1 if one of user's groups matches group_pattern list.
+diff --git a/groupaccess.h b/groupaccess.h
+--- a/groupaccess.h
++++ b/groupaccess.h
+@@ -25,11 +25,11 @@
+  */
+ 
  #ifndef GROUPACCESS_H
  #define GROUPACCESS_H
  
@@ -349,26 +417,780 @@
  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 @@
+ 
+ #endif
+diff --git a/keychain.c b/keychain.c
+new file mode 100644
+--- /dev/null
++++ b/keychain.c
+@@ -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)
++		free(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)
++			free(filename);
++		if (passphrase)
++			free(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 freeing), 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);
++		free(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)
++		free(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
++
++}
+diff --git a/keychain.h b/keychain.h
+new file mode 100644
+--- /dev/null
++++ b/keychain.h
+@@ -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);
+diff --git a/readconf.c b/readconf.c
+--- a/readconf.c
++++ b/readconf.c
+@@ -136,10 +136,13 @@
+ 	oSendEnv, oControlPath, oControlMaster, oControlPersist,
+ 	oHashKnownHosts,
  	oTunnel, oTunnelDevice, oLocalCommand, oPermitLocalCommand,
  	oVisualHostKey, oUseRoaming, oZeroKnowledgePasswordAuthentication,
- 	oKexAlgorithms, oIPQoS, oRequestTTY,
+ 	oKexAlgorithms, oIPQoS, oRequestTTY, oIgnoreUnknown,
 +#ifdef __APPLE_KEYCHAIN__
 +	oAskPassGUI,
 +#endif
- 	oDeprecated, oUnsupported
+ 	oIgnoredUnknownOption, oDeprecated, oUnsupported
  } OpCodes;
  
-@@ -257,7 +260,9 @@
+ /* Textual representations of the tokens. */
+ 
+@@ -248,11 +251,13 @@
+ #endif
  	{ "kexalgorithms", oKexAlgorithms },
  	{ "ipqos", oIPQoS },
  	{ "requesttty", oRequestTTY },
+ 	{ "ignoreunknown", oIgnoreUnknown },
 -
 +#ifdef __APPLE_KEYCHAIN__
 +	{ "askpassgui", oAskPassGUI },
@@ -376,10 +1198,14 @@
  	{ NULL, oBadOption }
  };
  
-@@ -1093,6 +1098,12 @@
- 			*intptr = value;
- 		break;
+ /*
+  * Adds a local TCP/IP port forward to options.  Never returns if there is an
+@@ -1070,10 +1075,16 @@
  
+ 	case oIgnoreUnknown:
+ 		charptr = &options->ignored_unknown;
+ 		goto parse_string;
+ 
 +#ifdef __APPLE_KEYCHAIN__
 +	case oAskPassGUI:
 +		intptr = &options->ask_pass_gui;
@@ -389,17 +1215,25 @@
  	case oDeprecated:
  		debug("%s line %d: Deprecated option \"%s\"",
  		    filename, linenum, keyword);
-@@ -1258,6 +1269,9 @@
+ 		return 0;
+ 
+@@ -1232,10 +1243,13 @@
+ 	options->zero_knowledge_password_authentication = -1;
  	options->ip_qos_interactive = -1;
  	options->ip_qos_bulk = -1;
  	options->request_tty = -1;
+ 	options->ignored_unknown = NULL;
 +#ifdef __APPLE_KEYCHAIN__
 +	options->ask_pass_gui = -1;
 +#endif
  }
  
  /*
-@@ -1415,6 +1429,10 @@
+  * Called after processing other sources of option data, this fills those
+  * options for which no value has been specified with their default values.
+@@ -1383,10 +1397,14 @@
+ 		options->ip_qos_interactive = IPTOS_LOWDELAY;
+ 	if (options->ip_qos_bulk == -1)
  		options->ip_qos_bulk = IPTOS_THROUGHPUT;
  	if (options->request_tty == -1)
  		options->request_tty = REQUEST_TTY_AUTO;
@@ -410,14 +1244,17 @@
  	/* 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 @@
+ 	/* options->hostname will be set in the main program if appropriate */
+ 	/* options->host_key_alias should not be set by default */
+diff --git a/readconf.h b/readconf.h
+--- a/readconf.h
++++ b/readconf.h
+@@ -137,10 +137,14 @@
  	int	use_roaming;
  
  	int	request_tty;
+ 
+ 	char	*ignored_unknown; /* Pattern list of unknown tokens to ignore */
 +
 +#ifdef __APPLE_KEYCHAIN__
 +	int ask_pass_gui;
@@ -425,13 +1262,14 @@
  }       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 @@
+ #define SSHCTL_MASTER_YES	1
+ #define SSHCTL_MASTER_AUTO	2
+diff --git a/scp.1 b/scp.1
+--- a/scp.1
++++ b/scp.1
+@@ -17,11 +17,11 @@
+ .Nm scp
+ .Nd secure copy (remote file copy program)
  .Sh SYNOPSIS
  .Nm scp
  .Bk -words
@@ -440,7 +1278,11 @@
  .Op Fl c Ar cipher
  .Op Fl F Ar ssh_config
  .Op Fl i Ar identity_file
-@@ -97,6 +97,8 @@
+ .Op Fl l Ar limit
+ .Op Fl o Ar ssh_option
+@@ -95,10 +95,12 @@
+ Passes the
+ .Fl C
  flag to
  .Xr ssh 1
  to enable compression.
@@ -449,10 +1291,14 @@
  .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 @@
+ .Xr ssh 1 .
+ .It Fl F Ar ssh_config
+diff --git a/scp.c b/scp.c
+--- a/scp.c
++++ b/scp.c
+@@ -76,10 +76,13 @@
+ #include <sys/types.h>
+ #include <sys/param.h>
  #ifdef HAVE_SYS_STAT_H
  # include <sys/stat.h>
  #endif
@@ -462,7 +1308,11 @@
  #ifdef HAVE_POLL_H
  #include <poll.h>
  #else
-@@ -114,6 +117,11 @@
+ # ifdef HAVE_SYS_POLL_H
+ #  include <sys/poll.h>
+@@ -112,10 +115,15 @@
+ #include "pathnames.h"
+ #include "log.h"
  #include "misc.h"
  #include "progressmeter.h"
  
@@ -474,7 +1324,11 @@
  extern char *__progname;
  
  #define COPY_BUFLEN	16384
-@@ -150,6 +158,12 @@
+ 
+ int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
+@@ -148,10 +156,16 @@
+ char *ssh_program = _PATH_SSH_PROGRAM;
+ 
  /* This is used to store the pid of ssh_program */
  pid_t do_cmd_pid = -1;
  
@@ -487,7 +1341,11 @@
  static void
  killchild(int signo)
  {
-@@ -395,7 +409,11 @@
+ 	if (do_cmd_pid > 1) {
+ 		kill(do_cmd_pid, signo ? signo : SIGTERM);
+@@ -393,11 +407,15 @@
+ 	addargs(&args, "-oForwardAgent=no");
+ 	addargs(&args, "-oPermitLocalCommand=no");
  	addargs(&args, "-oClearAllForwardings=yes");
  
  	fflag = tflag = 0;
@@ -499,7 +1357,11 @@
  		switch (ch) {
  		/* User-visible flags. */
  		case '1':
-@@ -456,6 +474,11 @@
+ 		case '2':
+ 		case '4':
+@@ -454,10 +472,15 @@
+ 			addargs(&args, "-q");
+ 			addargs(&remote_remote_args, "-q");
  			showprogress = 0;
  			break;
  
@@ -511,7 +1373,11 @@
  		/* Server options. */
  		case 'd':
  			targetshouldbedirectory = 1;
-@@ -505,7 +528,12 @@
+ 			break;
+ 		case 'f':	/* "from" */
+@@ -503,11 +526,16 @@
+ 		targetshouldbedirectory = 1;
+ 
  	remin = remout = -1;
  	do_cmd_pid = -1;
  	/* Command to be executed on remote system using "ssh". */
@@ -524,7 +1390,11 @@
  	    verbose_mode ? " -v" : "",
  	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
  	    targetshouldbedirectory ? " -d" : "");
-@@ -733,6 +761,10 @@
+ 
+ 	(void) signal(SIGPIPE, lostconn);
+@@ -749,23 +777,41 @@
+ 	off_t i, statbytes;
+ 	size_t amt;
  	int fd = -1, haderr, indx;
  	char *last, *name, buf[2048], encname[MAXPATHLEN];
  	int len;
@@ -535,7 +1405,7 @@
  
  	for (indx = 0; indx < argc; ++indx) {
  		name = argv[indx];
-@@ -740,12 +772,26 @@
+ 		statbytes = 0;
  		len = strlen(name);
  		while (len > 1 && name[len-1] == '/')
  			name[--len] = '\0';
@@ -562,7 +1432,11 @@
  		if (fstat(fd, &stb) < 0) {
  syserr:			run_err("%s: %s", name, strerror(errno));
  			goto next;
-@@ -842,6 +888,36 @@
+ 		}
+ 		if (stb.st_size < 0) {
+@@ -844,10 +890,40 @@
+ 		if (!haderr)
+ 			(void) atomicio(vwrite, remout, "", 1);
  		else
  			run_err("%s: %s", name, strerror(haderr));
  		(void) response();
@@ -599,7 +1473,11 @@
  	}
  }
  
-@@ -936,6 +1012,10 @@
+ void
+ rsource(char *name, struct stat *statp)
+@@ -935,10 +1011,14 @@
+ 
+ 	(void) atomicio(vwrite, remout, "", 1);
  	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
  		targisdir = 1;
  	for (first = 1;; first = 0) {
@@ -610,10 +1488,14 @@
  		cp = buf;
  		if (atomicio(read, remin, cp, 1) != 1)
  			return;
-@@ -1069,10 +1149,51 @@
+ 		if (*cp++ == '\n')
+ 			SCREWUP("unexpected <newline>");
+@@ -1080,14 +1160,55 @@
+ 			free(vect[0]);
+ 			continue;
  		}
  		omode = mode;
- 		mode |= S_IWRITE;
+ 		mode |= S_IWUSR;
 +
 +#if HAVE_COPYFILE
 +		if (copy_xattr && !strncmp(basename(curfile), "._", 2))
@@ -662,7 +1544,11 @@
  		(void) atomicio(vwrite, remout, "", 1);
  		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
  			(void) close(ofd);
-@@ -1157,6 +1278,29 @@
+ 			continue;
+ 		}
+@@ -1168,10 +1289,33 @@
+ 		if (close(ofd) == -1) {
+ 			wrerr = YES;
  			wrerrno = errno;
  		}
  		(void) response();
@@ -692,7 +1578,11 @@
  		if (setimes && wrerr == NO) {
  			setimes = 0;
  			if (utimes(np, tv) < 0) {
-@@ -1218,7 +1362,11 @@
+ 				run_err("%s: set times: %s",
+ 				    np, strerror(errno));
+@@ -1229,11 +1373,15 @@
+ 
+ void
  usage(void)
  {
  	(void) fprintf(stderr,
@@ -704,11 +1594,14 @@
  	    "           [-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 @@
+ }
+ 
+diff --git a/servconf.c b/servconf.c
+--- a/servconf.c
++++ b/servconf.c
+@@ -158,11 +158,11 @@
+ void
+ fill_default_server_options(ServerOptions *options)
  {
  	/* Portable-specific options */
  	if (options->use_pam == -1)
@@ -717,16 +1610,24 @@
  
  	/* Standard Options */
  	if (options->protocol == SSH_PROTO_UNKNOWN)
-@@ -245,7 +245,7 @@
- 	if (options->gss_store_rekey == -1)
- 		options->gss_store_rekey = 0;
+ 		options->protocol = SSH_PROTO_2;
+ 	if (options->num_host_key_files == 0) {
+@@ -241,11 +241,11 @@
+ 	if (options->gss_authentication == -1)
+ 		options->gss_authentication = 0;
+ 	if (options->gss_cleanup_creds == -1)
+ 		options->gss_cleanup_creds = 1;
  	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 @@
+ 		options->challenge_response_authentication = 1;
+ 	if (options->permit_empty_passwd == -1)
+@@ -621,11 +621,11 @@
+ 		goto out;
+ 
  	if ((pw = getpwnam(user)) == NULL) {
  		debug("Can't match group at line %d because user %.100s does "
  		    "not exist", line, user);
@@ -735,11 +1636,14 @@
  		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 @@
+ 		debug("user %.100s does not match group list %.100s at line %d",
+ 		    user, grps, line);
+diff --git a/session.c b/session.c
+--- a/session.c
++++ b/session.c
+@@ -2081,12 +2081,14 @@
+ 	/* for SSH1 the tty modes length is not given */
+ 	if (!compat20)
  		n_bytes = packet_remaining();
  	tty_parse_modes(s->ttyfd, &n_bytes);
  
@@ -750,7 +1654,11 @@
  
  	/* Set window size from the packet. */
  	pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
-@@ -2312,9 +2314,11 @@
+ 
+ 	packet_check_eom();
+@@ -2322,13 +2324,15 @@
+ 
+ 	/* Record that the user has logged out. */
  	if (s->pid != 0)
  		record_logout(s->pid, s->tty, s->pw->pw_name);
  
@@ -762,11 +1670,14 @@
  
  	/*
  	 * 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 @@
+ 	 * the pty cleanup, so that another process doesn't get this pty
+ 	 * while we're still cleaning up.
+diff --git a/ssh-add.0 b/ssh-add.0
+--- a/ssh-add.0
++++ b/ssh-add.0
+@@ -2,11 +2,11 @@
+ 
+ NAME
       ssh-add - adds private key identities to the authentication agent
  
  SYNOPSIS
@@ -775,7 +1686,11 @@
       ssh-add -s pkcs11
       ssh-add -e pkcs11
  
-@@ -55,6 +55,13 @@
+ DESCRIPTION
+      ssh-add adds private key identities to the authentication agent,
+@@ -53,10 +53,17 @@
+              represented by the agent.
+ 
       -l      Lists fingerprints of all identities currently represented by the
               agent.
  
@@ -789,11 +1704,14 @@
       -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 @@
+      -t life
+              Set a maximum lifetime when adding identities to an agent.  The
+diff --git a/ssh-add.1 b/ssh-add.1
+--- a/ssh-add.1
++++ b/ssh-add.1
+@@ -41,11 +41,11 @@
+ .Sh NAME
+ .Nm ssh-add
  .Nd adds private key identities to the authentication agent
  .Sh SYNOPSIS
  .Nm ssh-add
@@ -802,7 +1720,11 @@
  .Op Fl t Ar life
  .Op Ar
  .Nm ssh-add
-@@ -118,6 +118,13 @@
+ .Fl s Ar pkcs11
+ .Nm ssh-add
+@@ -116,10 +116,17 @@
+ .It Fl L
+ Lists public key parameters of all identities currently represented
  by the agent.
  .It Fl l
  Lists fingerprints of all identities currently represented by the agent.
@@ -816,11 +1738,14 @@
  .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 @@
+ .It Fl t Ar life
+ Set a maximum lifetime when adding identities to an agent.
+diff --git a/ssh-add.c b/ssh-add.c
+--- a/ssh-add.c
++++ b/ssh-add.c
+@@ -60,10 +60,11 @@
+ #include "buffer.h"
+ #include "authfd.h"
  #include "authfile.h"
  #include "pathnames.h"
  #include "misc.h"
@@ -828,7 +1753,11 @@
  
  /* argv0 */
  extern char *__progname;
-@@ -96,12 +97,24 @@
+ 
+ /* Default files to add */
+@@ -94,16 +95,28 @@
+ 		pass = NULL;
+ 	}
  }
  
  static int
@@ -854,7 +1783,11 @@
  	public = key_load_public(filename, &comment);
  	if (public == NULL) {
  		printf("Bad key file %s\n", filename);
-@@ -164,7 +177,7 @@
+ 		return -1;
+ 	}
+@@ -162,11 +175,11 @@
+ 
+ 	return ret;
  }
  
  static int
@@ -863,7 +1796,11 @@
  {
  	Key *private, *cert;
  	char *comment = NULL;
-@@ -201,11 +214,16 @@
+ 	char msg[1024], *certpath = NULL;
+ 	int fd, perms_ok, ret = -1;
+@@ -199,15 +212,20 @@
+ 	}
+ 	close(fd);
  
  	/* At first, try empty passphrase */
  	private = key_parse_private(&keyblob, filename, "", &comment);
@@ -881,7 +1818,11 @@
  	if (private == NULL) {
  		/* clear passphrase since it did not work */
  		clear_pass();
-@@ -221,8 +239,11 @@
+ 		snprintf(msg, sizeof msg, "Enter passphrase for %.200s: ",
+ 		    comment);
+@@ -219,12 +237,15 @@
+ 				buffer_free(&keyblob);
+ 				return -1;
  			}
  			private = key_parse_private(&keyblob, filename, pass,
  			    &comment);
@@ -894,7 +1835,11 @@
  			clear_pass();
  			snprintf(msg, sizeof msg,
  			    "Bad passphrase, try again for %.200s: ", comment);
-@@ -376,13 +397,13 @@
+ 		}
+ 	}
+@@ -374,17 +395,17 @@
+ 	free(p1);
+ 	return (ret);
  }
  
  static int
@@ -911,7 +1856,11 @@
  			return -1;
  	}
  	return 0;
-@@ -404,6 +425,11 @@
+ }
+ 
+@@ -402,20 +423,26 @@
+ 	fprintf(stderr, "  -D          Delete all identities.\n");
+ 	fprintf(stderr, "  -x          Lock agent.\n");
  	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");
@@ -923,7 +1872,10 @@
  }
  
  int
-@@ -414,6 +440,7 @@
+ main(int argc, char **argv)
+ {
+ 	extern char *optarg;
+ 	extern int optind;
  	AuthenticationConnection *ac = NULL;
  	char *pkcs11provider = NULL;
  	int i, ch, deleting = 0, ret = 0, key_only = 0;
@@ -931,7 +1883,11 @@
  
  	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
  	sanitise_stdfd();
-@@ -430,7 +457,7 @@
+ 
+ 	__progname = ssh_get_progname(argv[0]);
+@@ -428,11 +455,11 @@
+ 	if (ac == NULL) {
+ 		fprintf(stderr,
  		    "Could not open a connection to your authentication agent.\n");
  		exit(2);
  	}
@@ -940,7 +1896,11 @@
  		switch (ch) {
  		case 'k':
  			key_only = 1;
-@@ -469,6 +496,13 @@
+ 			break;
+ 		case 'l':
+@@ -467,10 +494,17 @@
+ 				fprintf(stderr, "Invalid lifetime\n");
+ 				ret = 1;
  				goto done;
  			}
  			break;
@@ -954,7 +1914,11 @@
  		default:
  			usage();
  			ret = 1;
-@@ -500,7 +534,7 @@
+ 			goto done;
+ 		}
+@@ -498,20 +532,20 @@
+ 		for (i = 0; default_files[i]; i++) {
+ 			snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir,
  			    default_files[i]);
  			if (stat(buf, &st) < 0)
  				continue;
@@ -963,7 +1927,8 @@
  				ret = 1;
  			else
  				count++;
-@@ -509,7 +543,7 @@
+ 		}
+ 		if (count == 0)
  			ret = 1;
  	} else {
  		for (i = 0; i < argc; i++) {
@@ -972,11 +1937,14 @@
  				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 @@
+ 	clear_pass();
+ 
+diff --git a/ssh-agent.c b/ssh-agent.c
+--- a/ssh-agent.c
++++ b/ssh-agent.c
+@@ -63,20 +63,25 @@
+ #include <stdio.h>
+ #include <stdlib.h>
  #include <time.h>
  #include <string.h>
  #include <unistd.h>
@@ -986,7 +1954,7 @@
  
  #include "xmalloc.h"
  #include "ssh.h"
-@@ -72,9 +75,11 @@
+ #include "rsa.h"
  #include "buffer.h"
  #include "key.h"
  #include "authfd.h"
@@ -998,7 +1966,11 @@
  
  #ifdef ENABLE_PKCS11
  #include "ssh-pkcs11.h"
-@@ -793,6 +798,61 @@
+ #endif
+ 
+@@ -788,10 +793,65 @@
+ 	buffer_put_char(&e->output,
+ 	    success ? SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE);
  }
  #endif /* ENABLE_PKCS11 */
  
@@ -1060,7 +2032,11 @@
  /* dispatch incoming messages */
  
  static void
-@@ -885,6 +945,9 @@
+ process_message(SocketEntry *e)
+ {
+@@ -880,10 +940,13 @@
+ 		break;
+ 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
  		process_remove_smartcard_key(e);
  		break;
  #endif /* ENABLE_PKCS11 */
@@ -1070,7 +2046,11 @@
  	default:
  		/* Unknown message.  Respond with failure. */
  		error("Unknown message %d", type);
-@@ -1126,7 +1189,11 @@
+ 		buffer_clear(&e->request);
+ 		buffer_put_int(&e->output, 1);
+@@ -1120,11 +1183,15 @@
+ }
+ 
  int
  main(int ac, char **av)
  {
@@ -1082,7 +2062,11 @@
  	int sock, fd, ch, result, saved_errno;
  	u_int nalloc;
  	char *shell, *format, *pidstr, *agentsocket = NULL;
-@@ -1160,7 +1227,11 @@
+ 	fd_set *readsetp = NULL, *writesetp = NULL;
+ 	struct sockaddr_un sunaddr;
+@@ -1154,20 +1221,29 @@
+ 	OpenSSL_add_all_algorithms();
+ 
  	__progname = ssh_get_progname(av[0]);
  	seed_rng();
  
@@ -1094,7 +2078,9 @@
  		switch (ch) {
  		case 'c':
  			if (s_flag)
-@@ -1170,6 +1241,11 @@
+ 				usage();
+ 			c_flag++;
+ 			break;
  		case 'k':
  			k_flag++;
  			break;
@@ -1106,7 +2092,11 @@
  		case 's':
  			if (c_flag)
  				usage();
-@@ -1196,7 +1272,11 @@
+ 			s_flag++;
+ 			break;
+@@ -1190,11 +1266,15 @@
+ 		}
+ 	}
  	ac -= optind;
  	av += optind;
  
@@ -1118,7 +2108,11 @@
  		usage();
  
  	if (ac == 0 && !c_flag && !s_flag) {
-@@ -1252,6 +1332,53 @@
+ 		shell = getenv("SHELL");
+ 		if (shell != NULL && (len = strlen(shell)) > 2 &&
+@@ -1246,10 +1326,57 @@
+ 
+ 	/*
  	 * Create socket early so it will exist before command gets run from
  	 * the parent.
  	 */
@@ -1172,7 +2166,11 @@
  	sock = socket(AF_UNIX, SOCK_STREAM, 0);
  	if (sock < 0) {
  		perror("socket");
-@@ -1273,6 +1400,14 @@
+ 		*socket_name = '\0'; /* Don't unlink any existing file */
+ 		cleanup_exit(1);
+@@ -1267,10 +1394,18 @@
+ 	umask(prev_mask);
+ 	if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
  		perror("listen");
  		cleanup_exit(1);
  	}
@@ -1187,7 +2185,11 @@
  
  	/*
  	 * Fork, and have the parent execute the command, if any, or present
-@@ -1345,6 +1480,7 @@
+ 	 * the socket data.  The child continues as the authentication agent.
+ 	 */
+@@ -1339,19 +1474,24 @@
+ 
+ #ifdef ENABLE_PKCS11
  	pkcs11_init(0);
  #endif
  	new_socket(AUTH_SOCKET, sock);
@@ -1195,7 +2197,9 @@
  	if (ac > 0)
  		parent_alive_interval = 10;
  	idtab_init();
-@@ -1355,6 +1491,10 @@
+ 	signal(SIGPIPE, SIG_IGN);
+ 	signal(SIGINT, d_flag ? cleanup_handler : SIG_IGN);
+ 	signal(SIGHUP, cleanup_handler);
  	signal(SIGTERM, cleanup_handler);
  	nalloc = 0;
  
@@ -1206,10 +2210,14 @@
  	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 @@
+ 		saved_errno = errno;
+ 		if (parent_alive_interval != 0)
+diff --git a/ssh-keysign.8 b/ssh-keysign.8
+--- a/ssh-keysign.8
++++ b/ssh-keysign.8
+@@ -69,10 +69,13 @@
+ They should be owned by root, readable only by root, and not
+ accessible to others.
  Since they are readable only by root,
  .Nm
  must be set-uid root if host-based authentication is used.
@@ -1219,10 +2227,14 @@
  .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 @@
+ .It Pa /etc/ssh/ssh_host_rsa_key-cert.pub
+ If these files exist they are assumed to contain public certificate
+diff --git a/sshconnect1.c b/sshconnect1.c
+--- a/sshconnect1.c
++++ b/sshconnect1.c
+@@ -45,10 +45,11 @@
+ #include "authfile.h"
+ #include "misc.h"
  #include "canohost.h"
  #include "hostfile.h"
  #include "auth.h"
@@ -1230,7 +2242,11 @@
  
  /* Session id for the current session. */
  u_char session_id[16];
-@@ -260,6 +261,10 @@
+ u_int supported_authentications = 0;
+ 
+@@ -258,10 +259,14 @@
+ 		    &perm_ok);
+ 	if (private == NULL && !options.batch_mode && perm_ok) {
  		snprintf(buf, sizeof(buf),
  		    "Enter passphrase for RSA key '%.100s': ", comment);
  		for (i = 0; i < options.number_of_password_prompts; i++) {
@@ -1241,10 +2257,14 @@
  			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 @@
+ 				    authfile, passphrase, NULL, NULL);
+ 				quit = 0;
+diff --git a/sshconnect2.c b/sshconnect2.c
+--- a/sshconnect2.c
++++ b/sshconnect2.c
+@@ -70,10 +70,11 @@
+ #include "pathnames.h"
+ #include "uidswap.h"
  #include "hostfile.h"
  #include "schnorr.h"
  #include "jpake.h"
@@ -1252,7 +2272,11 @@
  
  #ifdef GSSAPI
  #include "ssh-gss.h"
-@@ -1449,6 +1450,10 @@
+ #endif
+ 
+@@ -1331,10 +1332,14 @@
+ 		if (options.batch_mode)
+ 			return NULL;
  		snprintf(prompt, sizeof prompt,
  		    "Enter passphrase for key '%.100s': ", filename);
  		for (i = 0; i < options.number_of_password_prompts; i++) {
@@ -1263,11 +2287,14 @@
  			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 @@
+ 				    filename, passphrase, NULL, NULL);
+ 				quit = 0;
+diff --git a/sshd.0 b/sshd.0
+--- a/sshd.0
++++ b/sshd.0
+@@ -620,12 +620,12 @@
+              The content of this file is not sensitive; it can be world-
+              readable.
  
  SEE ALSO
       scp(1), sftp(1), ssh(1), ssh-add(1), ssh-agent(1), ssh-keygen(1),
@@ -1278,11 +2305,14 @@
  
  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 @@
+      Tatu Ylonen.  Aaron Campbell, Bob Beck, Markus Friedl, Niels Provos, Theo
+      de Raadt and Dug Song removed many bugs, re-added newer features and
+diff --git a/sshd.8 b/sshd.8
+--- a/sshd.8
++++ b/sshd.8
+@@ -954,14 +954,11 @@
+ .Xr ssh-agent 1 ,
+ .Xr ssh-keygen 1 ,
  .Xr ssh-keyscan 1 ,
  .Xr chroot 2 ,
  .Xr hosts_access 5 ,
@@ -1293,11 +2323,14 @@
  .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 @@
+ ssh 1.2.12 release by Tatu Ylonen.
+ Aaron Campbell, Bob Beck, Markus Friedl, Niels Provos,
+diff --git a/sshd.c b/sshd.c
+--- a/sshd.c
++++ b/sshd.c
+@@ -2106,23 +2106,23 @@
+ 
+ #ifdef SSH_AUDIT_EVENTS
  	audit_event(SSH_AUTH_SUCCESS);
  #endif
  
@@ -1310,7 +2343,7 @@
  #ifdef GSSAPI
  	if (options.gss_authentication) {
  		temporarily_use_uid(authctxt->pw);
-@@ -2115,12 +2121,6 @@
+ 		ssh_gssapi_storecreds();
  		restore_uid();
  	}
  #endif
@@ -1323,11 +2356,14 @@
  
  	/*
  	 * 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 @@
+ 	 * file descriptor passing.
+ 	 */
+diff --git a/sshd_config b/sshd_config
+--- a/sshd_config
++++ b/sshd_config
+@@ -32,11 +32,11 @@
+ # Ciphers and keying
+ #RekeyLimit default none
  
  # Logging
  # obsoletes QuietMode and FascistLogging
@@ -1336,7 +2372,11 @@
  #LogLevel INFO
  
  # Authentication:
-@@ -64,8 +64,9 @@
+ 
+ #LoginGraceTime 2m
+@@ -65,12 +65,13 @@
+ # RhostsRSAAuthentication and HostbasedAuthentication
+ #IgnoreUserKnownHosts no
  # Don't read the user's ~/.rhosts and ~/.shosts files
  #IgnoreRhosts yes
  
@@ -1348,7 +2388,11 @@
  #PermitEmptyPasswords no
  
  # Change to no to disable s/key passwords
-@@ -92,7 +93,10 @@
+ #ChallengeResponseAuthentication yes
+ 
+@@ -91,11 +92,14 @@
+ # PAM authentication via ChallengeResponseAuthentication may bypass
+ # the setting of "PermitRootLogin without-password".
  # 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'.
@@ -1360,10 +2404,14 @@
  
  #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 @@
+ #GatewayPorts no
+ #X11Forwarding no
+diff --git a/sshd_config.0 b/sshd_config.0
+--- a/sshd_config.0
++++ b/sshd_config.0
+@@ -505,11 +505,11 @@
+              increases linearly and all connection attempts are refused if the
+              number of unauthenticated connections reaches ``full'' (60).
  
       PasswordAuthentication
               Specifies whether password authentication is allowed.  The
@@ -1372,7 +2420,11 @@
  
       PermitEmptyPasswords
               When password authentication is allowed, it specifies whether the
-@@ -676,7 +676,7 @@
+              server allows login to accounts with empty password strings.  The
+              default is ``no''.
+@@ -707,11 +707,11 @@
+              Because PAM challenge-response authentication usually serves an
+              equivalent role to password authentication, you should disable
               either PasswordAuthentication or ChallengeResponseAuthentication.
  
               If UsePAM is enabled, you will not be able to run sshd(8) as a
@@ -1381,11 +2433,14 @@
  
       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 @@
+              unprivileged child process to deal with incoming network traffic.
+              After successful authentication, another process will be created
+diff --git a/sshd_config.5 b/sshd_config.5
+--- a/sshd_config.5
++++ b/sshd_config.5
+@@ -854,11 +854,11 @@
+ .Dq full
+ (60).
  .It Cm PasswordAuthentication
  Specifies whether password authentication is allowed.
  The default is
@@ -1394,7 +2449,11 @@
  .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 @@
+ The default is
+ .Dq no .
+@@ -1181,11 +1181,11 @@
+ .Cm UsePAM
+ is enabled, you will not be able to run
  .Xr sshd 8
  as a non-root user.
  The default is
@@ -1403,750 +2462,5 @@
  .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);
+ separates privileges by creating an unprivileged child process
+ to deal with incoming network traffic.

Deleted: trunk/dports/net/openssh/files/openssh-6.2p2-gsskex-all-20110125.patch
===================================================================
--- trunk/dports/net/openssh/files/openssh-6.2p2-gsskex-all-20110125.patch	2013-10-24 21:47:52 UTC (rev 112513)
+++ trunk/dports/net/openssh/files/openssh-6.2p2-gsskex-all-20110125.patch	2013-10-25 04:14:14 UTC (rev 112514)
@@ -1,2992 +0,0 @@
-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
-+++ 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 Makefile.in Makefile.in
-index d327787..dd0502e 100644
---- a/Makefile.in
-+++ b/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
---- a/auth-krb5.c
-+++ b/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
---- a/auth2-gss.c
-+++ b/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
---- 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 clientloop.c clientloop.c
-index c1d1d44..2ef816a 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;
- 
-@@ -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
---- a/configure.ac
-+++ b/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
---- 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 gss-serv-krb5.c 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 gss-serv.c 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 kex.c kex.c
-index 57a79dd..f9e7a9c 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
-@@ -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
---- 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
- };
- 
-@@ -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
-+++ 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 kexgsss.c 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 key.c key.c
-index 4cc5c5d..fdfed5c 100644
---- a/key.c
-+++ b/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
---- 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 monitor.c monitor.c
-index 8006b83..d7a782f 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
-@@ -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
---- a/monitor.h
-+++ b/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
---- a/monitor_wrap.c
-+++ b/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
---- 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 readconf.c readconf.c
-index 36265e4..375ca32 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 },
-@@ -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
---- a/readconf.h
-+++ b/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
---- a/servconf.c
-+++ b/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
---- a/servconf.h
-+++ b/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
---- 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
-@@ -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
---- 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 ssh_config.5 ssh_config.5
-index 269529c..bd3a712 100644
---- a/ssh_config.5
-+++ b/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
---- 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);
-@@ -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
---- 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>
-@@ -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
---- a/sshd_config
-+++ b/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
---- a/sshd_config.5
-+++ b/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

Added: trunk/dports/net/openssh/files/openssh-6.3p1-gsskex-all-20130920.patch
===================================================================
--- trunk/dports/net/openssh/files/openssh-6.3p1-gsskex-all-20130920.patch	                        (rev 0)
+++ trunk/dports/net/openssh/files/openssh-6.3p1-gsskex-all-20130920.patch	2013-10-25 04:14:14 UTC (rev 112514)
@@ -0,0 +1,2934 @@
+diff --speed-large-files --minimal -Nru openssh-5.8p1/ChangeLog.gssapi openssh-5.8p1.new/ChangeLog.gssapi
+--- openssh-5.8p1/ChangeLog.gssapi	1970-01-01 01:00:00.000000000 +0100
++++ openssh-5.8p1.new/ChangeLog.gssapi	2011-02-12 18:07:10.948345760 +0100
+@@ -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 --speed-large-files --minimal -Nru openssh-5.8p1/Makefile.in openssh-5.8p1.new/Makefile.in
+--- openssh-5.8p1/Makefile.in	2011-02-04 01:42:13.000000000 +0100
++++ openssh-5.8p1.new/Makefile.in	2011-02-12 18:07:10.990611445 +0100
+@@ -75,6 +75,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-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 kr1.o
+ 
+@@ -91,7 +92,7 @@
+ 	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 --speed-large-files --minimal -Nru openssh-5.8p1/auth-krb5.c openssh-5.8p1.new/auth-krb5.c
+--- openssh-5.8p1/auth-krb5.c	2009-12-21 00:49:22.000000000 +0100
++++ openssh-5.8p1.new/auth-krb5.c	2011-02-12 18:07:11.002529804 +0100
+@@ -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;
+ 	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, oerrno;
++#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;
+@@ -249,6 +261,7 @@
+ 		return oerrno;
+ 	}
+ 	close(tmpfd);
++#endif
+ 
+ 	return (krb5_cc_resolve(ctx, ccname, ccache));
+ }
+diff --speed-large-files --minimal -Nru openssh-5.8p1/auth2-gss.c openssh-5.8p1.new/auth2-gss.c
+--- openssh-5.8p1/auth2-gss.c	2007-12-02 12:59:45.000000000 +0100
++++ openssh-5.8p1.new/auth2-gss.c	2011-02-12 18:07:11.030761708 +0100
+@@ -1,7 +1,7 @@
+ /* $OpenBSD: auth2-gss.c,v 1.16 2007/10/29 00:52:45 dtucker 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_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);
++	free(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)
+@@ -242,7 +278,8 @@
+ 
+ 	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);
+@@ -277,7 +314,8 @@
+ 	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");
+ 
+@@ -292,6 +330,12 @@
+ 	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 --speed-large-files --minimal -Nru openssh-5.8p1/auth2.c openssh-5.8p1.new/auth2.c
+--- openssh-5.8p1/auth2.c	2010-08-31 14:36:39.000000000 +0200
++++ openssh-5.8p1.new/auth2.c	2011-02-12 18:07:11.043418162 +0100
+@@ -69,6 +69,7 @@
+ 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 @@
+ 	&method_none,
+ 	&method_pubkey,
+ #ifdef GSSAPI
++	&method_gsskeyex,
+ 	&method_gssapi,
+ #endif
+ #ifdef JPAKE
+diff --speed-large-files --minimal -Nru openssh-5.8p1/clientloop.c openssh-5.8p1.new/clientloop.c
+--- openssh-5.8p1/clientloop.c	2011-01-16 13:18:35.000000000 +0100
++++ openssh-5.8p1.new/clientloop.c	2011-02-12 18:07:11.063578136 +0100
+@@ -111,6 +111,10 @@
+ #include "msg.h"
+ #include "roaming.h"
+ 
++#ifdef GSSAPI
++#include "ssh-gss.h"
++#endif
++
+ /* import options */
+ extern Options options;
+ 
+@@ -1483,6 +1487,15 @@
+ 		/* 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 --speed-large-files --minimal -Nru openssh-5.8p1/configure.ac openssh-5.8p1.new/configure.ac
+--- openssh-5.8p1/configure.ac	2011-02-04 01:42:14.000000000 +0100
++++ openssh-5.8p1.new/configure.ac	2011-02-12 18:07:11.092748915 +0100
+@@ -514,6 +514,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])
+diff --speed-large-files --minimal -Nru openssh-5.8p1/gss-genr.c openssh-5.8p1.new/gss-genr.c
+--- openssh-5.8p1/gss-genr.c	2009-06-22 08:11:07.000000000 +0200
++++ openssh-5.8p1.new/gss-genr.c	2011-02-12 18:07:11.108432434 +0100
+@@ -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++)
++			free(gss_enc2oid[i].encoded);
++		free(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) {
++		free(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 @@
+ 	}
+ 
+ 	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 @@
+ }
+ 
+ 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 @@
+ 	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 @@
+ }
+ 
+ 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_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 @@
+ 			    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 --speed-large-files --minimal -Nru openssh-5.8p1/gss-serv-krb5.c openssh-5.8p1.new/gss-serv-krb5.c
+--- openssh-5.8p1/gss-serv-krb5.c	2006-09-01 07:38:36.000000000 +0200
++++ openssh-5.8p1.new/gss-serv-krb5.c	2011-02-12 18:07:11.123072516 +0100
+@@ -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 @@
+ 	OM_uint32 maj_status, min_status;
+ 	int len;
+	const char *errmsg;
++	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)
+@@ -184,6 +190,71 @@
+ 	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 @@
+ 	NULL,
+ 	&ssh_gssapi_krb5_userok,
+ 	NULL,
+-	&ssh_gssapi_krb5_storecreds
++	&ssh_gssapi_krb5_storecreds,
++	&ssh_gssapi_krb5_updatecreds
+ };
+ 
+ #endif /* KRB5 */
+diff --speed-large-files --minimal -Nru openssh-5.8p1/gss-serv.c openssh-5.8p1.new/gss-serv.c
+--- openssh-5.8p1/gss-serv.c	2008-05-19 07:05:07.000000000 +0200
++++ openssh-5.8p1.new/gss-serv.c	2011-02-12 18:07:11.135178913 +0100
+@@ -1,7 +1,7 @@
+ /* $OpenBSD: gss-serv.c,v 1.22 2008/05/08 12:02:23 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
+@@ -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, NULL}};
++    GSS_C_NO_CREDENTIAL, GSS_C_NO_NAME,  NULL, {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 @@
+ 	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 @@
+ }
+ 
+ /* 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 @@
+ 	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,
+@@ -247,8 +284,48 @@
+ 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;
+ 
+-	gss_buffer_desc ename;
++	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);
++
++		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;
+ 
+@@ -263,6 +340,13 @@
+ 	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);
+@@ -280,6 +364,8 @@
+ 		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;
+@@ -327,7 +413,7 @@
+ 
+ /* Privileged */
+ int
+-ssh_gssapi_userok(char *user)
++ssh_gssapi_userok(char *user, struct passwd *pw)
+ {
+ 	OM_uint32 lmin;
+ 
+@@ -337,9 +423,11 @@
+ 		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);
+@@ -352,14 +440,90 @@
+ 	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 --speed-large-files --minimal -Nru openssh-5.8p1/kex.c openssh-5.8p1.new/kex.c
+--- openssh-5.8p1/kex.c	2010-09-24 14:11:14.000000000 +0200
++++ openssh-5.8p1.new/kex.c	2011-02-12 18:07:11.149564726 +0100
+@@ -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
+@@ -80,6 +84,11 @@
+ 	{ KEX_ECDH_SHA2_NISTP384, KEX_ECDH_SHA2, NID_secp384r1, EVP_sha384 },
+ 	{ KEX_ECDH_SHA2_NISTP521, KEX_ECDH_SHA2, NID_secp521r1, EVP_sha512 },
+ #endif
++#ifdef GSSAPI
++	{ KEX_GSS_GEX_SHA1_ID, KEX_GSS_GEX_SHA1, 0, EVP_sha1 },
++	{ KEX_GSS_GRP1_SHA1_ID, KEX_GSS_GRP1_SHA1, 0, EVP_sha1 },
++	{ KEX_GSS_GRP14_SHA1_ID, KEX_GSS_GRP14_SHA1, 0, EVP_sha1 },
++#endif
+ 	{ NULL, -1, -1, NULL},
+ };
+ 
+diff --speed-large-files --minimal -Nru openssh-5.8p1/kex.h openssh-5.8p1.new/kex.h
+--- openssh-5.8p1/kex.h	2010-09-24 14:11:14.000000000 +0200
++++ openssh-5.8p1.new/kex.h	2011-02-12 18:07:11.161650596 +0100
+@@ -73,6 +73,9 @@
+ 	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 @@
+ 	int	flags;
+ 	const EVP_MD *evp_md;
+ 	int	ec_nid;
++#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	 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 --speed-large-files --minimal -Nru openssh-5.8p1/kexgssc.c openssh-5.8p1.new/kexgssc.c
+--- openssh-5.8p1/kexgssc.c	1970-01-01 01:00:00.000000000 +0100
++++ openssh-5.8p1.new/kexgssc.c	2011-02-12 18:07:11.176741991 +0100
+@@ -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)
++			free(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);
++	free(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");
++
++	free(msg_tok.value);
++
++	DH_free(dh);
++	if (serverhostkey)
++		free(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 --speed-large-files --minimal -Nru openssh-5.8p1/kexgsss.c openssh-5.8p1.new/kexgsss.c
+--- openssh-5.8p1/kexgsss.c	1970-01-01 01:00:00.000000000 +0100
++++ openssh-5.8p1.new/kexgsss.c	2011-02-12 18:07:11.186584789 +0100
+@@ -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()))
++			free(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));
++
++		free(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);
++	free(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 --speed-large-files --minimal -Nru openssh-5.8p1/key.c openssh-5.8p1.new/key.c
+--- openssh-5.8p1/key.c	2011-02-04 01:48:34.000000000 +0100
++++ openssh-5.8p1.new/key.c	2011-02-12 18:07:11.202089386 +0100
+@@ -929,6 +929,7 @@
+ 	{ "ecdsa-sha2-nistp521-cert-v01 at openssh.com", "ECDSA-CERT",
+ 	    KEY_ECDSA_CERT, NID_secp521r1, 1 },
+ #endif /* OPENSSL_HAS_ECC */
++	{ "null", "null", KEY_NULL, 0, 0 },
+ 	{ "ssh-rsa-cert-v00 at openssh.com", "RSA-CERT-V00",
+ 	    KEY_RSA_CERT_V00, 0, 1 },
+ 	{ "ssh-dss-cert-v00 at openssh.com", "DSA-CERT-V00",
+diff --speed-large-files --minimal -Nru openssh-5.8p1/key.h openssh-5.8p1.new/key.h
+--- openssh-5.8p1/key.h	2010-11-05 00:19:49.000000000 +0100
++++ openssh-5.8p1.new/key.h	2011-02-12 18:07:11.216270794 +0100
+@@ -44,6 +44,7 @@
+ 	KEY_ECDSA_CERT,
+ 	KEY_RSA_CERT_V00,
+ 	KEY_DSA_CERT_V00,
++	KEY_NULL,
+ 	KEY_UNSPEC
+ };
+ enum fp_type {
+diff --speed-large-files --minimal -Nru openssh-5.8p1/monitor.c openssh-5.8p1.new/monitor.c
+--- openssh-5.8p1/monitor.c	2010-09-10 03:23:34.000000000 +0200
++++ openssh-5.8p1.new/monitor.c	2011-02-12 18:07:11.241713537 +0100
+@@ -172,6 +172,8 @@
+ 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
+@@ -241,6 +243,7 @@
+     {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},
+@@ -253,6 +256,12 @@
+ };
+ 
+ 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},
+@@ -357,6 +366,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;
+ 
+@@ -443,6 +456,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);
+@@ -1692,6 +1709,13 @@
+ 	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);
+@@ -1898,6 +1922,9 @@
+ 	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;
+ 
+@@ -1925,6 +1952,9 @@
+ 	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);
+@@ -1942,6 +1972,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);
+ }
+@@ -1953,6 +1984,9 @@
+ 	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);
+@@ -1979,7 +2013,11 @@
+ {
+ 	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);
+@@ -1992,6 +2030,74 @@
+ 	/* 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);
++
++	free(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);
++
++	free(store.filename);
++	free(store.envvar);
++	free(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 --speed-large-files --minimal -Nru openssh-5.8p1/monitor.h openssh-5.8p1.new/monitor.h
+--- openssh-5.8p1/monitor.h	2008-11-05 06:20:46.000000000 +0100
++++ openssh-5.8p1.new/monitor.h	2011-02-12 18:07:11.311728071 +0100
+@@ -53,6 +53,9 @@
+	MONITOR_REQ_JPAKE_STEP2 = 56, MONITOR_ANS_JPAKE_STEP2 = 57,
+	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 --speed-large-files --minimal -Nru openssh-5.8p1/monitor_wrap.c openssh-5.8p1.new/monitor_wrap.c
+--- openssh-5.8p1/monitor_wrap.c	2010-08-31 14:41:14.000000000 +0200
++++ openssh-5.8p1.new/monitor_wrap.c	2011-02-12 18:07:11.359631731 +0100
+@@ -1232,7 +1232,7 @@
+ }
+ 
+ int
+-mm_ssh_gssapi_userok(char *user)
++mm_ssh_gssapi_userok(char *user, struct passwd *pw)
+ {
+ 	Buffer m;
+ 	int authenticated = 0;
+@@ -1249,6 +1249,51 @@
+ 	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 --speed-large-files --minimal -Nru openssh-5.8p1/monitor_wrap.h openssh-5.8p1.new/monitor_wrap.h
+--- openssh-5.8p1/monitor_wrap.h	2009-03-05 14:58:22.000000000 +0100
++++ openssh-5.8p1.new/monitor_wrap.h	2011-02-12 18:07:11.407619296 +0100
+@@ -57,8 +57,10 @@
+ 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 --speed-large-files --minimal -Nru openssh-5.8p1/readconf.c openssh-5.8p1.new/readconf.c
+--- openssh-5.8p1/readconf.c	2010-11-20 05:19:38.000000000 +0100
++++ openssh-5.8p1.new/readconf.c	2011-02-12 18:07:11.460306621 +0100
+@@ -129,6 +129,8 @@
+ 	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 @@
+ 	{ "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 },
+@@ -479,10 +490,30 @@
+ 		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;
+@@ -1092,7 +1123,12 @@
+ 	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;
+@@ -1193,8 +1229,14 @@
+ 		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 --speed-large-files --minimal -Nru openssh-5.8p1/readconf.h openssh-5.8p1.new/readconf.h
+--- openssh-5.8p1/readconf.h	2010-11-20 05:19:38.000000000 +0100
++++ openssh-5.8p1.new/readconf.h	2011-02-12 18:07:11.507187275 +0100
+@@ -46,7 +46,12 @@
+ 	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 --speed-large-files --minimal -Nru openssh-5.8p1/servconf.c openssh-5.8p1.new/servconf.c
+--- openssh-5.8p1/servconf.c	2010-11-20 05:19:38.000000000 +0100
++++ openssh-5.8p1.new/servconf.c	2011-02-12 18:07:11.533252334 +0100
+@@ -97,7 +97,10 @@
+ 	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;
+@@ -226,8 +229,14 @@
+ 		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)
+@@ -322,7 +331,9 @@
+ 	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,
+@@ -386,10 +397,20 @@
+ #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 },
+@@ -944,10 +965,22 @@
+ 		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;
+@@ -1704,7 +1737,10 @@
+ #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 --speed-large-files --minimal -Nru openssh-5.8p1/servconf.h openssh-5.8p1.new/servconf.h
+--- openssh-5.8p1/servconf.h	2010-11-20 05:19:38.000000000 +0100
++++ openssh-5.8p1.new/servconf.h	2011-02-12 18:07:11.548572408 +0100
+@@ -97,7 +97,10 @@
+ 	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 --speed-large-files --minimal -Nru openssh-5.8p1/ssh-gss.h openssh-5.8p1.new/ssh-gss.h
+--- openssh-5.8p1/ssh-gss.h	2007-06-12 15:40:39.000000000 +0200
++++ openssh-5.8p1.new/ssh-gss.h	2011-02-12 18:07:11.567306608 +0100
+@@ -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 @@
+ 	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 @@
+ 	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 @@
+ 	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_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 --speed-large-files --minimal -Nru openssh-5.8p1/ssh_config openssh-5.8p1.new/ssh_config
+--- openssh-5.8p1/ssh_config	2010-01-12 09:40:27.000000000 +0100
++++ openssh-5.8p1.new/ssh_config	2011-02-12 18:07:11.580240516 +0100
+@@ -26,6 +26,8 @@
+ #   HostbasedAuthentication no
+ #   GSSAPIAuthentication no
+ #   GSSAPIDelegateCredentials no
++#   GSSAPIKeyExchange no
++#   GSSAPITrustDNS no
+ #   BatchMode no
+ #   CheckHostIP yes
+ #   AddressFamily any
+diff --speed-large-files --minimal -Nru openssh-5.8p1/ssh_config.5 openssh-5.8p1.new/ssh_config.5
+--- openssh-5.8p1/ssh_config.5	2010-12-26 04:26:48.000000000 +0100
++++ openssh-5.8p1.new/ssh_config.5	2011-02-12 18:07:11.600266821 +0100
+@@ -508,11 +508,43 @@
+ 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 --speed-large-files --minimal -Nru openssh-5.8p1/sshconnect2.c openssh-5.8p1.new/sshconnect2.c
+--- openssh-5.8p1/sshconnect2.c	2010-12-01 02:21:51.000000000 +0100
++++ openssh-5.8p1.new/sshconnect2.c	2011-02-12 18:07:11.623078773 +0100
+@@ -159,9 +159,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, 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;
+@@ -196,6 +221,17 @@
+ 	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);
++		free(gss);
++	}
++#endif
++
+ 	if (options.rekey_limit || options.rekey_interval)
+ 		packet_set_rekey_limits((u_int32_t)options.rekey_limit,
+ 
+@@ -206,10 +242,30 @@
+ 	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);
+@@ -304,6 +360,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 *);
+@@ -319,6 +376,11 @@
+ 
+ Authmethod authmethods[] = {
+ #ifdef GSSAPI
++	{"gssapi-keyex",
++		userauth_gsskeyex,
++		NULL,
++		&options.gss_authentication,
++		NULL},
+ 	{"gssapi-with-mic",
+ 		userauth_gssapi,
+ 		NULL,
+@@ -625,19 +687,31 @@
+ 	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++;
+@@ -734,8 +808,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");
+@@ -845,6 +919,48 @@
+ 	free(msg);
+ 	free(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 --speed-large-files --minimal -Nru openssh-5.8p1/sshd.c openssh-5.8p1.new/sshd.c
+--- openssh-5.8p1/sshd.c	2011-01-11 07:20:31.000000000 +0100
++++ openssh-5.8p1.new/sshd.c	2011-02-12 18:07:11.656005267 +0100
+@@ -120,6 +120,10 @@
+ #include "roaming.h"
+ #include "version.h"
+ 
++#ifdef USE_SECURITY_SESSION_API
++#include <Security/AuthSession.h>
++#endif
++
+ #ifdef LIBWRAP
+ #include <tcpd.h>
+ #include <syslog.h>
+@@ -1590,10 +1594,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);
+@@ -1922,6 +1929,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
+@@ -2303,6 +2364,48 @@
+ 
+ 	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;
+@@ -2310,6 +2413,13 @@
+ 	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 --speed-large-files --minimal -Nru openssh-5.8p1/sshd_config openssh-5.8p1.new/sshd_config
+--- openssh-5.8p1/sshd_config	2010-09-10 03:20:12.000000000 +0200
++++ openssh-5.8p1.new/sshd_config	2011-02-12 18:07:11.668077725 +0100
+@@ -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 
+diff --speed-large-files --minimal -Nru openssh-5.8p1/sshd_config.5 openssh-5.8p1.new/sshd_config.5
+--- openssh-5.8p1/sshd_config.5	2010-12-26 04:26:48.000000000 +0100
++++ openssh-5.8p1.new/sshd_config.5	2011-02-12 18:07:11.685676774 +0100
+@@ -423,12 +423,40 @@
+ 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/20131024/2f535def/attachment-0001.html>


More information about the macports-changes mailing list