kentpeacock / rpms / openssh

Forked from rpms/openssh 2 years ago
Clone
943807
diff --git a/Makefile.in b/Makefile.in
943807
index e7549470..b68c1710 100644
943807
--- a/Makefile.in
943807
+++ b/Makefile.in
943807
@@ -109,6 +109,7 @@ LIBSSH_OBJS=${LIBOPENSSH_OBJS} \
943807
 	kex.o kexdh.o kexgex.o kexecdh.o kexc25519.o \
943807
 	kexgexc.o kexgexs.o \
943807
 	kexsntrup761x25519.o sntrup761.o kexgen.o \
943807
+	kexgssc.o \
943807
 	sftp-realpath.o platform-pledge.o platform-tracing.o platform-misc.o \
943807
 	sshbuf-io.o
943807
 
943807
@@ -125,7 +126,7 @@ SSHDOBJS=sshd.o auth-rhosts.o auth-passwd.o \
943807
 	auth-bsdauth.o auth2-hostbased.o auth2-kbdint.o \
943807
 	auth2-none.o auth2-passwd.o auth2-pubkey.o \
943807
 	monitor.o monitor_wrap.o auth-krb5.o \
943807
-	auth2-gss.o gss-serv.o gss-serv-krb5.o \
943807
+	auth2-gss.o gss-serv.o gss-serv-krb5.o kexgsss.o \
943807
 	loginrec.o auth-pam.o auth-shadow.o auth-sia.o md5crypt.o \
943807
 	srclimit.o sftp-server.o sftp-common.o \
943807
 	sandbox-null.o sandbox-rlimit.o sandbox-systrace.o sandbox-darwin.o \
5dbb6f
diff -up a/auth.c.gsskex b/auth.c
5dbb6f
--- a/auth.c.gsskex	2021-08-20 06:03:49.000000000 +0200
5dbb6f
+++ b/auth.c	2021-08-27 12:41:51.262788953 +0200
5dbb6f
@@ -402,7 +402,8 @@ auth_root_allowed(struct ssh *ssh, const
943807
 	case PERMIT_NO_PASSWD:
943807
 		if (strcmp(method, "publickey") == 0 ||
943807
 		    strcmp(method, "hostbased") == 0 ||
943807
-		    strcmp(method, "gssapi-with-mic") == 0)
943807
+		    strcmp(method, "gssapi-with-mic") == 0 ||
943807
+		    strcmp(method, "gssapi-keyex") == 0)
943807
 			return 1;
943807
 		break;
943807
 	case PERMIT_FORCED_ONLY:
5dbb6f
@@ -730,97 +731,6 @@ fakepw(void)
943807
 }
943807
 
5dbb6f
 /*
943807
- * Returns the remote DNS hostname as a string. The returned string must not
943807
- * be freed. NB. this will usually trigger a DNS query the first time it is
943807
- * called.
943807
- * This function does additional checks on the hostname to mitigate some
5dbb6f
- * attacks on based on conflation of hostnames and IP addresses.
943807
- */
943807
-
943807
-static char *
943807
-remote_hostname(struct ssh *ssh)
943807
-{
943807
-	struct sockaddr_storage from;
943807
-	socklen_t fromlen;
943807
-	struct addrinfo hints, *ai, *aitop;
943807
-	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
943807
-	const char *ntop = ssh_remote_ipaddr(ssh);
943807
-
943807
-	/* Get IP address of client. */
943807
-	fromlen = sizeof(from);
943807
-	memset(&from, 0, sizeof(from));
943807
-	if (getpeername(ssh_packet_get_connection_in(ssh),
943807
-	    (struct sockaddr *)&from, &fromlen) == -1) {
943807
-		debug("getpeername failed: %.100s", strerror(errno));
943807
-		return xstrdup(ntop);
943807
-	}
943807
-
943807
-	ipv64_normalise_mapped(&from, &fromlen);
943807
-	if (from.ss_family == AF_INET6)
943807
-		fromlen = sizeof(struct sockaddr_in6);
943807
-
943807
-	debug3("Trying to reverse map address %.100s.", ntop);
943807
-	/* Map the IP address to a host name. */
943807
-	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
943807
-	    NULL, 0, NI_NAMEREQD) != 0) {
943807
-		/* Host name not found.  Use ip address. */
943807
-		return xstrdup(ntop);
943807
-	}
943807
-
943807
-	/*
943807
-	 * if reverse lookup result looks like a numeric hostname,
943807
-	 * someone is trying to trick us by PTR record like following:
943807
-	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
943807
-	 */
943807
-	memset(&hints, 0, sizeof(hints));
943807
-	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
943807
-	hints.ai_flags = AI_NUMERICHOST;
943807
-	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
943807
-		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
943807
-		    name, ntop);
943807
-		freeaddrinfo(ai);
943807
-		return xstrdup(ntop);
943807
-	}
943807
-
943807
-	/* Names are stored in lowercase. */
943807
-	lowercase(name);
943807
-
943807
-	/*
943807
-	 * Map it back to an IP address and check that the given
943807
-	 * address actually is an address of this host.  This is
943807
-	 * necessary because anyone with access to a name server can
943807
-	 * define arbitrary names for an IP address. Mapping from
943807
-	 * name to IP address can be trusted better (but can still be
943807
-	 * fooled if the intruder has access to the name server of
943807
-	 * the domain).
943807
-	 */
943807
-	memset(&hints, 0, sizeof(hints));
943807
-	hints.ai_family = from.ss_family;
943807
-	hints.ai_socktype = SOCK_STREAM;
943807
-	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
943807
-		logit("reverse mapping checking getaddrinfo for %.700s "
943807
-		    "[%s] failed.", name, ntop);
943807
-		return xstrdup(ntop);
943807
-	}
943807
-	/* Look for the address from the list of addresses. */
943807
-	for (ai = aitop; ai; ai = ai->ai_next) {
943807
-		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
943807
-		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
943807
-		    (strcmp(ntop, ntop2) == 0))
943807
-				break;
943807
-	}
943807
-	freeaddrinfo(aitop);
943807
-	/* If we reached the end of the list, the address was not there. */
943807
-	if (ai == NULL) {
943807
-		/* Address not found for the host name. */
943807
-		logit("Address %.100s maps to %.600s, but this does not "
943807
-		    "map back to the address.", ntop, name);
943807
-		return xstrdup(ntop);
943807
-	}
943807
-	return xstrdup(name);
943807
-}
943807
-
5dbb6f
-/*
943807
  * Return the canonical name of the host in the other side of the current
943807
  * connection.  The host name is cached, so it is efficient to call this
5dbb6f
  * several times.
943807
diff --git a/auth2-gss.c b/auth2-gss.c
943807
index 9351e042..d6446c0c 100644
943807
--- a/auth2-gss.c
943807
+++ b/auth2-gss.c
943807
@@ -1,7 +1,7 @@
943807
 /* $OpenBSD: auth2-gss.c,v 1.32 2021/01/27 10:15:08 djm Exp $ */
943807
 
943807
 /*
943807
- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
943807
+ * Copyright (c) 2001-2007 Simon Wilkinson. All rights reserved.
943807
  *
943807
  * Redistribution and use in source and binary forms, with or without
943807
  * modification, are permitted provided that the following conditions
943807
@@ -54,6 +54,48 @@ static int input_gssapi_mic(int type, u_int32_t plen, struct ssh *ssh);
943807
 static int input_gssapi_exchange_complete(int type, u_int32_t plen, struct ssh *ssh);
943807
 static int input_gssapi_errtok(int, u_int32_t, struct ssh *);
943807
 
943807
+/*
943807
+ * The 'gssapi_keyex' userauth mechanism.
943807
+ */
943807
+static int
943807
+userauth_gsskeyex(struct ssh *ssh)
943807
+{
943807
+	Authctxt *authctxt = ssh->authctxt;
943807
+	int r, authenticated = 0;
943807
+	struct sshbuf *b = NULL;
943807
+	gss_buffer_desc mic, gssbuf;
943807
+	u_char *p;
943807
+	size_t len;
943807
+
943807
+	if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
943807
+	    (r = sshpkt_get_end(ssh)) != 0)
943807
+		fatal_fr(r, "parsing");
943807
+
943807
+	if ((b = sshbuf_new()) == NULL)
943807
+		fatal_f("sshbuf_new failed");
943807
+
943807
+	mic.value = p;
943807
+	mic.length = len;
943807
+
943807
+	ssh_gssapi_buildmic(b, authctxt->user, authctxt->service,
943807
+	    "gssapi-keyex", ssh->kex->session_id);
943807
+
943807
+	if ((gssbuf.value = sshbuf_mutable_ptr(b)) == NULL)
943807
+		fatal_f("sshbuf_mutable_ptr failed");
943807
+	gssbuf.length = sshbuf_len(b);
943807
+
943807
+	/* gss_kex_context is NULL with privsep, so we can't check it here */
943807
+	if (!GSS_ERROR(PRIVSEP(ssh_gssapi_checkmic(gss_kex_context,
943807
+	    &gssbuf, &mic))))
943807
+		authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user,
943807
+		    authctxt->pw, 1));
943807
+
943807
+	sshbuf_free(b);
943807
+	free(mic.value);
943807
+
943807
+	return (authenticated);
943807
+}
943807
+
943807
 /*
943807
  * We only support those mechanisms that we know about (ie ones that we know
943807
  * how to check local user kuserok and the like)
943807
@@ -260,7 +302,8 @@ input_gssapi_exchange_complete(int type, u_int32_t plen, struct ssh *ssh)
943807
 	if ((r = sshpkt_get_end(ssh)) != 0)
943807
 		fatal_fr(r, "parse packet");
943807
 
943807
-	authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user));
943807
+	authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user,
943807
+	    authctxt->pw, 1));
943807
 
943807
 	if ((!use_privsep || mm_is_monitor()) &&
943807
 	    (displayname = ssh_gssapi_displayname()) != NULL)
943807
@@ -306,7 +349,8 @@ input_gssapi_mic(int type, u_int32_t plen, struct ssh *ssh)
943807
 	gssbuf.length = sshbuf_len(b);
943807
 
943807
 	if (!GSS_ERROR(PRIVSEP(ssh_gssapi_checkmic(gssctxt, &gssbuf, &mic))))
943807
-		authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user));
943807
+		authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user,
943807
+		    authctxt->pw, 0));
943807
 	else
943807
 		logit("GSSAPI MIC check failed");
943807
 
943807
@@ -326,6 +370,12 @@ input_gssapi_mic(int type, u_int32_t plen, struct ssh *ssh)
943807
 	return 0;
943807
 }
943807
 
943807
+Authmethod method_gsskeyex = {
943807
+	"gssapi-keyex",
943807
+	userauth_gsskeyex,
943807
+	&options.gss_authentication
943807
+};
943807
+
943807
 Authmethod method_gssapi = {
943807
 	"gssapi-with-mic",
943807
 	userauth_gssapi,
943807
diff --git a/auth2.c b/auth2.c
943807
index 0e776224..1c217268 100644
943807
--- a/auth2.c
943807
+++ b/auth2.c
943807
@@ -73,6 +73,7 @@ extern Authmethod method_passwd;
943807
 extern Authmethod method_kbdint;
943807
 extern Authmethod method_hostbased;
943807
 #ifdef GSSAPI
943807
+extern Authmethod method_gsskeyex;
943807
 extern Authmethod method_gssapi;
943807
 #endif
943807
 
943807
@@ -80,6 +81,7 @@ Authmethod *authmethods[] = {
943807
 	&method_none,
943807
 	&method_pubkey,
943807
 #ifdef GSSAPI
943807
+	&method_gsskeyex,
943807
 	&method_gssapi,
943807
 #endif
943807
 	&method_passwd,
943807
diff --git a/canohost.c b/canohost.c
943807
index abea9c6e..8e81b519 100644
943807
--- a/canohost.c
943807
+++ b/canohost.c
943807
@@ -35,6 +35,99 @@
943807
 #include "canohost.h"
943807
 #include "misc.h"
943807
 
943807
+/*
943807
+ * Returns the remote DNS hostname as a string. The returned string must not
943807
+ * be freed. NB. this will usually trigger a DNS query the first time it is
943807
+ * called.
943807
+ * This function does additional checks on the hostname to mitigate some
943807
+ * attacks on legacy rhosts-style authentication.
943807
+ * XXX is RhostsRSAAuthentication vulnerable to these?
943807
+ * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
943807
+ */
943807
+
943807
+char *
943807
+remote_hostname(struct ssh *ssh)
943807
+{
943807
+	struct sockaddr_storage from;
943807
+	socklen_t fromlen;
943807
+	struct addrinfo hints, *ai, *aitop;
943807
+	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
943807
+	const char *ntop = ssh_remote_ipaddr(ssh);
943807
+
943807
+	/* Get IP address of client. */
943807
+	fromlen = sizeof(from);
943807
+	memset(&from, 0, sizeof(from));
943807
+	if (getpeername(ssh_packet_get_connection_in(ssh),
943807
+	    (struct sockaddr *)&from, &fromlen) == -1) {
943807
+		debug("getpeername failed: %.100s", strerror(errno));
943807
+		return xstrdup(ntop);
943807
+	}
943807
+
943807
+	ipv64_normalise_mapped(&from, &fromlen);
943807
+	if (from.ss_family == AF_INET6)
943807
+		fromlen = sizeof(struct sockaddr_in6);
943807
+
943807
+	debug3("Trying to reverse map address %.100s.", ntop);
943807
+	/* Map the IP address to a host name. */
943807
+	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
943807
+	    NULL, 0, NI_NAMEREQD) != 0) {
943807
+		/* Host name not found.  Use ip address. */
943807
+		return xstrdup(ntop);
943807
+	}
943807
+
943807
+	/*
943807
+	 * if reverse lookup result looks like a numeric hostname,
943807
+	 * someone is trying to trick us by PTR record like following:
943807
+	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
943807
+	 */
943807
+	memset(&hints, 0, sizeof(hints));
943807
+	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
943807
+	hints.ai_flags = AI_NUMERICHOST;
943807
+	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
943807
+		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
943807
+		    name, ntop);
943807
+		freeaddrinfo(ai);
943807
+		return xstrdup(ntop);
943807
+	}
943807
+
943807
+	/* Names are stored in lowercase. */
943807
+	lowercase(name);
943807
+
943807
+	/*
943807
+	 * Map it back to an IP address and check that the given
943807
+	 * address actually is an address of this host.  This is
943807
+	 * necessary because anyone with access to a name server can
943807
+	 * define arbitrary names for an IP address. Mapping from
943807
+	 * name to IP address can be trusted better (but can still be
943807
+	 * fooled if the intruder has access to the name server of
943807
+	 * the domain).
943807
+	 */
943807
+	memset(&hints, 0, sizeof(hints));
943807
+	hints.ai_family = from.ss_family;
943807
+	hints.ai_socktype = SOCK_STREAM;
943807
+	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
943807
+		logit("reverse mapping checking getaddrinfo for %.700s "
943807
+		    "[%s] failed.", name, ntop);
943807
+		return xstrdup(ntop);
943807
+	}
943807
+	/* Look for the address from the list of addresses. */
943807
+	for (ai = aitop; ai; ai = ai->ai_next) {
943807
+		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
943807
+		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
943807
+		    (strcmp(ntop, ntop2) == 0))
943807
+				break;
943807
+	}
943807
+	freeaddrinfo(aitop);
943807
+	/* If we reached the end of the list, the address was not there. */
943807
+	if (ai == NULL) {
943807
+		/* Address not found for the host name. */
943807
+		logit("Address %.100s maps to %.600s, but this does not "
943807
+		    "map back to the address.", ntop, name);
943807
+		return xstrdup(ntop);
943807
+	}
943807
+	return xstrdup(name);
943807
+}
943807
+
943807
 void
943807
 ipv64_normalise_mapped(struct sockaddr_storage *addr, socklen_t *len)
943807
 {
943807
diff --git a/canohost.h b/canohost.h
943807
index 26d62855..0cadc9f1 100644
943807
--- a/canohost.h
943807
+++ b/canohost.h
943807
@@ -15,6 +15,9 @@
943807
 #ifndef _CANOHOST_H
943807
 #define _CANOHOST_H
943807
 
943807
+struct ssh;
943807
+
943807
+char		*remote_hostname(struct ssh *);
943807
 char		*get_peer_ipaddr(int);
943807
 int		 get_peer_port(int);
943807
 char		*get_local_ipaddr(int);
943807
diff --git a/clientloop.c b/clientloop.c
943807
index ebd0dbca..1bdac6a4 100644
943807
--- a/clientloop.c
943807
+++ b/clientloop.c
943807
@@ -112,6 +112,10 @@
943807
 #include "ssherr.h"
943807
 #include "hostfile.h"
943807
 
943807
+#ifdef GSSAPI
943807
+#include "ssh-gss.h"
943807
+#endif
943807
+
943807
 /* import options */
943807
 extern Options options;
943807
 
943807
@@ -1379,9 +1383,18 @@ client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
943807
 			break;
943807
 
943807
 		/* Do channel operations unless rekeying in progress. */
943807
-		if (!ssh_packet_is_rekeying(ssh))
943807
+		if (!ssh_packet_is_rekeying(ssh)) {
943807
 			channel_after_select(ssh, readset, writeset);
943807
 
943807
+#ifdef GSSAPI
943807
+			if (options.gss_renewal_rekey &&
943807
+			    ssh_gssapi_credentials_updated(NULL)) {
943807
+				debug("credentials updated - forcing rekey");
943807
+				need_rekeying = 1;
943807
+			}
943807
+#endif
943807
+		}
943807
+
943807
 		/* Buffer input from the connection.  */
943807
 		client_process_net_input(ssh, readset);
943807
 
943807
diff --git a/configure.ac b/configure.ac
943807
index b689db4b..efafb6bd 100644
943807
--- a/configure.ac
943807
+++ b/configure.ac
943807
@@ -674,6 +674,30 @@ main() { if (NSVersionOfRunTimeLibrary("System") >= (60 << 16))
943807
 	    [Use tunnel device compatibility to OpenBSD])
943807
 	AC_DEFINE([SSH_TUN_PREPEND_AF], [1],
943807
 	    [Prepend the address family to IP tunnel traffic])
943807
+	AC_MSG_CHECKING([if we have the Security Authorization Session API])
943807
+	AC_TRY_COMPILE([#include <Security/AuthSession.h>],
943807
+		[SessionCreate(0, 0);],
943807
+		[ac_cv_use_security_session_api="yes"
943807
+		 AC_DEFINE([USE_SECURITY_SESSION_API], [1],
943807
+			[platform has the Security Authorization Session API])
943807
+		 LIBS="$LIBS -framework Security"
943807
+		 AC_MSG_RESULT([yes])],
943807
+		[ac_cv_use_security_session_api="no"
943807
+		 AC_MSG_RESULT([no])])
943807
+	AC_MSG_CHECKING([if we have an in-memory credentials cache])
943807
+	AC_TRY_COMPILE(
943807
+		[#include <Kerberos/Kerberos.h>],
943807
+		[cc_context_t c;
943807
+		 (void) cc_initialize (&c, 0, NULL, NULL);],
943807
+		[AC_DEFINE([USE_CCAPI], [1],
943807
+			[platform uses an in-memory credentials cache])
943807
+		 LIBS="$LIBS -framework Security"
943807
+		 AC_MSG_RESULT([yes])
943807
+		 if test "x$ac_cv_use_security_session_api" = "xno"; then
943807
+			AC_MSG_ERROR([*** Need a security framework to use the credentials cache API ***])
943807
+		fi],
943807
+		[AC_MSG_RESULT([no])]
943807
+	)
943807
 	m4_pattern_allow([AU_IPv])
943807
 	AC_CHECK_DECL([AU_IPv4], [],
943807
 	    AC_DEFINE([AU_IPv4], [0], [System only supports IPv4 audit records])
943807
diff --git a/gss-genr.c b/gss-genr.c
943807
index d56257b4..763a63ff 100644
943807
--- a/gss-genr.c
943807
+++ b/gss-genr.c
943807
@@ -1,7 +1,7 @@
943807
 /* $OpenBSD: gss-genr.c,v 1.28 2021/01/27 10:05:28 djm Exp $ */
943807
 
943807
 /*
943807
- * Copyright (c) 2001-2007 Simon Wilkinson. All rights reserved.
943807
+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
943807
  *
943807
  * Redistribution and use in source and binary forms, with or without
943807
  * modification, are permitted provided that the following conditions
943807
@@ -41,9 +41,33 @@
943807
 #include "sshbuf.h"
943807
 #include "log.h"
943807
 #include "ssh2.h"
943807
+#include "cipher.h"
943807
+#include "sshkey.h"
943807
+#include "kex.h"
943807
+#include "digest.h"
943807
+#include "packet.h"
943807
 
943807
 #include "ssh-gss.h"
943807
 
943807
+typedef struct {
943807
+	char *encoded;
943807
+	gss_OID oid;
943807
+} ssh_gss_kex_mapping;
943807
+
943807
+/*
943807
+ * XXX - It would be nice to find a more elegant way of handling the
943807
+ * XXX   passing of the key exchange context to the userauth routines
943807
+ */
943807
+
943807
+Gssctxt *gss_kex_context = NULL;
943807
+
943807
+static ssh_gss_kex_mapping *gss_enc2oid = NULL;
943807
+
943807
+int
943807
+ssh_gssapi_oid_table_ok(void) {
943807
+	return (gss_enc2oid != NULL);
943807
+}
943807
+
943807
 /* sshbuf_get for gss_buffer_desc */
943807
 int
943807
 ssh_gssapi_get_buffer_desc(struct sshbuf *b, gss_buffer_desc *g)
943807
@@ -62,6 +86,159 @@ ssh_gssapi_get_buffer_desc(struct sshbuf *b, gss_buffer_desc *g)
943807
 	return 0;
943807
 }
943807
 
943807
+/* sshpkt_get of gss_buffer_desc */
943807
+int
943807
+ssh_gssapi_sshpkt_get_buffer_desc(struct ssh *ssh, gss_buffer_desc *g)
943807
+{
943807
+	int r;
943807
+	u_char *p;
943807
+	size_t len;
943807
+
943807
+	if ((r = sshpkt_get_string(ssh, &p, &len)) != 0)
943807
+		return r;
943807
+	g->value = p;
943807
+	g->length = len;
943807
+	return 0;
943807
+}
943807
+
943807
+/*
943807
+ * Return a list of the gss-group1-sha1 mechanisms supported by this program
943807
+ *
943807
+ * We test mechanisms to ensure that we can use them, to avoid starting
943807
+ * a key exchange with a bad mechanism
943807
+ */
943807
+
943807
+char *
943807
+ssh_gssapi_client_mechanisms(const char *host, const char *client,
943807
+    const char *kex) {
943807
+	gss_OID_set gss_supported = NULL;
943807
+	OM_uint32 min_status;
943807
+
943807
+	if (GSS_ERROR(gss_indicate_mechs(&min_status, &gss_supported)))
943807
+		return NULL;
943807
+
943807
+	return ssh_gssapi_kex_mechs(gss_supported, ssh_gssapi_check_mechanism,
943807
+	    host, client, kex);
943807
+}
943807
+
943807
+char *
943807
+ssh_gssapi_kex_mechs(gss_OID_set gss_supported, ssh_gssapi_check_fn *check,
943807
+    const char *host, const char *client, const char *kex) {
943807
+	struct sshbuf *buf = NULL;
943807
+	size_t i;
943807
+	int r = SSH_ERR_ALLOC_FAIL;
943807
+	int oidpos, enclen;
943807
+	char *mechs, *encoded;
943807
+	u_char digest[SSH_DIGEST_MAX_LENGTH];
943807
+	char deroid[2];
943807
+	struct ssh_digest_ctx *md = NULL;
943807
+	char *s, *cp, *p;
943807
+
943807
+	if (gss_enc2oid != NULL) {
943807
+		for (i = 0; gss_enc2oid[i].encoded != NULL; i++)
943807
+			free(gss_enc2oid[i].encoded);
943807
+		free(gss_enc2oid);
943807
+	}
943807
+
943807
+	gss_enc2oid = xmalloc(sizeof(ssh_gss_kex_mapping) *
943807
+	    (gss_supported->count + 1));
943807
+
943807
+	if ((buf = sshbuf_new()) == NULL)
943807
+		fatal_f("sshbuf_new failed");
943807
+
943807
+	oidpos = 0;
943807
+	s = cp = xstrdup(kex);
943807
+	for (i = 0; i < gss_supported->count; i++) {
943807
+		if (gss_supported->elements[i].length < 128 &&
943807
+		    (*check)(NULL, &(gss_supported->elements[i]), host, client)) {
943807
+
943807
+			deroid[0] = SSH_GSS_OIDTYPE;
943807
+			deroid[1] = gss_supported->elements[i].length;
943807
+
943807
+			if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
943807
+			    (r = ssh_digest_update(md, deroid, 2)) != 0 ||
943807
+			    (r = ssh_digest_update(md,
943807
+			        gss_supported->elements[i].elements,
943807
+			        gss_supported->elements[i].length)) != 0 ||
943807
+			    (r = ssh_digest_final(md, digest, sizeof(digest))) != 0)
943807
+				fatal_fr(r, "digest failed");
943807
+			ssh_digest_free(md);
943807
+			md = NULL;
943807
+
943807
+			encoded = xmalloc(ssh_digest_bytes(SSH_DIGEST_MD5)
943807
+			    * 2);
943807
+			enclen = __b64_ntop(digest,
943807
+			    ssh_digest_bytes(SSH_DIGEST_MD5), encoded,
943807
+			    ssh_digest_bytes(SSH_DIGEST_MD5) * 2);
943807
+
943807
+			cp = strncpy(s, kex, strlen(kex));
943807
+			for ((p = strsep(&cp, ",")); p && *p != '\0';
943807
+				(p = strsep(&cp, ","))) {
943807
+				if (sshbuf_len(buf) != 0 &&
943807
+				    (r = sshbuf_put_u8(buf, ',')) != 0)
943807
+					fatal_fr(r, "sshbuf_put_u8 error");
943807
+				if ((r = sshbuf_put(buf, p, strlen(p))) != 0 ||
943807
+				    (r = sshbuf_put(buf, encoded, enclen)) != 0)
943807
+					fatal_fr(r, "sshbuf_put error");
943807
+			}
943807
+
943807
+			gss_enc2oid[oidpos].oid = &(gss_supported->elements[i]);
943807
+			gss_enc2oid[oidpos].encoded = encoded;
943807
+			oidpos++;
943807
+		}
943807
+	}
943807
+	free(s);
943807
+	gss_enc2oid[oidpos].oid = NULL;
943807
+	gss_enc2oid[oidpos].encoded = NULL;
943807
+
943807
+	if ((mechs = sshbuf_dup_string(buf)) == NULL)
943807
+		fatal_f("sshbuf_dup_string failed");
943807
+
943807
+	sshbuf_free(buf);
943807
+
943807
+	if (strlen(mechs) == 0) {
943807
+		free(mechs);
943807
+		mechs = NULL;
943807
+	}
943807
+
943807
+	return (mechs);
943807
+}
943807
+
943807
+gss_OID
943807
+ssh_gssapi_id_kex(Gssctxt *ctx, char *name, int kex_type) {
943807
+	int i = 0;
943807
+
943807
+#define SKIP_KEX_NAME(type) \
943807
+	case type: \
943807
+		if (strlen(name) < sizeof(type##_ID)) \
943807
+			return GSS_C_NO_OID; \
943807
+		name += sizeof(type##_ID) - 1; \
943807
+		break;
943807
+
943807
+	switch (kex_type) {
943807
+	SKIP_KEX_NAME(KEX_GSS_GRP1_SHA1)
943807
+	SKIP_KEX_NAME(KEX_GSS_GRP14_SHA1)
943807
+	SKIP_KEX_NAME(KEX_GSS_GRP14_SHA256)
943807
+	SKIP_KEX_NAME(KEX_GSS_GRP16_SHA512)
943807
+	SKIP_KEX_NAME(KEX_GSS_GEX_SHA1)
943807
+	SKIP_KEX_NAME(KEX_GSS_NISTP256_SHA256)
943807
+	SKIP_KEX_NAME(KEX_GSS_C25519_SHA256)
943807
+	default:
943807
+		return GSS_C_NO_OID;
943807
+	}
943807
+
943807
+#undef SKIP_KEX_NAME
943807
+
943807
+	while (gss_enc2oid[i].encoded != NULL &&
943807
+	    strcmp(name, gss_enc2oid[i].encoded) != 0)
943807
+		i++;
943807
+
943807
+	if (gss_enc2oid[i].oid != NULL && ctx != NULL)
943807
+		ssh_gssapi_set_oid(ctx, gss_enc2oid[i].oid);
943807
+
943807
+	return gss_enc2oid[i].oid;
943807
+}
943807
+
943807
 /* Check that the OID in a data stream matches that in the context */
943807
 int
943807
 ssh_gssapi_check_oid(Gssctxt *ctx, void *data, size_t len)
943807
@@ -218,7 +398,7 @@ ssh_gssapi_init_ctx(Gssctxt *ctx, int deleg_creds, gss_buffer_desc *recv_tok,
943807
 	}
943807
 
943807
 	ctx->major = gss_init_sec_context(&ctx->minor,
943807
-	    GSS_C_NO_CREDENTIAL, &ctx->context, ctx->name, ctx->oid,
943807
+	    ctx->client_creds, &ctx->context, ctx->name, ctx->oid,
943807
 	    GSS_C_MUTUAL_FLAG | GSS_C_INTEG_FLAG | deleg_flag,
943807
 	    0, NULL, recv_tok, NULL, send_tok, flags, NULL);
943807
 
943807
@@ -247,9 +427,43 @@ ssh_gssapi_import_name(Gssctxt *ctx, const char *host)
943807
 	return (ctx->major);
943807
 }
943807
 
943807
+OM_uint32
943807
+ssh_gssapi_client_identity(Gssctxt *ctx, const char *name)
943807
+{
943807
+	gss_buffer_desc gssbuf;
943807
+	gss_name_t gssname;
943807
+	OM_uint32 status;
943807
+	gss_OID_set oidset;
943807
+
943807
+	gssbuf.value = (void *) name;
943807
+	gssbuf.length = strlen(gssbuf.value);
943807
+
943807
+	gss_create_empty_oid_set(&status, &oidset);
943807
+	gss_add_oid_set_member(&status, ctx->oid, &oidset);
943807
+
943807
+	ctx->major = gss_import_name(&ctx->minor, &gssbuf,
943807
+	    GSS_C_NT_USER_NAME, &gssname);
943807
+
943807
+	if (!ctx->major)
943807
+		ctx->major = gss_acquire_cred(&ctx->minor,
943807
+		    gssname, 0, oidset, GSS_C_INITIATE,
943807
+		    &ctx->client_creds, NULL, NULL);
943807
+
943807
+	gss_release_name(&status, &gssname);
943807
+	gss_release_oid_set(&status, &oidset);
943807
+
943807
+	if (ctx->major)
943807
+		ssh_gssapi_error(ctx);
943807
+
943807
+	return(ctx->major);
943807
+}
943807
+
943807
 OM_uint32
943807
 ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_t buffer, gss_buffer_t hash)
943807
 {
943807
+	if (ctx == NULL)
943807
+		return -1;
943807
+
943807
 	if ((ctx->major = gss_get_mic(&ctx->minor, ctx->context,
943807
 	    GSS_C_QOP_DEFAULT, buffer, hash)))
943807
 		ssh_gssapi_error(ctx);
943807
@@ -257,6 +471,19 @@ ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_t buffer, gss_buffer_t hash)
943807
 	return (ctx->major);
943807
 }
943807
 
943807
+/* Priviledged when used by server */
943807
+OM_uint32
943807
+ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
943807
+{
943807
+	if (ctx == NULL)
943807
+		return -1;
943807
+
943807
+	ctx->major = gss_verify_mic(&ctx->minor, ctx->context,
943807
+	    gssbuf, gssmic, NULL);
943807
+
943807
+	return (ctx->major);
943807
+}
943807
+
943807
 void
943807
 ssh_gssapi_buildmic(struct sshbuf *b, const char *user, const char *service,
943807
     const char *context, const struct sshbuf *session_id)
943807
@@ -273,11 +500,16 @@ ssh_gssapi_buildmic(struct sshbuf *b, const char *user, const char *service,
943807
 }
943807
 
943807
 int
943807
-ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host)
943807
+ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host,
943807
+    const char *client)
943807
 {
943807
 	gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
943807
 	OM_uint32 major, minor;
943807
 	gss_OID_desc spnego_oid = {6, (void *)"\x2B\x06\x01\x05\x05\x02"};
943807
+	Gssctxt *intctx = NULL;
943807
+
943807
+	if (ctx == NULL)
943807
+		ctx = &intct;;
943807
 
943807
 	/* RFC 4462 says we MUST NOT do SPNEGO */
943807
 	if (oid->length == spnego_oid.length && 
943807
@@ -287,6 +519,10 @@ ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host)
943807
 	ssh_gssapi_build_ctx(ctx);
943807
 	ssh_gssapi_set_oid(*ctx, oid);
943807
 	major = ssh_gssapi_import_name(*ctx, host);
943807
+
943807
+	if (!GSS_ERROR(major) && client)
943807
+		major = ssh_gssapi_client_identity(*ctx, client);
943807
+
943807
 	if (!GSS_ERROR(major)) {
943807
 		major = ssh_gssapi_init_ctx(*ctx, 0, GSS_C_NO_BUFFER, &token, 
943807
 		    NULL);
943807
@@ -296,10 +532,66 @@ ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host)
943807
 			    GSS_C_NO_BUFFER);
943807
 	}
943807
 
943807
-	if (GSS_ERROR(major)) 
943807
+	if (GSS_ERROR(major) || intctx != NULL)
943807
 		ssh_gssapi_delete_ctx(ctx);
943807
 
943807
 	return (!GSS_ERROR(major));
943807
 }
943807
 
943807
+int
943807
+ssh_gssapi_credentials_updated(Gssctxt *ctxt) {
943807
+	static gss_name_t saved_name = GSS_C_NO_NAME;
943807
+	static OM_uint32 saved_lifetime = 0;
943807
+	static gss_OID saved_mech = GSS_C_NO_OID;
943807
+	static gss_name_t name;
943807
+	static OM_uint32 last_call = 0;
943807
+	OM_uint32 lifetime, now, major, minor;
943807
+	int equal;
943807
+
943807
+	now = time(NULL);
943807
+
943807
+	if (ctxt) {
943807
+		debug("Rekey has happened - updating saved versions");
943807
+
943807
+		if (saved_name != GSS_C_NO_NAME)
943807
+			gss_release_name(&minor, &saved_name);
943807
+
943807
+		major = gss_inquire_cred(&minor, GSS_C_NO_CREDENTIAL,
943807
+		    &saved_name, &saved_lifetime, NULL, NULL);
943807
+
943807
+		if (!GSS_ERROR(major)) {
943807
+			saved_mech = ctxt->oid;
943807
+		        saved_lifetime+= now;
943807
+		} else {
943807
+			/* Handle the error */
943807
+		}
943807
+		return 0;
943807
+	}
943807
+
943807
+	if (now - last_call < 10)
943807
+		return 0;
943807
+
943807
+	last_call = now;
943807
+
943807
+	if (saved_mech == GSS_C_NO_OID)
943807
+		return 0;
943807
+
943807
+	major = gss_inquire_cred(&minor, GSS_C_NO_CREDENTIAL,
943807
+	    &name, &lifetime, NULL, NULL);
943807
+	if (major == GSS_S_CREDENTIALS_EXPIRED)
943807
+		return 0;
943807
+	else if (GSS_ERROR(major))
943807
+		return 0;
943807
+
943807
+	major = gss_compare_name(&minor, saved_name, name, &equal);
943807
+	gss_release_name(&minor, &name);
943807
+	if (GSS_ERROR(major))
943807
+		return 0;
943807
+
943807
+	if (equal && (saved_lifetime < lifetime + now - 10))
943807
+		return 1;
943807
+
943807
+	return 0;
943807
+}
943807
+
943807
 #endif /* GSSAPI */
943807
diff --git a/gss-serv-krb5.c b/gss-serv-krb5.c
943807
index a151bc1e..8d2b677f 100644
943807
--- a/gss-serv-krb5.c
943807
+++ b/gss-serv-krb5.c
943807
@@ -1,7 +1,7 @@
943807
 /* $OpenBSD: gss-serv-krb5.c,v 1.9 2018/07/09 21:37:55 markus Exp $ */
943807
 
943807
 /*
943807
- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
943807
+ * Copyright (c) 2001-2007 Simon Wilkinson. All rights reserved.
943807
  *
943807
  * Redistribution and use in source and binary forms, with or without
943807
  * modification, are permitted provided that the following conditions
943807
@@ -120,7 +120,7 @@ ssh_gssapi_krb5_storecreds(ssh_gssapi_client *client)
943807
 	krb5_error_code problem;
943807
 	krb5_principal princ;
943807
 	OM_uint32 maj_status, min_status;
943807
-	int len;
943807
+	const char *new_ccname, *new_cctype;
943807
 	const char *errmsg;
943807
 
943807
 	if (client->creds == NULL) {
943807
@@ -180,11 +180,26 @@ ssh_gssapi_krb5_storecreds(ssh_gssapi_client *client)
943807
 		return;
943807
 	}
943807
 
943807
-	client->store.filename = xstrdup(krb5_cc_get_name(krb_context, ccache));
943807
+	new_cctype = krb5_cc_get_type(krb_context, ccache);
943807
+	new_ccname = krb5_cc_get_name(krb_context, ccache);
943807
+
943807
 	client->store.envvar = "KRB5CCNAME";
943807
-	len = strlen(client->store.filename) + 6;
943807
-	client->store.envval = xmalloc(len);
943807
-	snprintf(client->store.envval, len, "FILE:%s", client->store.filename);
943807
+#ifdef USE_CCAPI
943807
+	xasprintf(&client->store.envval, "API:%s", new_ccname);
943807
+	client->store.filename = NULL;
943807
+#else
943807
+	if (new_ccname[0] == ':')
943807
+		new_ccname++;
943807
+	xasprintf(&client->store.envval, "%s:%s", new_cctype, new_ccname);
943807
+	if (strcmp(new_cctype, "DIR") == 0) {
943807
+		char *p;
943807
+		p = strrchr(client->store.envval, '/');
943807
+		if (p)
943807
+			*p = '\0';
943807
+	}
943807
+	if ((strcmp(new_cctype, "FILE") == 0) || (strcmp(new_cctype, "DIR") == 0))
943807
+		client->store.filename = xstrdup(new_ccname);
943807
+#endif
943807
 
943807
 #ifdef USE_PAM
943807
 	if (options.use_pam)
943807
@@ -193,9 +208,76 @@ ssh_gssapi_krb5_storecreds(ssh_gssapi_client *client)
943807
 
943807
 	krb5_cc_close(krb_context, ccache);
943807
 
943807
+	client->store.data = krb_context;
943807
+
943807
 	return;
943807
 }
943807
 
943807
+int
943807
+ssh_gssapi_krb5_updatecreds(ssh_gssapi_ccache *store,
943807
+    ssh_gssapi_client *client)
943807
+{
943807
+	krb5_ccache ccache = NULL;
943807
+	krb5_principal principal = NULL;
943807
+	char *name = NULL;
943807
+	krb5_error_code problem;
943807
+	OM_uint32 maj_status, min_status;
943807
+
943807
+	if ((problem = krb5_cc_resolve(krb_context, store->envval, &ccache))) {
943807
+                logit("krb5_cc_resolve(): %.100s",
943807
+                    krb5_get_err_text(krb_context, problem));
943807
+                return 0;
943807
+	}
943807
+
943807
+	/* Find out who the principal in this cache is */
943807
+	if ((problem = krb5_cc_get_principal(krb_context, ccache,
943807
+	    &principal))) {
943807
+		logit("krb5_cc_get_principal(): %.100s",
943807
+		    krb5_get_err_text(krb_context, problem));
943807
+		krb5_cc_close(krb_context, ccache);
943807
+		return 0;
943807
+	}
943807
+
943807
+	if ((problem = krb5_unparse_name(krb_context, principal, &name))) {
943807
+		logit("krb5_unparse_name(): %.100s",
943807
+		    krb5_get_err_text(krb_context, problem));
943807
+		krb5_free_principal(krb_context, principal);
943807
+		krb5_cc_close(krb_context, ccache);
943807
+		return 0;
943807
+	}
943807
+
943807
+
943807
+	if (strcmp(name,client->exportedname.value)!=0) {
943807
+		debug("Name in local credentials cache differs. Not storing");
943807
+		krb5_free_principal(krb_context, principal);
943807
+		krb5_cc_close(krb_context, ccache);
943807
+		krb5_free_unparsed_name(krb_context, name);
943807
+		return 0;
943807
+	}
943807
+	krb5_free_unparsed_name(krb_context, name);
943807
+
943807
+	/* Name matches, so lets get on with it! */
943807
+
943807
+	if ((problem = krb5_cc_initialize(krb_context, ccache, principal))) {
943807
+		logit("krb5_cc_initialize(): %.100s",
943807
+		    krb5_get_err_text(krb_context, problem));
943807
+		krb5_free_principal(krb_context, principal);
943807
+		krb5_cc_close(krb_context, ccache);
943807
+		return 0;
943807
+	}
943807
+
943807
+	krb5_free_principal(krb_context, principal);
943807
+
943807
+	if ((maj_status = gss_krb5_copy_ccache(&min_status, client->creds,
943807
+	    ccache))) {
943807
+		logit("gss_krb5_copy_ccache() failed. Sorry!");
943807
+		krb5_cc_close(krb_context, ccache);
943807
+		return 0;
943807
+	}
943807
+
943807
+	return 1;
943807
+}
943807
+
943807
 ssh_gssapi_mech gssapi_kerberos_mech = {
943807
 	"toWM5Slw5Ew8Mqkay+al2g==",
943807
 	"Kerberos",
943807
@@ -203,7 +285,8 @@ ssh_gssapi_mech gssapi_kerberos_mech = {
943807
 	NULL,
943807
 	&ssh_gssapi_krb5_userok,
943807
 	NULL,
943807
-	&ssh_gssapi_krb5_storecreds
943807
+	&ssh_gssapi_krb5_storecreds,
943807
+	&ssh_gssapi_krb5_updatecreds
943807
 };
943807
 
943807
 #endif /* KRB5 */
943807
diff --git a/gss-serv.c b/gss-serv.c
943807
index ab3a15f0..6ce56e92 100644
943807
--- a/gss-serv.c
943807
+++ b/gss-serv.c
943807
@@ -1,7 +1,7 @@
943807
 /* $OpenBSD: gss-serv.c,v 1.32 2020/03/13 03:17:07 djm Exp $ */
943807
 
943807
 /*
943807
- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
943807
+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
943807
  *
943807
  * Redistribution and use in source and binary forms, with or without
943807
  * modification, are permitted provided that the following conditions
943807
@@ -44,17 +44,19 @@
943807
 #include "session.h"
943807
 #include "misc.h"
943807
 #include "servconf.h"
943807
+#include "uidswap.h"
943807
 
943807
 #include "ssh-gss.h"
943807
+#include "monitor_wrap.h"
943807
 
943807
 extern ServerOptions options;
943807
 
943807
 static ssh_gssapi_client gssapi_client =
943807
-    { GSS_C_EMPTY_BUFFER, GSS_C_EMPTY_BUFFER,
943807
-    GSS_C_NO_CREDENTIAL, NULL, {NULL, NULL, NULL, NULL}};
943807
+    { GSS_C_EMPTY_BUFFER, GSS_C_EMPTY_BUFFER, GSS_C_NO_CREDENTIAL,
943807
+    GSS_C_NO_NAME, NULL, {NULL, NULL, NULL, NULL, NULL}, 0, 0};
943807
 
943807
 ssh_gssapi_mech gssapi_null_mech =
943807
-    { NULL, NULL, {0, NULL}, NULL, NULL, NULL, NULL};
943807
+    { NULL, NULL, {0, NULL}, NULL, NULL, NULL, NULL, NULL};
943807
 
943807
 #ifdef KRB5
943807
 extern ssh_gssapi_mech gssapi_kerberos_mech;
943807
@@ -140,6 +142,29 @@ ssh_gssapi_server_ctx(Gssctxt **ctx, gss_OID oid)
943807
 	return (ssh_gssapi_acquire_cred(*ctx));
943807
 }
943807
 
943807
+/* Unprivileged */
943807
+char *
943807
+ssh_gssapi_server_mechanisms(void) {
943807
+	if (supported_oids == NULL)
943807
+		ssh_gssapi_prepare_supported_oids();
943807
+	return (ssh_gssapi_kex_mechs(supported_oids,
943807
+	    &ssh_gssapi_server_check_mech, NULL, NULL,
943807
+	    options.gss_kex_algorithms));
943807
+}
943807
+
943807
+/* Unprivileged */
943807
+int
943807
+ssh_gssapi_server_check_mech(Gssctxt **dum, gss_OID oid, const char *data,
943807
+    const char *dummy) {
943807
+	Gssctxt *ctx = NULL;
943807
+	int res;
943807
+
943807
+	res = !GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctx, oid)));
943807
+	ssh_gssapi_delete_ctx(&ctx;;
943807
+
943807
+	return (res);
943807
+}
943807
+
943807
 /* Unprivileged */
943807
 void
943807
 ssh_gssapi_supported_oids(gss_OID_set *oidset)
943807
@@ -150,7 +175,9 @@ ssh_gssapi_supported_oids(gss_OID_set *oidset)
943807
 	gss_OID_set supported;
943807
 
943807
 	gss_create_empty_oid_set(&min_status, oidset);
943807
-	gss_indicate_mechs(&min_status, &supported);
943807
+
943807
+	if (GSS_ERROR(gss_indicate_mechs(&min_status, &supported)))
943807
+		return;
943807
 
943807
 	while (supported_mechs[i]->name != NULL) {
943807
 		if (GSS_ERROR(gss_test_oid_set_member(&min_status,
943807
@@ -276,8 +303,48 @@ OM_uint32
943807
 ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
943807
 {
943807
 	int i = 0;
943807
+	int equal = 0;
943807
+	gss_name_t new_name = GSS_C_NO_NAME;
943807
+	gss_buffer_desc ename = GSS_C_EMPTY_BUFFER;
943807
+
943807
+	if (options.gss_store_rekey && client->used && ctx->client_creds) {
943807
+		if (client->mech->oid.length != ctx->oid->length ||
943807
+		    (memcmp(client->mech->oid.elements,
943807
+		     ctx->oid->elements, ctx->oid->length) !=0)) {
943807
+			debug("Rekeyed credentials have different mechanism");
943807
+			return GSS_S_COMPLETE;
943807
+		}
943807
+
943807
+		if ((ctx->major = gss_inquire_cred_by_mech(&ctx->minor,
943807
+		    ctx->client_creds, ctx->oid, &new_name,
943807
+		    NULL, NULL, NULL))) {
943807
+			ssh_gssapi_error(ctx);
943807
+			return (ctx->major);
943807
+		}
943807
 
943807
-	gss_buffer_desc ename;
943807
+		ctx->major = gss_compare_name(&ctx->minor, client->name,
943807
+		    new_name, &equal);
943807
+
943807
+		if (GSS_ERROR(ctx->major)) {
943807
+			ssh_gssapi_error(ctx);
943807
+			return (ctx->major);
943807
+		}
943807
+
943807
+		if (!equal) {
943807
+			debug("Rekeyed credentials have different name");
943807
+			return GSS_S_COMPLETE;
943807
+		}
943807
+
943807
+		debug("Marking rekeyed credentials for export");
943807
+
943807
+		gss_release_name(&ctx->minor, &client->name);
943807
+		gss_release_cred(&ctx->minor, &client->creds);
943807
+		client->name = new_name;
943807
+		client->creds = ctx->client_creds;
943807
+		ctx->client_creds = GSS_C_NO_CREDENTIAL;
943807
+		client->updated = 1;
943807
+		return GSS_S_COMPLETE;
943807
+	}
943807
 
943807
 	client->mech = NULL;
943807
 
943807
@@ -292,6 +359,13 @@ ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
943807
 	if (client->mech == NULL)
943807
 		return GSS_S_FAILURE;
943807
 
943807
+	if (ctx->client_creds &&
943807
+	    (ctx->major = gss_inquire_cred_by_mech(&ctx->minor,
943807
+	     ctx->client_creds, ctx->oid, &client->name, NULL, NULL, NULL))) {
943807
+		ssh_gssapi_error(ctx);
943807
+		return (ctx->major);
943807
+	}
943807
+
943807
 	if ((ctx->major = gss_display_name(&ctx->minor, ctx->client,
943807
 	    &client->displayname, NULL))) {
943807
 		ssh_gssapi_error(ctx);
943807
@@ -309,6 +383,8 @@ ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
943807
 		return (ctx->major);
943807
 	}
943807
 
943807
+	gss_release_buffer(&ctx->minor, &ename);
943807
+
943807
 	/* We can't copy this structure, so we just move the pointer to it */
943807
 	client->creds = ctx->client_creds;
943807
 	ctx->client_creds = GSS_C_NO_CREDENTIAL;
943807
@@ -319,11 +395,20 @@ ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
943807
 void
943807
 ssh_gssapi_cleanup_creds(void)
943807
 {
943807
-	if (gssapi_client.store.filename != NULL) {
943807
-		/* Unlink probably isn't sufficient */
943807
-		debug("removing gssapi cred file\"%s\"",
943807
-		    gssapi_client.store.filename);
943807
-		unlink(gssapi_client.store.filename);
943807
+	krb5_ccache ccache = NULL;
943807
+	krb5_error_code problem;
943807
+
943807
+	if (gssapi_client.store.data != NULL) {
943807
+		if ((problem = krb5_cc_resolve(gssapi_client.store.data, gssapi_client.store.envval, &ccache))) {
943807
+			debug_f("krb5_cc_resolve(): %.100s",
943807
+				krb5_get_err_text(gssapi_client.store.data, problem));
943807
+		} else if ((problem = krb5_cc_destroy(gssapi_client.store.data, ccache))) {
943807
+			debug_f("krb5_cc_destroy(): %.100s",
943807
+				krb5_get_err_text(gssapi_client.store.data, problem));
943807
+		} else {
943807
+			krb5_free_context(gssapi_client.store.data);
943807
+			gssapi_client.store.data = NULL;
943807
+		}
943807
 	}
943807
 }
943807
 
943807
@@ -356,19 +441,23 @@ ssh_gssapi_do_child(char ***envp, u_int *envsizep)
943807
 
943807
 /* Privileged */
943807
 int
943807
-ssh_gssapi_userok(char *user)
943807
+ssh_gssapi_userok(char *user, struct passwd *pw, int kex)
943807
 {
943807
 	OM_uint32 lmin;
943807
 
943807
+	(void) kex; /* used in privilege separation */
943807
+
943807
 	if (gssapi_client.exportedname.length == 0 ||
943807
 	    gssapi_client.exportedname.value == NULL) {
943807
 		debug("No suitable client data");
943807
 		return 0;
943807
 	}
943807
 	if (gssapi_client.mech && gssapi_client.mech->userok)
943807
-		if ((*gssapi_client.mech->userok)(&gssapi_client, user))
943807
+		if ((*gssapi_client.mech->userok)(&gssapi_client, user)) {
943807
+			gssapi_client.used = 1;
943807
+			gssapi_client.store.owner = pw;
943807
 			return 1;
943807
-		else {
943807
+		} else {
943807
 			/* Destroy delegated credentials if userok fails */
943807
 			gss_release_buffer(&lmin, &gssapi_client.displayname);
943807
 			gss_release_buffer(&lmin, &gssapi_client.exportedname);
943807
@@ -382,14 +471,90 @@ ssh_gssapi_userok(char *user)
943807
 	return (0);
943807
 }
943807
 
943807
-/* Privileged */
943807
-OM_uint32
943807
-ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
943807
+/* These bits are only used for rekeying. The unpriviledged child is running
943807
+ * as the user, the monitor is root.
943807
+ *
943807
+ * In the child, we want to :
943807
+ *    *) Ask the monitor to store our credentials into the store we specify
943807
+ *    *) If it succeeds, maybe do a PAM update
943807
+ */
943807
+
943807
+/* Stuff for PAM */
943807
+
943807
+#ifdef USE_PAM
943807
+static int ssh_gssapi_simple_conv(int n, const struct pam_message **msg,
943807
+    struct pam_response **resp, void *data)
943807
 {
943807
-	ctx->major = gss_verify_mic(&ctx->minor, ctx->context,
943807
-	    gssbuf, gssmic, NULL);
943807
+	return (PAM_CONV_ERR);
943807
+}
943807
+#endif
943807
 
943807
-	return (ctx->major);
943807
+void
943807
+ssh_gssapi_rekey_creds(void) {
943807
+	int ok;
943807
+#ifdef USE_PAM
943807
+	int ret;
943807
+	pam_handle_t *pamh = NULL;
943807
+	struct pam_conv pamconv = {ssh_gssapi_simple_conv, NULL};
943807
+	char *envstr;
943807
+#endif
943807
+
943807
+	if (gssapi_client.store.filename == NULL &&
943807
+	    gssapi_client.store.envval == NULL &&
943807
+	    gssapi_client.store.envvar == NULL)
943807
+		return;
943807
+
943807
+	ok = PRIVSEP(ssh_gssapi_update_creds(&gssapi_client.store));
943807
+
943807
+	if (!ok)
943807
+		return;
943807
+
943807
+	debug("Rekeyed credentials stored successfully");
943807
+
943807
+	/* Actually managing to play with the ssh pam stack from here will
943807
+	 * be next to impossible. In any case, we may want different options
943807
+	 * for rekeying. So, use our own :)
943807
+	 */
943807
+#ifdef USE_PAM	
943807
+	if (!use_privsep) {
943807
+		debug("Not even going to try and do PAM with privsep disabled");
943807
+		return;
943807
+	}
943807
+
943807
+	ret = pam_start("sshd-rekey", gssapi_client.store.owner->pw_name,
943807
+ 	    &pamconv, &pamh);
943807
+	if (ret)
943807
+		return;
943807
+
943807
+	xasprintf(&envstr, "%s=%s", gssapi_client.store.envvar,
943807
+	    gssapi_client.store.envval);
943807
+
943807
+	ret = pam_putenv(pamh, envstr);
943807
+	if (!ret)
943807
+		pam_setcred(pamh, PAM_REINITIALIZE_CRED);
943807
+	pam_end(pamh, PAM_SUCCESS);
943807
+#endif
943807
+}
943807
+
943807
+int
943807
+ssh_gssapi_update_creds(ssh_gssapi_ccache *store) {
943807
+	int ok = 0;
943807
+
943807
+	/* Check we've got credentials to store */
943807
+	if (!gssapi_client.updated)
943807
+		return 0;
943807
+
943807
+	gssapi_client.updated = 0;
943807
+
943807
+	temporarily_use_uid(gssapi_client.store.owner);
943807
+	if (gssapi_client.mech && gssapi_client.mech->updatecreds)
943807
+		ok = (*gssapi_client.mech->updatecreds)(store, &gssapi_client);
943807
+	else
943807
+		debug("No update function for this mechanism");
943807
+
943807
+	restore_uid();
943807
+
943807
+	return ok;
943807
 }
943807
 
943807
 /* Privileged */
943807
diff --git a/kex.c b/kex.c
943807
index ce85f043..574c7609 100644
943807
--- a/kex.c
943807
+++ b/kex.c
943807
@@ -57,11 +57,16 @@
943807
 #include "misc.h"
943807
 #include "dispatch.h"
943807
 #include "monitor.h"
943807
+#include "xmalloc.h"
943807
 
943807
 #include "ssherr.h"
943807
 #include "sshbuf.h"
943807
 #include "digest.h"
943807
 
943807
+#ifdef GSSAPI
943807
+#include "ssh-gss.h"
943807
+#endif
943807
+
943807
 /* prototype */
943807
 static int kex_choose_conf(struct ssh *);
943807
 static int kex_input_newkeys(int, u_int32_t, struct ssh *);
943807
@@ -115,15 +120,28 @@ static const struct kexalg kexalgs[] = {
943807
 #endif /* HAVE_EVP_SHA256 || !WITH_OPENSSL */
943807
 	{ NULL, 0, -1, -1},
943807
 };
943807
+static const struct kexalg gss_kexalgs[] = {
943807
+#ifdef GSSAPI
943807
+	{ KEX_GSS_GEX_SHA1_ID, KEX_GSS_GEX_SHA1, 0, SSH_DIGEST_SHA1 },
943807
+	{ KEX_GSS_GRP1_SHA1_ID, KEX_GSS_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
943807
+	{ KEX_GSS_GRP14_SHA1_ID, KEX_GSS_GRP14_SHA1, 0, SSH_DIGEST_SHA1 },
943807
+	{ KEX_GSS_GRP14_SHA256_ID, KEX_GSS_GRP14_SHA256, 0, SSH_DIGEST_SHA256 },
943807
+	{ KEX_GSS_GRP16_SHA512_ID, KEX_GSS_GRP16_SHA512, 0, SSH_DIGEST_SHA512 },
943807
+	{ KEX_GSS_NISTP256_SHA256_ID, KEX_GSS_NISTP256_SHA256,
943807
+	    NID_X9_62_prime256v1, SSH_DIGEST_SHA256 },
943807
+	{ KEX_GSS_C25519_SHA256_ID, KEX_GSS_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
943807
+#endif
943807
+	{ NULL, 0, -1, -1},
943807
+};
943807
 
943807
-char *
943807
-kex_alg_list(char sep)
943807
+static char *
943807
+kex_alg_list_internal(char sep, const struct kexalg *algs)
943807
 {
943807
 	char *ret = NULL, *tmp;
943807
 	size_t nlen, rlen = 0;
943807
 	const struct kexalg *k;
943807
 
943807
-	for (k = kexalgs; k->name != NULL; k++) {
943807
+	for (k = algs; k->name != NULL; k++) {
943807
 		if (ret != NULL)
943807
 			ret[rlen++] = sep;
943807
 		nlen = strlen(k->name);
943807
@@ -138,6 +156,18 @@ kex_alg_list(char sep)
943807
 	return ret;
943807
 }
943807
 
943807
+char *
943807
+kex_alg_list(char sep)
943807
+{
943807
+	return kex_alg_list_internal(sep, kexalgs);
943807
+}
943807
+
943807
+char *
943807
+kex_gss_alg_list(char sep)
943807
+{
943807
+	return kex_alg_list_internal(sep, gss_kexalgs);
943807
+}
943807
+
943807
 static const struct kexalg *
943807
 kex_alg_by_name(const char *name)
943807
 {
943807
@@ -147,6 +177,10 @@ kex_alg_by_name(const char *name)
943807
 		if (strcmp(k->name, name) == 0)
943807
 			return k;
943807
 	}
943807
+	for (k = gss_kexalgs; k->name != NULL; k++) {
943807
+		if (strncmp(k->name, name, strlen(k->name)) == 0)
943807
+			return k;
943807
+	}
943807
 	return NULL;
943807
 }
943807
 
943807
@@ -315,6 +349,29 @@ kex_assemble_names(char **listp, const char *def, const char *all)
943807
 	return r;
943807
 }
943807
 
943807
+/* Validate GSS KEX method name list */
943807
+int
943807
+kex_gss_names_valid(const char *names)
943807
+{
943807
+	char *s, *cp, *p;
943807
+
943807
+	if (names == NULL || *names == '\0')
943807
+		return 0;
943807
+	s = cp = xstrdup(names);
943807
+	for ((p = strsep(&cp, ",")); p && *p != '\0';
943807
+	    (p = strsep(&cp, ","))) {
943807
+		if (strncmp(p, "gss-", 4) != 0
943807
+		  || kex_alg_by_name(p) == NULL) {
943807
+			error("Unsupported KEX algorithm \"%.100s\"", p);
943807
+			free(s);
943807
+			return 0;
943807
+		}
943807
+	}
943807
+	debug3("gss kex names ok: [%s]", names);
943807
+	free(s);
943807
+	return 1;
943807
+}
943807
+
943807
 /* put algorithm proposal into buffer */
943807
 int
943807
 kex_prop2buf(struct sshbuf *b, char *proposal[PROPOSAL_MAX])
943807
@@ -698,6 +755,9 @@ kex_free(struct kex *kex)
943807
 	sshbuf_free(kex->server_version);
943807
 	sshbuf_free(kex->client_pub);
943807
 	sshbuf_free(kex->session_id);
943807
+#ifdef GSSAPI
943807
+	free(kex->gss_host);
943807
+#endif /* GSSAPI */
943807
 	free(kex->failed_choice);
943807
 	free(kex->hostkey_alg);
943807
 	free(kex->name);
943807
diff --git a/kex.h b/kex.h
943807
index a5ae6ac0..fe714141 100644
943807
--- a/kex.h
943807
+++ b/kex.h
943807
@@ -102,6 +102,15 @@ enum kex_exchange {
943807
 	KEX_ECDH_SHA2,
943807
 	KEX_C25519_SHA256,
943807
 	KEX_KEM_SNTRUP761X25519_SHA512,
943807
+#ifdef GSSAPI
943807
+	KEX_GSS_GRP1_SHA1,
943807
+	KEX_GSS_GRP14_SHA1,
943807
+	KEX_GSS_GRP14_SHA256,
943807
+	KEX_GSS_GRP16_SHA512,
943807
+	KEX_GSS_GEX_SHA1,
943807
+	KEX_GSS_NISTP256_SHA256,
943807
+	KEX_GSS_C25519_SHA256,
943807
+#endif
943807
 	KEX_MAX
943807
 };
943807
 
943807
@@ -153,6 +162,12 @@ struct kex {
943807
 	u_int	flags;
943807
 	int	hash_alg;
943807
 	int	ec_nid;
943807
+#ifdef GSSAPI
943807
+	int	gss_deleg_creds;
943807
+	int	gss_trust_dns;
943807
+	char    *gss_host;
943807
+	char	*gss_client;
943807
+#endif
943807
 	char	*failed_choice;
943807
 	int	(*verify_host_key)(struct sshkey *, struct ssh *);
943807
 	struct sshkey *(*load_host_public_key)(int, int, struct ssh *);
943807
@@ -174,8 +189,10 @@ struct kex {
943807
 
943807
 int	 kex_names_valid(const char *);
943807
 char	*kex_alg_list(char);
943807
+char	*kex_gss_alg_list(char);
943807
 char	*kex_names_cat(const char *, const char *);
943807
 int	 kex_assemble_names(char **, const char *, const char *);
943807
+int	 kex_gss_names_valid(const char *);
943807
 
943807
 int	 kex_exchange_identification(struct ssh *, int, const char *);
943807
 
943807
@@ -202,6 +219,12 @@ int	 kexgex_client(struct ssh *);
943807
 int	 kexgex_server(struct ssh *);
943807
 int	 kex_gen_client(struct ssh *);
943807
 int	 kex_gen_server(struct ssh *);
943807
+#if defined(GSSAPI) && defined(WITH_OPENSSL)
943807
+int	 kexgssgex_client(struct ssh *);
943807
+int	 kexgssgex_server(struct ssh *);
943807
+int	 kexgss_client(struct ssh *);
943807
+int	 kexgss_server(struct ssh *);
943807
+#endif
943807
 
943807
 int	 kex_dh_keypair(struct kex *);
943807
 int	 kex_dh_enc(struct kex *, const struct sshbuf *, struct sshbuf **,
943807
@@ -234,6 +257,12 @@ int	 kexgex_hash(int, const struct sshbuf *, const struct sshbuf *,
943807
     const BIGNUM *, const u_char *, size_t,
943807
     u_char *, size_t *);
943807
 
943807
+int	 kex_gen_hash(int hash_alg, const struct sshbuf *client_version,
943807
+    const struct sshbuf *server_version, const struct sshbuf *client_kexinit,
943807
+    const struct sshbuf *server_kexinit, const struct sshbuf *server_host_key_blob,
943807
+    const struct sshbuf *client_pub, const struct sshbuf *server_pub,
943807
+    const struct sshbuf *shared_secret, u_char *hash, size_t *hashlen);
943807
+
943807
 void	kexc25519_keygen(u_char key[CURVE25519_SIZE], u_char pub[CURVE25519_SIZE])
943807
 	__attribute__((__bounded__(__minbytes__, 1, CURVE25519_SIZE)))
943807
 	__attribute__((__bounded__(__minbytes__, 2, CURVE25519_SIZE)));
943807
diff --git a/kexdh.c b/kexdh.c
943807
index 67133e33..edaa4676 100644
943807
--- a/kexdh.c
943807
+++ b/kexdh.c
943807
@@ -48,13 +48,23 @@ kex_dh_keygen(struct kex *kex)
943807
 {
943807
 	switch (kex->kex_type) {
943807
 	case KEX_DH_GRP1_SHA1:
943807
+#ifdef GSSAPI
943807
+	case KEX_GSS_GRP1_SHA1:
943807
+#endif
943807
 		kex->dh = dh_new_group1();
943807
 		break;
943807
 	case KEX_DH_GRP14_SHA1:
943807
 	case KEX_DH_GRP14_SHA256:
943807
+#ifdef GSSAPI
943807
+	case KEX_GSS_GRP14_SHA1:
943807
+	case KEX_GSS_GRP14_SHA256:
943807
+#endif
943807
 		kex->dh = dh_new_group14();
943807
 		break;
943807
 	case KEX_DH_GRP16_SHA512:
943807
+#ifdef GSSAPI
943807
+	case KEX_GSS_GRP16_SHA512:
943807
+#endif
943807
 		kex->dh = dh_new_group16();
943807
 		break;
943807
 	case KEX_DH_GRP18_SHA512:
943807
diff --git a/kexgen.c b/kexgen.c
943807
index 69348b96..c0e8c2f4 100644
943807
--- a/kexgen.c
943807
+++ b/kexgen.c
943807
@@ -44,7 +44,7 @@
943807
 static int input_kex_gen_init(int, u_int32_t, struct ssh *);
943807
 static int input_kex_gen_reply(int type, u_int32_t seq, struct ssh *ssh);
943807
 
943807
-static int
943807
+int
943807
 kex_gen_hash(
943807
     int hash_alg,
943807
     const struct sshbuf *client_version,
943807
diff --git a/kexgssc.c b/kexgssc.c
943807
new file mode 100644
943807
index 00000000..f6e1405e
943807
--- /dev/null
943807
+++ b/kexgssc.c
943807
@@ -0,0 +1,611 @@
943807
+/*
943807
+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
943807
+ *
943807
+ * Redistribution and use in source and binary forms, with or without
943807
+ * modification, are permitted provided that the following conditions
943807
+ * are met:
943807
+ * 1. Redistributions of source code must retain the above copyright
943807
+ *    notice, this list of conditions and the following disclaimer.
943807
+ * 2. Redistributions in binary form must reproduce the above copyright
943807
+ *    notice, this list of conditions and the following disclaimer in the
943807
+ *    documentation and/or other materials provided with the distribution.
943807
+ *
943807
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR
943807
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
943807
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
943807
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
943807
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
943807
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
943807
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
943807
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
943807
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
943807
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
943807
+ */
943807
+
943807
+#include "includes.h"
943807
+
943807
+#if defined(GSSAPI) && defined(WITH_OPENSSL)
943807
+
943807
+#include "includes.h"
943807
+
943807
+#include <openssl/crypto.h>
943807
+#include <openssl/bn.h>
943807
+
943807
+#include <string.h>
943807
+
943807
+#include "xmalloc.h"
943807
+#include "sshbuf.h"
943807
+#include "ssh2.h"
943807
+#include "sshkey.h"
943807
+#include "cipher.h"
943807
+#include "kex.h"
943807
+#include "log.h"
943807
+#include "packet.h"
943807
+#include "dh.h"
943807
+#include "digest.h"
943807
+#include "ssherr.h"
943807
+
943807
+#include "ssh-gss.h"
943807
+
943807
+int
943807
+kexgss_client(struct ssh *ssh)
943807
+{
943807
+	struct kex *kex = ssh->kex;
943807
+	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER,
943807
+	    recv_tok = GSS_C_EMPTY_BUFFER,
943807
+	    gssbuf, msg_tok = GSS_C_EMPTY_BUFFER, *token_ptr;
943807
+	Gssctxt *ctxt;
943807
+	OM_uint32 maj_status, min_status, ret_flags;
943807
+	struct sshbuf *server_blob = NULL;
943807
+	struct sshbuf *shared_secret = NULL;
943807
+	struct sshbuf *server_host_key_blob = NULL;
943807
+	struct sshbuf *empty = NULL;
943807
+	u_char *msg;
943807
+	int type = 0;
943807
+	int first = 1;
943807
+	u_char hash[SSH_DIGEST_MAX_LENGTH];
943807
+	size_t hashlen;
943807
+	u_char c;
943807
+	int r;
943807
+
943807
+	/* Initialise our GSSAPI world */
943807
+	ssh_gssapi_build_ctx(&ctxt);
943807
+	if (ssh_gssapi_id_kex(ctxt, kex->name, kex->kex_type)
943807
+	    == GSS_C_NO_OID)
943807
+		fatal("Couldn't identify host exchange");
943807
+
943807
+	if (ssh_gssapi_import_name(ctxt, kex->gss_host))
943807
+		fatal("Couldn't import hostname");
943807
+
943807
+	if (kex->gss_client &&
943807
+	    ssh_gssapi_client_identity(ctxt, kex->gss_client))
943807
+		fatal("Couldn't acquire client credentials");
943807
+
943807
+	/* Step 1 */
943807
+	switch (kex->kex_type) {
943807
+	case KEX_GSS_GRP1_SHA1:
943807
+	case KEX_GSS_GRP14_SHA1:
943807
+	case KEX_GSS_GRP14_SHA256:
943807
+	case KEX_GSS_GRP16_SHA512:
943807
+		r = kex_dh_keypair(kex);
943807
+		break;
943807
+	case KEX_GSS_NISTP256_SHA256:
943807
+		r = kex_ecdh_keypair(kex);
943807
+		break;
943807
+	case KEX_GSS_C25519_SHA256:
943807
+		r = kex_c25519_keypair(kex);
943807
+		break;
943807
+	default:
943807
+		fatal_f("Unexpected KEX type %d", kex->kex_type);
943807
+	}
943807
+	if (r != 0) {
943807
+		ssh_gssapi_delete_ctx(&ctxt);
943807
+		return r;
943807
+	}
943807
+
943807
+	token_ptr = GSS_C_NO_BUFFER;
943807
+
943807
+	do {
943807
+		debug("Calling gss_init_sec_context");
943807
+
943807
+		maj_status = ssh_gssapi_init_ctx(ctxt,
943807
+		    kex->gss_deleg_creds, token_ptr, &send_tok,
943807
+		    &ret_flags);
943807
+
943807
+		if (GSS_ERROR(maj_status)) {
943807
+			/* XXX Useles code: Missing send? */
943807
+			if (send_tok.length != 0) {
943807
+				if ((r = sshpkt_start(ssh,
943807
+				        SSH2_MSG_KEXGSS_CONTINUE)) != 0 ||
943807
+				    (r = sshpkt_put_string(ssh, send_tok.value,
943807
+				        send_tok.length)) != 0)
943807
+					fatal("sshpkt failed: %s", ssh_err(r));
943807
+			}
943807
+			fatal("gss_init_context failed");
943807
+		}
943807
+
943807
+		/* If we've got an old receive buffer get rid of it */
943807
+		if (token_ptr != GSS_C_NO_BUFFER)
943807
+			gss_release_buffer(&min_status, &recv_tok);
943807
+
943807
+		if (maj_status == GSS_S_COMPLETE) {
943807
+			/* If mutual state flag is not true, kex fails */
943807
+			if (!(ret_flags & GSS_C_MUTUAL_FLAG))
943807
+				fatal("Mutual authentication failed");
943807
+
943807
+			/* If integ avail flag is not true kex fails */
943807
+			if (!(ret_flags & GSS_C_INTEG_FLAG))
943807
+				fatal("Integrity check failed");
943807
+		}
943807
+
943807
+		/*
943807
+		 * If we have data to send, then the last message that we
943807
+		 * received cannot have been a 'complete'.
943807
+		 */
943807
+		if (send_tok.length != 0) {
943807
+			if (first) {
943807
+				if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_INIT)) != 0 ||
943807
+				    (r = sshpkt_put_string(ssh, send_tok.value,
943807
+				        send_tok.length)) != 0 ||
943807
+				    (r = sshpkt_put_stringb(ssh, kex->client_pub)) != 0)
943807
+					fatal("failed to construct packet: %s", ssh_err(r));
943807
+				first = 0;
943807
+			} else {
943807
+				if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_CONTINUE)) != 0 ||
943807
+				    (r = sshpkt_put_string(ssh, send_tok.value,
943807
+				        send_tok.length)) != 0)
943807
+					fatal("failed to construct packet: %s", ssh_err(r));
943807
+			}
943807
+			if ((r = sshpkt_send(ssh)) != 0)
943807
+				fatal("failed to send packet: %s", ssh_err(r));
943807
+			gss_release_buffer(&min_status, &send_tok);
943807
+
943807
+			/* If we've sent them data, they should reply */
943807
+			do {
943807
+				type = ssh_packet_read(ssh);
943807
+				if (type == SSH2_MSG_KEXGSS_HOSTKEY) {
943807
+					char *tmp = NULL;
943807
+					size_t tmp_len = 0;
943807
+
943807
+					debug("Received KEXGSS_HOSTKEY");
943807
+					if (server_host_key_blob)
943807
+						fatal("Server host key received more than once");
943807
+					if ((r = sshpkt_get_string(ssh, &tmp, &tmp_len)) != 0)
943807
+						fatal("Failed to read server host key: %s", ssh_err(r));
943807
+					if ((server_host_key_blob = sshbuf_from(tmp, tmp_len)) == NULL)
943807
+						fatal("sshbuf_from failed");
943807
+				}
943807
+			} while (type == SSH2_MSG_KEXGSS_HOSTKEY);
943807
+
943807
+			switch (type) {
943807
+			case SSH2_MSG_KEXGSS_CONTINUE:
943807
+				debug("Received GSSAPI_CONTINUE");
943807
+				if (maj_status == GSS_S_COMPLETE)
943807
+					fatal("GSSAPI Continue received from server when complete");
943807
+				if ((r = ssh_gssapi_sshpkt_get_buffer_desc(ssh,
943807
+				        &recv_tok)) != 0 ||
943807
+				    (r = sshpkt_get_end(ssh)) != 0)
943807
+					fatal("Failed to read token: %s", ssh_err(r));
943807
+				break;
943807
+			case SSH2_MSG_KEXGSS_COMPLETE:
943807
+				debug("Received GSSAPI_COMPLETE");
943807
+				if (msg_tok.value != NULL)
943807
+				        fatal("Received GSSAPI_COMPLETE twice?");
943807
+				if ((r = sshpkt_getb_froms(ssh, &server_blob)) != 0 ||
943807
+				    (r = ssh_gssapi_sshpkt_get_buffer_desc(ssh,
943807
+				        &msg_tok)) != 0)
943807
+					fatal("Failed to read message: %s", ssh_err(r));
943807
+
943807
+				/* Is there a token included? */
943807
+				if ((r = sshpkt_get_u8(ssh, &c)) != 0)
943807
+					fatal("sshpkt failed: %s", ssh_err(r));
943807
+				if (c) {
943807
+					if ((r = ssh_gssapi_sshpkt_get_buffer_desc(
943807
+					    ssh, &recv_tok)) != 0)
943807
+						fatal("Failed to read token: %s", ssh_err(r));
943807
+					/* If we're already complete - protocol error */
943807
+					if (maj_status == GSS_S_COMPLETE)
943807
+						sshpkt_disconnect(ssh, "Protocol error: received token when complete");
943807
+				} else {
943807
+					/* No token included */
943807
+					if (maj_status != GSS_S_COMPLETE)
943807
+						sshpkt_disconnect(ssh, "Protocol error: did not receive final token");
943807
+				}
943807
+				if ((r = sshpkt_get_end(ssh)) != 0) {
943807
+					fatal("Expecting end of packet.");
943807
+				}
943807
+				break;
943807
+			case SSH2_MSG_KEXGSS_ERROR:
943807
+				debug("Received Error");
943807
+				if ((r = sshpkt_get_u32(ssh, &maj_status)) != 0 ||
943807
+				    (r = sshpkt_get_u32(ssh, &min_status)) != 0 ||
943807
+				    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
943807
+				    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 || /* lang tag */
943807
+				    (r = sshpkt_get_end(ssh)) != 0)
943807
+					fatal("sshpkt_get failed: %s", ssh_err(r));
943807
+				fatal("GSSAPI Error: \n%.400s", msg);
943807
+			default:
943807
+				sshpkt_disconnect(ssh, "Protocol error: didn't expect packet type %d",
943807
+				    type);
943807
+			}
943807
+			token_ptr = &recv_tok;
943807
+		} else {
943807
+			/* No data, and not complete */
943807
+			if (maj_status != GSS_S_COMPLETE)
943807
+				fatal("Not complete, and no token output");
943807
+		}
943807
+	} while (maj_status & GSS_S_CONTINUE_NEEDED);
943807
+
943807
+	/*
943807
+	 * We _must_ have received a COMPLETE message in reply from the
943807
+	 * server, which will have set server_blob and msg_tok
943807
+	 */
943807
+
943807
+	if (type != SSH2_MSG_KEXGSS_COMPLETE)
943807
+		fatal("Didn't receive a SSH2_MSG_KEXGSS_COMPLETE when I expected it");
943807
+
943807
+	/* compute shared secret */
943807
+	switch (kex->kex_type) {
943807
+	case KEX_GSS_GRP1_SHA1:
943807
+	case KEX_GSS_GRP14_SHA1:
943807
+	case KEX_GSS_GRP14_SHA256:
943807
+	case KEX_GSS_GRP16_SHA512:
943807
+		r = kex_dh_dec(kex, server_blob, &shared_secret);
943807
+		break;
943807
+	case KEX_GSS_C25519_SHA256:
943807
+		if (sshbuf_ptr(server_blob)[sshbuf_len(server_blob)] & 0x80)
943807
+			fatal("The received key has MSB of last octet set!");
943807
+		r = kex_c25519_dec(kex, server_blob, &shared_secret);
943807
+		break;
943807
+	case KEX_GSS_NISTP256_SHA256:
943807
+		if (sshbuf_len(server_blob) != 65)
943807
+			fatal("The received NIST-P256 key did not match"
943807
+			    "expected length (expected 65, got %zu)", sshbuf_len(server_blob));
943807
+
943807
+		if (sshbuf_ptr(server_blob)[0] != POINT_CONVERSION_UNCOMPRESSED)
943807
+			fatal("The received NIST-P256 key does not have first octet 0x04");
943807
+
943807
+		r = kex_ecdh_dec(kex, server_blob, &shared_secret);
943807
+		break;
943807
+	default:
943807
+		r = SSH_ERR_INVALID_ARGUMENT;
943807
+		break;
943807
+	}
943807
+	if (r != 0)
943807
+		goto out;
943807
+
943807
+	if ((empty = sshbuf_new()) == NULL) {
943807
+		r = SSH_ERR_ALLOC_FAIL;
943807
+		goto out;
943807
+	}
943807
+
943807
+	hashlen = sizeof(hash);
943807
+	if ((r = kex_gen_hash(
943807
+	    kex->hash_alg,
943807
+	    kex->client_version,
943807
+	    kex->server_version,
943807
+	    kex->my,
943807
+	    kex->peer,
943807
+	    (server_host_key_blob ? server_host_key_blob : empty),
943807
+	    kex->client_pub,
943807
+	    server_blob,
943807
+	    shared_secret,
943807
+	    hash, &hashlen)) != 0)
943807
+		fatal_f("Unexpected KEX type %d", kex->kex_type);
943807
+
943807
+	gssbuf.value = hash;
943807
+	gssbuf.length = hashlen;
943807
+
943807
+	/* Verify that the hash matches the MIC we just got. */
943807
+	if (GSS_ERROR(ssh_gssapi_checkmic(ctxt, &gssbuf, &msg_tok)))
943807
+		sshpkt_disconnect(ssh, "Hash's MIC didn't verify");
943807
+
943807
+	gss_release_buffer(&min_status, &msg_tok);
943807
+
943807
+	if (kex->gss_deleg_creds)
943807
+		ssh_gssapi_credentials_updated(ctxt);
943807
+
943807
+	if (gss_kex_context == NULL)
943807
+		gss_kex_context = ctxt;
943807
+	else
943807
+		ssh_gssapi_delete_ctx(&ctxt);
943807
+
943807
+	if ((r = kex_derive_keys(ssh, hash, hashlen, shared_secret)) == 0)
943807
+		r = kex_send_newkeys(ssh);
943807
+
943807
+out:
943807
+	explicit_bzero(hash, sizeof(hash));
943807
+	explicit_bzero(kex->c25519_client_key, sizeof(kex->c25519_client_key));
943807
+	sshbuf_free(empty);
943807
+	sshbuf_free(server_host_key_blob);
943807
+	sshbuf_free(server_blob);
943807
+	sshbuf_free(shared_secret);
943807
+	sshbuf_free(kex->client_pub);
943807
+	kex->client_pub = NULL;
943807
+	return r;
943807
+}
943807
+
943807
+int
943807
+kexgssgex_client(struct ssh *ssh)
943807
+{
943807
+	struct kex *kex = ssh->kex;
943807
+	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER,
943807
+	    recv_tok = GSS_C_EMPTY_BUFFER, gssbuf,
943807
+            msg_tok = GSS_C_EMPTY_BUFFER, *token_ptr;
943807
+	Gssctxt *ctxt;
943807
+	OM_uint32 maj_status, min_status, ret_flags;
943807
+	struct sshbuf *shared_secret = NULL;
943807
+	BIGNUM *p = NULL;
943807
+	BIGNUM *g = NULL;
943807
+	struct sshbuf *buf = NULL;
943807
+	struct sshbuf *server_host_key_blob = NULL;
943807
+	struct sshbuf *server_blob = NULL;
943807
+	BIGNUM *dh_server_pub = NULL;
943807
+	u_char *msg;
943807
+	int type = 0;
943807
+	int first = 1;
943807
+	u_char hash[SSH_DIGEST_MAX_LENGTH];
943807
+	size_t hashlen;
943807
+	const BIGNUM *pub_key, *dh_p, *dh_g;
943807
+	int nbits = 0, min = DH_GRP_MIN, max = DH_GRP_MAX;
943807
+	struct sshbuf *empty = NULL;
943807
+	u_char c;
943807
+	int r;
943807
+
943807
+	/* Initialise our GSSAPI world */
943807
+	ssh_gssapi_build_ctx(&ctxt);
943807
+	if (ssh_gssapi_id_kex(ctxt, kex->name, kex->kex_type)
943807
+	    == GSS_C_NO_OID)
943807
+		fatal("Couldn't identify host exchange");
943807
+
943807
+	if (ssh_gssapi_import_name(ctxt, kex->gss_host))
943807
+		fatal("Couldn't import hostname");
943807
+
943807
+	if (kex->gss_client &&
943807
+	    ssh_gssapi_client_identity(ctxt, kex->gss_client))
943807
+		fatal("Couldn't acquire client credentials");
943807
+
943807
+	debug("Doing group exchange");
943807
+	nbits = dh_estimate(kex->dh_need * 8);
943807
+
943807
+	kex->min = DH_GRP_MIN;
943807
+	kex->max = DH_GRP_MAX;
943807
+	kex->nbits = nbits;
943807
+	if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_GROUPREQ)) != 0 ||
943807
+	    (r = sshpkt_put_u32(ssh, min)) != 0 ||
943807
+	    (r = sshpkt_put_u32(ssh, nbits)) != 0 ||
943807
+	    (r = sshpkt_put_u32(ssh, max)) != 0 ||
943807
+	    (r = sshpkt_send(ssh)) != 0)
943807
+		fatal("Failed to construct a packet: %s", ssh_err(r));
943807
+
943807
+	if ((r = ssh_packet_read_expect(ssh, SSH2_MSG_KEXGSS_GROUP)) != 0)
943807
+		fatal("Error: %s", ssh_err(r));
943807
+
943807
+	if ((r = sshpkt_get_bignum2(ssh, &p)) != 0 ||
943807
+	    (r = sshpkt_get_bignum2(ssh, &g)) != 0 ||
943807
+	    (r = sshpkt_get_end(ssh)) != 0)
943807
+		fatal("shpkt_get_bignum2 failed: %s", ssh_err(r));
943807
+
943807
+	if (BN_num_bits(p) < min || BN_num_bits(p) > max)
943807
+		fatal("GSSGRP_GEX group out of range: %d !< %d !< %d",
943807
+		    min, BN_num_bits(p), max);
943807
+
943807
+	if ((kex->dh = dh_new_group(g, p)) == NULL)
943807
+		fatal("dn_new_group() failed");
943807
+	p = g = NULL; /* belong to kex->dh now */
943807
+
943807
+	if ((r = dh_gen_key(kex->dh, kex->we_need * 8)) != 0)
943807
+		goto out;
943807
+	DH_get0_key(kex->dh, &pub_key, NULL);
943807
+
943807
+	token_ptr = GSS_C_NO_BUFFER;
943807
+
943807
+	do {
943807
+		/* Step 2 - call GSS_Init_sec_context() */
943807
+		debug("Calling gss_init_sec_context");
943807
+
943807
+		maj_status = ssh_gssapi_init_ctx(ctxt,
943807
+		    kex->gss_deleg_creds, token_ptr, &send_tok,
943807
+		    &ret_flags);
943807
+
943807
+		if (GSS_ERROR(maj_status)) {
943807
+			/* XXX Useles code: Missing send? */
943807
+			if (send_tok.length != 0) {
943807
+				if ((r = sshpkt_start(ssh,
943807
+				        SSH2_MSG_KEXGSS_CONTINUE)) != 0 ||
943807
+				    (r = sshpkt_put_string(ssh, send_tok.value,
943807
+				        send_tok.length)) != 0)
943807
+					fatal("sshpkt failed: %s", ssh_err(r));
943807
+			}
943807
+			fatal("gss_init_context failed");
943807
+		}
943807
+
943807
+		/* If we've got an old receive buffer get rid of it */
943807
+		if (token_ptr != GSS_C_NO_BUFFER)
943807
+			gss_release_buffer(&min_status, &recv_tok);
943807
+
943807
+		if (maj_status == GSS_S_COMPLETE) {
943807
+			/* If mutual state flag is not true, kex fails */
943807
+			if (!(ret_flags & GSS_C_MUTUAL_FLAG))
943807
+				fatal("Mutual authentication failed");
943807
+
943807
+			/* If integ avail flag is not true kex fails */
943807
+			if (!(ret_flags & GSS_C_INTEG_FLAG))
943807
+				fatal("Integrity check failed");
943807
+		}
943807
+
943807
+		/*
943807
+		 * If we have data to send, then the last message that we
943807
+		 * received cannot have been a 'complete'.
943807
+		 */
943807
+		if (send_tok.length != 0) {
943807
+			if (first) {
943807
+				if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_INIT)) != 0 ||
943807
+				    (r = sshpkt_put_string(ssh, send_tok.value,
943807
+				        send_tok.length)) != 0 ||
943807
+				    (r = sshpkt_put_bignum2(ssh, pub_key)) != 0)
943807
+					fatal("sshpkt failed: %s", ssh_err(r));
943807
+				first = 0;
943807
+			} else {
943807
+				if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_CONTINUE)) != 0 ||
943807
+				    (r = sshpkt_put_string(ssh,send_tok.value,
943807
+				        send_tok.length)) != 0)
943807
+					fatal("sshpkt failed: %s", ssh_err(r));
943807
+			}
943807
+			if ((r = sshpkt_send(ssh)) != 0)
943807
+				fatal("sshpkt_send failed: %s", ssh_err(r));
943807
+			gss_release_buffer(&min_status, &send_tok);
943807
+
943807
+			/* If we've sent them data, they should reply */
943807
+			do {
943807
+				type = ssh_packet_read(ssh);
943807
+				if (type == SSH2_MSG_KEXGSS_HOSTKEY) {
943807
+					char *tmp = NULL;
943807
+					size_t tmp_len = 0;
943807
+
943807
+					debug("Received KEXGSS_HOSTKEY");
943807
+					if (server_host_key_blob)
943807
+						fatal("Server host key received more than once");
943807
+					if ((r = sshpkt_get_string(ssh, &tmp, &tmp_len)) != 0)
943807
+						fatal("sshpkt failed: %s", ssh_err(r));
943807
+					if ((server_host_key_blob = sshbuf_from(tmp, tmp_len)) == NULL)
943807
+						fatal("sshbuf_from failed");
943807
+				}
943807
+			} while (type == SSH2_MSG_KEXGSS_HOSTKEY);
943807
+
943807
+			switch (type) {
943807
+			case SSH2_MSG_KEXGSS_CONTINUE:
943807
+				debug("Received GSSAPI_CONTINUE");
943807
+				if (maj_status == GSS_S_COMPLETE)
943807
+					fatal("GSSAPI Continue received from server when complete");
943807
+				if ((r = ssh_gssapi_sshpkt_get_buffer_desc(ssh,
943807
+				        &recv_tok)) != 0 ||
943807
+				    (r = sshpkt_get_end(ssh)) != 0)
943807
+					fatal("sshpkt failed: %s", ssh_err(r));
943807
+				break;
943807
+			case SSH2_MSG_KEXGSS_COMPLETE:
943807
+				debug("Received GSSAPI_COMPLETE");
943807
+				if (msg_tok.value != NULL)
943807
+				        fatal("Received GSSAPI_COMPLETE twice?");
943807
+				if ((r = sshpkt_getb_froms(ssh, &server_blob)) != 0 ||
943807
+				    (r = ssh_gssapi_sshpkt_get_buffer_desc(ssh,
943807
+				        &msg_tok)) != 0)
943807
+					fatal("sshpkt failed: %s", ssh_err(r));
943807
+
943807
+				/* Is there a token included? */
943807
+				if ((r = sshpkt_get_u8(ssh, &c)) != 0)
943807
+					fatal("sshpkt failed: %s", ssh_err(r));
943807
+				if (c) {
943807
+					if ((r = ssh_gssapi_sshpkt_get_buffer_desc(
943807
+					        ssh, &recv_tok)) != 0 ||
943807
+					    (r = sshpkt_get_end(ssh)) != 0)
943807
+						fatal("sshpkt failed: %s", ssh_err(r));
943807
+					/* If we're already complete - protocol error */
943807
+					if (maj_status == GSS_S_COMPLETE)
943807
+						sshpkt_disconnect(ssh, "Protocol error: received token when complete");
943807
+				} else {
943807
+					/* No token included */
943807
+					if (maj_status != GSS_S_COMPLETE)
943807
+						sshpkt_disconnect(ssh, "Protocol error: did not receive final token");
943807
+				}
943807
+				break;
943807
+			case SSH2_MSG_KEXGSS_ERROR:
943807
+				debug("Received Error");
943807
+				if ((r = sshpkt_get_u32(ssh, &maj_status)) != 0 ||
943807
+				    (r = sshpkt_get_u32(ssh, &min_status)) != 0 ||
943807
+				    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
943807
+				    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 || /* lang tag */
943807
+				    (r = sshpkt_get_end(ssh)) != 0)
943807
+					fatal("sshpkt failed: %s", ssh_err(r));
943807
+				fatal("GSSAPI Error: \n%.400s", msg);
943807
+			default:
943807
+				sshpkt_disconnect(ssh, "Protocol error: didn't expect packet type %d",
943807
+				    type);
943807
+			}
943807
+			token_ptr = &recv_tok;
943807
+		} else {
943807
+			/* No data, and not complete */
943807
+			if (maj_status != GSS_S_COMPLETE)
943807
+				fatal("Not complete, and no token output");
943807
+		}
943807
+	} while (maj_status & GSS_S_CONTINUE_NEEDED);
943807
+
943807
+	/*
943807
+	 * We _must_ have received a COMPLETE message in reply from the
943807
+	 * server, which will have set dh_server_pub and msg_tok
943807
+	 */
943807
+
943807
+	if (type != SSH2_MSG_KEXGSS_COMPLETE)
943807
+		fatal("Didn't receive a SSH2_MSG_KEXGSS_COMPLETE when I expected it");
943807
+
943807
+	/* 7. C verifies that the key Q_S is valid */
943807
+	/* 8. C computes shared secret */
943807
+	if ((buf = sshbuf_new()) == NULL ||
943807
+	    (r = sshbuf_put_stringb(buf, server_blob)) != 0 ||
943807
+	    (r = sshbuf_get_bignum2(buf, &dh_server_pub)) != 0)
943807
+		goto out;
943807
+	sshbuf_free(buf);
943807
+	buf = NULL;
943807
+
943807
+	if ((shared_secret = sshbuf_new()) == NULL) {
943807
+		r = SSH_ERR_ALLOC_FAIL;
943807
+		goto out;
943807
+	}
943807
+
943807
+	if ((r = kex_dh_compute_key(kex, dh_server_pub, shared_secret)) != 0)
943807
+		goto out;
943807
+	if ((empty = sshbuf_new()) == NULL) {
943807
+		r = SSH_ERR_ALLOC_FAIL;
943807
+		goto out;
943807
+	}
943807
+
943807
+	DH_get0_pqg(kex->dh, &dh_p, NULL, &dh_g);
943807
+	hashlen = sizeof(hash);
943807
+	if ((r = kexgex_hash(
943807
+	    kex->hash_alg,
943807
+	    kex->client_version,
943807
+	    kex->server_version,
943807
+	    kex->my,
943807
+	    kex->peer,
943807
+	    (server_host_key_blob ? server_host_key_blob : empty),
943807
+ 	    kex->min, kex->nbits, kex->max,
943807
+	    dh_p, dh_g,
943807
+	    pub_key,
943807
+	    dh_server_pub,
943807
+	    sshbuf_ptr(shared_secret), sshbuf_len(shared_secret),
943807
+	    hash, &hashlen)) != 0)
943807
+		fatal("Failed to calculate hash: %s", ssh_err(r));
943807
+
943807
+	gssbuf.value = hash;
943807
+	gssbuf.length = hashlen;
943807
+
943807
+	/* Verify that the hash matches the MIC we just got. */
943807
+	if (GSS_ERROR(ssh_gssapi_checkmic(ctxt, &gssbuf, &msg_tok)))
943807
+		sshpkt_disconnect(ssh, "Hash's MIC didn't verify");
943807
+
943807
+	gss_release_buffer(&min_status, &msg_tok);
943807
+
943807
+	if (kex->gss_deleg_creds)
943807
+		ssh_gssapi_credentials_updated(ctxt);
943807
+
943807
+	if (gss_kex_context == NULL)
943807
+		gss_kex_context = ctxt;
943807
+	else
943807
+		ssh_gssapi_delete_ctx(&ctxt);
943807
+
943807
+	/* Finally derive the keys and send them */
943807
+	if ((r = kex_derive_keys(ssh, hash, hashlen, shared_secret)) == 0)
943807
+		r = kex_send_newkeys(ssh);
943807
+out:
943807
+	sshbuf_free(buf);
943807
+	sshbuf_free(server_blob);
943807
+	sshbuf_free(empty);
943807
+	explicit_bzero(hash, sizeof(hash));
943807
+	DH_free(kex->dh);
943807
+	kex->dh = NULL;
943807
+	BN_clear_free(dh_server_pub);
943807
+	sshbuf_free(shared_secret);
943807
+	sshbuf_free(server_host_key_blob);
943807
+	return r;
943807
+}
943807
+#endif /* defined(GSSAPI) && defined(WITH_OPENSSL) */
943807
diff --git a/kexgsss.c b/kexgsss.c
943807
new file mode 100644
943807
index 00000000..60bc02de
943807
--- /dev/null
943807
+++ b/kexgsss.c
943807
@@ -0,0 +1,482 @@
943807
+/*
943807
+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
943807
+ *
943807
+ * Redistribution and use in source and binary forms, with or without
943807
+ * modification, are permitted provided that the following conditions
943807
+ * are met:
943807
+ * 1. Redistributions of source code must retain the above copyright
943807
+ *    notice, this list of conditions and the following disclaimer.
943807
+ * 2. Redistributions in binary form must reproduce the above copyright
943807
+ *    notice, this list of conditions and the following disclaimer in the
943807
+ *    documentation and/or other materials provided with the distribution.
943807
+ *
943807
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR
943807
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
943807
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
943807
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
943807
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
943807
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
943807
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
943807
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
943807
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
943807
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
943807
+ */
943807
+
943807
+#include "includes.h"
943807
+
943807
+#if defined(GSSAPI) && defined(WITH_OPENSSL)
943807
+
943807
+#include <string.h>
943807
+
943807
+#include <openssl/crypto.h>
943807
+#include <openssl/bn.h>
943807
+
943807
+#include "xmalloc.h"
943807
+#include "sshbuf.h"
943807
+#include "ssh2.h"
943807
+#include "sshkey.h"
943807
+#include "cipher.h"
943807
+#include "kex.h"
943807
+#include "log.h"
943807
+#include "packet.h"
943807
+#include "dh.h"
943807
+#include "ssh-gss.h"
943807
+#include "monitor_wrap.h"
943807
+#include "misc.h"      /* servconf.h needs misc.h for struct ForwardOptions */
943807
+#include "servconf.h"
943807
+#include "ssh-gss.h"
943807
+#include "digest.h"
943807
+#include "ssherr.h"
943807
+
943807
+extern ServerOptions options;
943807
+
943807
+int
943807
+kexgss_server(struct ssh *ssh)
943807
+{
943807
+	struct kex *kex = ssh->kex;
943807
+	OM_uint32 maj_status, min_status;
943807
+
943807
+	/*
943807
+	 * Some GSSAPI implementations use the input value of ret_flags (an
943807
+	 * output variable) as a means of triggering mechanism specific
943807
+	 * features. Initializing it to zero avoids inadvertently
943807
+	 * activating this non-standard behaviour.
943807
+	 */
943807
+
943807
+	OM_uint32 ret_flags = 0;
943807
+	gss_buffer_desc gssbuf = {0, NULL}, recv_tok, msg_tok;
943807
+	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
943807
+	Gssctxt *ctxt = NULL;
943807
+	struct sshbuf *shared_secret = NULL;
943807
+	struct sshbuf *client_pubkey = NULL;
943807
+	struct sshbuf *server_pubkey = NULL;
943807
+	struct sshbuf *empty = sshbuf_new();
943807
+	int type = 0;
943807
+	gss_OID oid;
943807
+	char *mechs;
943807
+	u_char hash[SSH_DIGEST_MAX_LENGTH];
943807
+	size_t hashlen;
943807
+	int r;
943807
+
943807
+	/* Initialise GSSAPI */
943807
+
943807
+	/* If we're rekeying, privsep means that some of the private structures
943807
+	 * in the GSSAPI code are no longer available. This kludges them back
943807
+	 * into life
943807
+	 */
943807
+	if (!ssh_gssapi_oid_table_ok()) {
943807
+		mechs = ssh_gssapi_server_mechanisms();
943807
+		free(mechs);
943807
+	}
943807
+
943807
+	debug2_f("Identifying %s", kex->name);
943807
+	oid = ssh_gssapi_id_kex(NULL, kex->name, kex->kex_type);
943807
+	if (oid == GSS_C_NO_OID)
943807
+	   fatal("Unknown gssapi mechanism");
943807
+
943807
+	debug2_f("Acquiring credentials");
943807
+
943807
+	if (GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctxt, oid))))
943807
+		fatal("Unable to acquire credentials for the server");
943807
+
943807
+	do {
943807
+		debug("Wait SSH2_MSG_KEXGSS_INIT");
943807
+		type = ssh_packet_read(ssh);
943807
+		switch(type) {
943807
+		case SSH2_MSG_KEXGSS_INIT:
943807
+			if (gssbuf.value != NULL)
943807
+				fatal("Received KEXGSS_INIT after initialising");
943807
+			if ((r = ssh_gssapi_sshpkt_get_buffer_desc(ssh,
943807
+			        &recv_tok)) != 0 ||
943807
+			    (r = sshpkt_getb_froms(ssh, &client_pubkey)) != 0 ||
943807
+			    (r = sshpkt_get_end(ssh)) != 0)
943807
+				fatal("sshpkt failed: %s", ssh_err(r));
943807
+
943807
+			switch (kex->kex_type) {
943807
+			case KEX_GSS_GRP1_SHA1:
943807
+			case KEX_GSS_GRP14_SHA1:
943807
+			case KEX_GSS_GRP14_SHA256:
943807
+			case KEX_GSS_GRP16_SHA512:
943807
+				r = kex_dh_enc(kex, client_pubkey, &server_pubkey,
943807
+				    &shared_secret);
943807
+				break;
943807
+			case KEX_GSS_NISTP256_SHA256:
943807
+				r = kex_ecdh_enc(kex, client_pubkey, &server_pubkey,
943807
+				    &shared_secret);
943807
+				break;
943807
+			case KEX_GSS_C25519_SHA256:
943807
+				r = kex_c25519_enc(kex, client_pubkey, &server_pubkey,
943807
+				    &shared_secret);
943807
+				break;
943807
+			default:
943807
+				fatal_f("Unexpected KEX type %d", kex->kex_type);
943807
+			}
943807
+			if (r != 0)
943807
+				goto out;
943807
+
943807
+			/* Send SSH_MSG_KEXGSS_HOSTKEY here, if we want */
943807
+
943807
+			/* Calculate the hash early so we can free the
943807
+			* client_pubkey, which has reference to the parent
943807
+			* buffer state->incoming_packet
943807
+			*/
943807
+			hashlen = sizeof(hash);
943807
+			if ((r = kex_gen_hash(
943807
+			    kex->hash_alg,
943807
+			    kex->client_version,
943807
+			    kex->server_version,
943807
+			    kex->peer,
943807
+			    kex->my,
943807
+			    empty,
943807
+			    client_pubkey,
943807
+			    server_pubkey,
943807
+			    shared_secret,
943807
+			    hash, &hashlen)) != 0)
943807
+				goto out;
943807
+
943807
+			gssbuf.value = hash;
943807
+			gssbuf.length = hashlen;
943807
+
943807
+			sshbuf_free(client_pubkey);
943807
+			client_pubkey = NULL;
943807
+
943807
+			break;
943807
+		case SSH2_MSG_KEXGSS_CONTINUE:
943807
+			if ((r = ssh_gssapi_sshpkt_get_buffer_desc(ssh,
943807
+			        &recv_tok)) != 0 ||
943807
+			    (r = sshpkt_get_end(ssh)) != 0)
943807
+				fatal("sshpkt failed: %s", ssh_err(r));
943807
+			break;
943807
+		default:
943807
+			sshpkt_disconnect(ssh,
943807
+			    "Protocol error: didn't expect packet type %d",
943807
+			    type);
943807
+		}
943807
+
943807
+		maj_status = PRIVSEP(ssh_gssapi_accept_ctx(ctxt, &recv_tok,
943807
+		    &send_tok, &ret_flags));
943807
+
943807
+		gss_release_buffer(&min_status, &recv_tok);
943807
+
943807
+		if (maj_status != GSS_S_COMPLETE && send_tok.length == 0)
943807
+			fatal("Zero length token output when incomplete");
943807
+
943807
+		if (gssbuf.value == NULL)
943807
+			fatal("No client public key");
943807
+
943807
+		if (maj_status & GSS_S_CONTINUE_NEEDED) {
943807
+			debug("Sending GSSAPI_CONTINUE");
943807
+			if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_CONTINUE)) != 0 ||
943807
+			    (r = sshpkt_put_string(ssh, send_tok.value, send_tok.length)) != 0 ||
943807
+			    (r = sshpkt_send(ssh)) != 0)
943807
+				fatal("sshpkt failed: %s", ssh_err(r));
943807
+			gss_release_buffer(&min_status, &send_tok);
943807
+		}
943807
+	} while (maj_status & GSS_S_CONTINUE_NEEDED);
943807
+
943807
+	if (GSS_ERROR(maj_status)) {
943807
+		if (send_tok.length > 0) {
943807
+			if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_CONTINUE)) != 0 ||
943807
+			    (r = sshpkt_put_string(ssh, send_tok.value, send_tok.length)) != 0 ||
943807
+			    (r = sshpkt_send(ssh)) != 0)
943807
+				fatal("sshpkt failed: %s", ssh_err(r));
943807
+		}
943807
+		fatal("accept_ctx died");
943807
+	}
943807
+
943807
+	if (!(ret_flags & GSS_C_MUTUAL_FLAG))
943807
+		fatal("Mutual Authentication flag wasn't set");
943807
+
943807
+	if (!(ret_flags & GSS_C_INTEG_FLAG))
943807
+		fatal("Integrity flag wasn't set");
943807
+
943807
+	if (GSS_ERROR(PRIVSEP(ssh_gssapi_sign(ctxt, &gssbuf, &msg_tok))))
943807
+		fatal("Couldn't get MIC");
943807
+
943807
+	if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_COMPLETE)) != 0 ||
943807
+	    (r = sshpkt_put_stringb(ssh, server_pubkey)) != 0 ||
943807
+	    (r = sshpkt_put_string(ssh, msg_tok.value, msg_tok.length)) != 0)
943807
+		fatal("sshpkt failed: %s", ssh_err(r));
943807
+
943807
+	if (send_tok.length != 0) {
943807
+		if ((r = sshpkt_put_u8(ssh, 1)) != 0 || /* true */
943807
+		    (r = sshpkt_put_string(ssh, send_tok.value, send_tok.length)) != 0)
943807
+			fatal("sshpkt failed: %s", ssh_err(r));
943807
+	} else {
943807
+		if ((r = sshpkt_put_u8(ssh, 0)) != 0) /* false */
943807
+			fatal("sshpkt failed: %s", ssh_err(r));
943807
+	}
943807
+	if ((r = sshpkt_send(ssh)) != 0)
943807
+		fatal("sshpkt_send failed: %s", ssh_err(r));
943807
+
943807
+	gss_release_buffer(&min_status, &send_tok);
943807
+	gss_release_buffer(&min_status, &msg_tok);
943807
+
943807
+	if (gss_kex_context == NULL)
943807
+		gss_kex_context = ctxt;
943807
+	else
943807
+		ssh_gssapi_delete_ctx(&ctxt);
943807
+
943807
+	if ((r = kex_derive_keys(ssh, hash, hashlen, shared_secret)) == 0)
943807
+		r = kex_send_newkeys(ssh);
943807
+
943807
+	/* If this was a rekey, then save out any delegated credentials we
943807
+	 * just exchanged.  */
943807
+	if (options.gss_store_rekey)
943807
+		ssh_gssapi_rekey_creds();
943807
+out:
943807
+	sshbuf_free(empty);
943807
+	explicit_bzero(hash, sizeof(hash));
943807
+	sshbuf_free(shared_secret);
943807
+	sshbuf_free(client_pubkey);
943807
+	sshbuf_free(server_pubkey);
943807
+	return r;
943807
+}
943807
+
943807
+int
943807
+kexgssgex_server(struct ssh *ssh)
943807
+{
943807
+	struct kex *kex = ssh->kex;
943807
+	OM_uint32 maj_status, min_status;
943807
+
943807
+	/*
943807
+	 * Some GSSAPI implementations use the input value of ret_flags (an
943807
+	 * output variable) as a means of triggering mechanism specific
943807
+	 * features. Initializing it to zero avoids inadvertently
943807
+	 * activating this non-standard behaviour.
943807
+	 */
943807
+
943807
+	OM_uint32 ret_flags = 0;
943807
+	gss_buffer_desc gssbuf, recv_tok, msg_tok;
943807
+	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
943807
+	Gssctxt *ctxt = NULL;
943807
+	struct sshbuf *shared_secret = NULL;
943807
+	int type = 0;
943807
+	gss_OID oid;
943807
+	char *mechs;
943807
+	u_char hash[SSH_DIGEST_MAX_LENGTH];
943807
+	size_t hashlen;
943807
+	BIGNUM *dh_client_pub = NULL;
943807
+	const BIGNUM *pub_key, *dh_p, *dh_g;
943807
+	int min = -1, max = -1, nbits = -1;
943807
+	int cmin = -1, cmax = -1; /* client proposal */
943807
+	struct sshbuf *empty = sshbuf_new();
943807
+	int r;
943807
+
943807
+	/* Initialise GSSAPI */
943807
+
943807
+	/* If we're rekeying, privsep means that some of the private structures
943807
+	 * in the GSSAPI code are no longer available. This kludges them back
943807
+	 * into life
943807
+	 */
943807
+	if (!ssh_gssapi_oid_table_ok())
943807
+		if ((mechs = ssh_gssapi_server_mechanisms()))
943807
+			free(mechs);
943807
+
943807
+	debug2_f("Identifying %s", kex->name);
943807
+	oid = ssh_gssapi_id_kex(NULL, kex->name, kex->kex_type);
943807
+	if (oid == GSS_C_NO_OID)
943807
+	   fatal("Unknown gssapi mechanism");
943807
+
943807
+	debug2_f("Acquiring credentials");
943807
+
943807
+	if (GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctxt, oid))))
943807
+		fatal("Unable to acquire credentials for the server");
943807
+
943807
+	/* 5. S generates an ephemeral key pair (do the allocations early) */
943807
+	debug("Doing group exchange");
943807
+	ssh_packet_read_expect(ssh, SSH2_MSG_KEXGSS_GROUPREQ);
943807
+	/* store client proposal to provide valid signature */
943807
+	if ((r = sshpkt_get_u32(ssh, &cmin)) != 0 ||
943807
+	    (r = sshpkt_get_u32(ssh, &nbits)) != 0 ||
943807
+	    (r = sshpkt_get_u32(ssh, &cmax)) != 0 ||
943807
+	    (r = sshpkt_get_end(ssh)) != 0)
943807
+		fatal("sshpkt failed: %s", ssh_err(r));
943807
+	kex->nbits = nbits;
943807
+	kex->min = cmin;
943807
+	kex->max = cmax;
943807
+	min = MAX(DH_GRP_MIN, cmin);
943807
+	max = MIN(DH_GRP_MAX, cmax);
943807
+	nbits = MAXIMUM(DH_GRP_MIN, nbits);
943807
+	nbits = MINIMUM(DH_GRP_MAX, nbits);
943807
+	if (max < min || nbits < min || max < nbits)
943807
+		fatal("GSS_GEX, bad parameters: %d !< %d !< %d",
943807
+		    min, nbits, max);
943807
+	kex->dh = PRIVSEP(choose_dh(min, nbits, max));
943807
+	if (kex->dh == NULL) {
943807
+		sshpkt_disconnect(ssh, "Protocol error: no matching group found");
943807
+		fatal("Protocol error: no matching group found");
943807
+	}
943807
+
943807
+	DH_get0_pqg(kex->dh, &dh_p, NULL, &dh_g);
943807
+	if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_GROUP)) != 0 ||
943807
+	    (r = sshpkt_put_bignum2(ssh, dh_p)) != 0 ||
943807
+	    (r = sshpkt_put_bignum2(ssh, dh_g)) != 0 ||
943807
+	    (r = sshpkt_send(ssh)) != 0)
943807
+		fatal("sshpkt failed: %s", ssh_err(r));
943807
+
943807
+	if ((r = ssh_packet_write_wait(ssh)) != 0)
943807
+		fatal("ssh_packet_write_wait: %s", ssh_err(r));
943807
+
943807
+	/* Compute our exchange value in parallel with the client */
943807
+	if ((r = dh_gen_key(kex->dh, kex->we_need * 8)) != 0)
943807
+		goto out;
943807
+
943807
+	do {
943807
+		debug("Wait SSH2_MSG_GSSAPI_INIT");
943807
+		type = ssh_packet_read(ssh);
943807
+		switch(type) {
943807
+		case SSH2_MSG_KEXGSS_INIT:
943807
+			if (dh_client_pub != NULL)
943807
+				fatal("Received KEXGSS_INIT after initialising");
943807
+			if ((r = ssh_gssapi_sshpkt_get_buffer_desc(ssh,
943807
+			        &recv_tok)) != 0 ||
943807
+			    (r = sshpkt_get_bignum2(ssh, &dh_client_pub)) != 0 ||
943807
+			    (r = sshpkt_get_end(ssh)) != 0)
943807
+				fatal("sshpkt failed: %s", ssh_err(r));
943807
+
943807
+			/* Send SSH_MSG_KEXGSS_HOSTKEY here, if we want */
943807
+			break;
943807
+		case SSH2_MSG_KEXGSS_CONTINUE:
943807
+			if ((r = ssh_gssapi_sshpkt_get_buffer_desc(ssh,
943807
+			        &recv_tok)) != 0 ||
943807
+			    (r = sshpkt_get_end(ssh)) != 0)
943807
+				fatal("sshpkt failed: %s", ssh_err(r));
943807
+			break;
943807
+		default:
943807
+			sshpkt_disconnect(ssh,
943807
+			    "Protocol error: didn't expect packet type %d",
943807
+			    type);
943807
+		}
943807
+
943807
+		maj_status = PRIVSEP(ssh_gssapi_accept_ctx(ctxt, &recv_tok,
943807
+		    &send_tok, &ret_flags));
943807
+
943807
+		gss_release_buffer(&min_status, &recv_tok);
943807
+
943807
+		if (maj_status != GSS_S_COMPLETE && send_tok.length == 0)
943807
+			fatal("Zero length token output when incomplete");
943807
+
943807
+		if (dh_client_pub == NULL)
943807
+			fatal("No client public key");
943807
+
943807
+		if (maj_status & GSS_S_CONTINUE_NEEDED) {
943807
+			debug("Sending GSSAPI_CONTINUE");
943807
+			if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_CONTINUE)) != 0 ||
943807
+			    (r = sshpkt_put_string(ssh, send_tok.value, send_tok.length)) != 0 ||
943807
+			    (r = sshpkt_send(ssh)) != 0)
943807
+				fatal("sshpkt failed: %s", ssh_err(r));
943807
+			gss_release_buffer(&min_status, &send_tok);
943807
+		}
943807
+	} while (maj_status & GSS_S_CONTINUE_NEEDED);
943807
+
943807
+	if (GSS_ERROR(maj_status)) {
943807
+		if (send_tok.length > 0) {
943807
+			if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_CONTINUE)) != 0 ||
943807
+			    (r = sshpkt_put_string(ssh, send_tok.value, send_tok.length)) != 0 ||
943807
+			    (r = sshpkt_send(ssh)) != 0)
943807
+				fatal("sshpkt failed: %s", ssh_err(r));
943807
+		}
943807
+		fatal("accept_ctx died");
943807
+	}
943807
+
943807
+	if (!(ret_flags & GSS_C_MUTUAL_FLAG))
943807
+		fatal("Mutual Authentication flag wasn't set");
943807
+
943807
+	if (!(ret_flags & GSS_C_INTEG_FLAG))
943807
+		fatal("Integrity flag wasn't set");
943807
+
943807
+	/* calculate shared secret */
943807
+	if ((shared_secret = sshbuf_new()) == NULL) {
943807
+		r = SSH_ERR_ALLOC_FAIL;
943807
+		goto out;
943807
+	}
943807
+	if ((r = kex_dh_compute_key(kex, dh_client_pub, shared_secret)) != 0)
943807
+		goto out;
943807
+
943807
+	DH_get0_key(kex->dh, &pub_key, NULL);
943807
+	DH_get0_pqg(kex->dh, &dh_p, NULL, &dh_g);
943807
+	hashlen = sizeof(hash);
943807
+	if ((r = kexgex_hash(
943807
+	    kex->hash_alg,
943807
+	    kex->client_version,
943807
+	    kex->server_version,
943807
+	    kex->peer,
943807
+	    kex->my,
943807
+	    empty,
943807
+	    cmin, nbits, cmax,
943807
+	    dh_p, dh_g,
943807
+	    dh_client_pub,
943807
+	    pub_key,
943807
+	    sshbuf_ptr(shared_secret), sshbuf_len(shared_secret),
943807
+	    hash, &hashlen)) != 0)
943807
+		fatal("kexgex_hash failed: %s", ssh_err(r));
943807
+
943807
+	gssbuf.value = hash;
943807
+	gssbuf.length = hashlen;
943807
+
943807
+	if (GSS_ERROR(PRIVSEP(ssh_gssapi_sign(ctxt, &gssbuf, &msg_tok))))
943807
+		fatal("Couldn't get MIC");
943807
+
943807
+	if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_COMPLETE)) != 0 ||
943807
+	    (r = sshpkt_put_bignum2(ssh, pub_key)) != 0 ||
943807
+	    (r = sshpkt_put_string(ssh, msg_tok.value, msg_tok.length)) != 0)
943807
+		fatal("sshpkt failed: %s", ssh_err(r));
943807
+
943807
+	if (send_tok.length != 0) {
943807
+		if ((r = sshpkt_put_u8(ssh, 1)) != 0 || /* true */
943807
+		    (r = sshpkt_put_string(ssh, send_tok.value, send_tok.length)) != 0)
943807
+			fatal("sshpkt failed: %s", ssh_err(r));
943807
+	} else {
943807
+		if ((r = sshpkt_put_u8(ssh, 0)) != 0) /* false */
943807
+			fatal("sshpkt failed: %s", ssh_err(r));
943807
+	}
943807
+	if ((r = sshpkt_send(ssh)) != 0)
943807
+		fatal("sshpkt failed: %s", ssh_err(r));
943807
+
943807
+	gss_release_buffer(&min_status, &send_tok);
943807
+	gss_release_buffer(&min_status, &msg_tok);
943807
+
943807
+	if (gss_kex_context == NULL)
943807
+		gss_kex_context = ctxt;
943807
+	else
943807
+		ssh_gssapi_delete_ctx(&ctxt);
943807
+
943807
+	/* Finally derive the keys and send them */
943807
+	if ((r = kex_derive_keys(ssh, hash, hashlen, shared_secret)) == 0)
943807
+		r = kex_send_newkeys(ssh);
943807
+
943807
+	/* If this was a rekey, then save out any delegated credentials we
943807
+	 * just exchanged.  */
943807
+	if (options.gss_store_rekey)
943807
+		ssh_gssapi_rekey_creds();
943807
+out:
943807
+	sshbuf_free(empty);
943807
+	explicit_bzero(hash, sizeof(hash));
943807
+	DH_free(kex->dh);
943807
+	kex->dh = NULL;
943807
+	BN_clear_free(dh_client_pub);
943807
+	sshbuf_free(shared_secret);
943807
+	return r;
943807
+}
943807
+#endif /* defined(GSSAPI) && defined(WITH_OPENSSL) */
943807
diff --git a/monitor.c b/monitor.c
943807
index 2ce89fe9..ebf76c7f 100644
943807
--- a/monitor.c
943807
+++ b/monitor.c
943807
@@ -148,6 +148,8 @@ int mm_answer_gss_setup_ctx(struct ssh *, int, struct sshbuf *);
943807
 int mm_answer_gss_accept_ctx(struct ssh *, int, struct sshbuf *);
943807
 int mm_answer_gss_userok(struct ssh *, int, struct sshbuf *);
943807
 int mm_answer_gss_checkmic(struct ssh *, int, struct sshbuf *);
943807
+int mm_answer_gss_sign(struct ssh *, int, struct sshbuf *);
943807
+int mm_answer_gss_updatecreds(struct ssh *, int, struct sshbuf *);
943807
 #endif
943807
 
943807
 #ifdef SSH_AUDIT_EVENTS
943807
@@ -220,11 +222,18 @@ struct mon_table mon_dispatch_proto20[] = {
943807
     {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
943807
     {MONITOR_REQ_GSSUSEROK, MON_ONCE|MON_AUTHDECIDE, mm_answer_gss_userok},
943807
     {MONITOR_REQ_GSSCHECKMIC, MON_ONCE, mm_answer_gss_checkmic},
943807
+    {MONITOR_REQ_GSSSIGN, MON_ONCE, mm_answer_gss_sign},
943807
 #endif
943807
     {0, 0, NULL}
943807
 };
943807
 
943807
 struct mon_table mon_dispatch_postauth20[] = {
943807
+#ifdef GSSAPI
943807
+    {MONITOR_REQ_GSSSETUP, 0, mm_answer_gss_setup_ctx},
943807
+    {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
943807
+    {MONITOR_REQ_GSSSIGN, 0, mm_answer_gss_sign},
943807
+    {MONITOR_REQ_GSSUPCREDS, 0, mm_answer_gss_updatecreds},
943807
+#endif
943807
 #ifdef WITH_OPENSSL
943807
     {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
943807
 #endif
943807
@@ -293,6 +302,10 @@ monitor_child_preauth(struct ssh *ssh, struct monitor *pmonitor)
943807
 	/* Permit requests for moduli and signatures */
943807
 	monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
943807
 	monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
943807
+#ifdef GSSAPI
943807
+	/* and for the GSSAPI key exchange */
943807
+	monitor_permit(mon_dispatch, MONITOR_REQ_GSSSETUP, 1);
943807
+#endif
943807
 
943807
 	/* The first few requests do not require asynchronous access */
943807
 	while (!authenticated) {
943807
@@ -406,6 +419,10 @@ monitor_child_postauth(struct ssh *ssh, struct monitor *pmonitor)
943807
 	monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
943807
 	monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
943807
 	monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
943807
+#ifdef GSSAPI
943807
+	/* and for the GSSAPI key exchange */
943807
+	monitor_permit(mon_dispatch, MONITOR_REQ_GSSSETUP, 1);
943807
+#endif
943807
 
943807
 	if (auth_opts->permit_pty_flag) {
943807
 		monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1);
943807
@@ -1713,6 +1730,17 @@ monitor_apply_keystate(struct ssh *ssh, struct monitor *pmonitor)
943807
 # ifdef OPENSSL_HAS_ECC
943807
 	kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
943807
 # endif
943807
+# ifdef GSSAPI
943807
+	if (options.gss_keyex) {
943807
+		kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
943807
+		kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
943807
+		kex->kex[KEX_GSS_GRP14_SHA256] = kexgss_server;
943807
+		kex->kex[KEX_GSS_GRP16_SHA512] = kexgss_server;
943807
+		kex->kex[KEX_GSS_GEX_SHA1] = kexgssgex_server;
943807
+		kex->kex[KEX_GSS_NISTP256_SHA256] = kexgss_server;
943807
+		kex->kex[KEX_GSS_C25519_SHA256] = kexgss_server;
943807
+	}
943807
+# endif
943807
 #endif /* WITH_OPENSSL */
943807
 	kex->kex[KEX_C25519_SHA256] = kex_gen_server;
943807
 	kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
943807
@@ -1806,8 +1834,8 @@ mm_answer_gss_setup_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
943807
 	u_char *p;
943807
 	int r;
943807
 
943807
-	if (!options.gss_authentication)
943807
-		fatal_f("GSSAPI authentication not enabled");
943807
+	if (!options.gss_authentication && !options.gss_keyex)
943807
+		fatal_f("GSSAPI not enabled");
943807
 
943807
 	if ((r = sshbuf_get_string(m, &p, &len)) != 0)
943807
 		fatal_fr(r, "parse");
943807
@@ -1839,8 +1867,8 @@ mm_answer_gss_accept_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
943807
 	OM_uint32 flags = 0; /* GSI needs this */
943807
 	int r;
943807
 
943807
-	if (!options.gss_authentication)
943807
-		fatal_f("GSSAPI authentication not enabled");
943807
+	if (!options.gss_authentication && !options.gss_keyex)
943807
+		fatal_f("GSSAPI not enabled");
943807
 
943807
 	if ((r = ssh_gssapi_get_buffer_desc(m, &in)) != 0)
943807
 		fatal_fr(r, "ssh_gssapi_get_buffer_desc");
943807
@@ -1860,6 +1888,7 @@ mm_answer_gss_accept_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
943807
 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
943807
 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
943807
 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
943807
+		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSIGN, 1);
943807
 	}
943807
 	return (0);
943807
 }
943807
@@ -1871,8 +1900,8 @@ mm_answer_gss_checkmic(struct ssh *ssh, int sock, struct sshbuf *m)
943807
 	OM_uint32 ret;
943807
 	int r;
943807
 
943807
-	if (!options.gss_authentication)
943807
-		fatal_f("GSSAPI authentication not enabled");
943807
+	if (!options.gss_authentication && !options.gss_keyex)
943807
+		fatal_f("GSSAPI not enabled");
943807
 
943807
 	if ((r = ssh_gssapi_get_buffer_desc(m, &gssbuf)) != 0 ||
943807
 	    (r = ssh_gssapi_get_buffer_desc(m, &mic)) != 0)
943807
@@ -1898,13 +1927,17 @@ mm_answer_gss_checkmic(struct ssh *ssh, int sock, struct sshbuf *m)
943807
 int
943807
 mm_answer_gss_userok(struct ssh *ssh, int sock, struct sshbuf *m)
943807
 {
943807
-	int r, authenticated;
943807
+	int r, authenticated, kex;
943807
 	const char *displayname;
943807
 
943807
-	if (!options.gss_authentication)
943807
-		fatal_f("GSSAPI authentication not enabled");
943807
+	if (!options.gss_authentication && !options.gss_keyex)
943807
+		fatal_f("GSSAPI not enabled");
943807
 
943807
-	authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
943807
+	if ((r = sshbuf_get_u32(m, &kex)) != 0)
943807
+		fatal_fr(r, "buffer error");
943807
+
943807
+	authenticated = authctxt->valid &&
943807
+	    ssh_gssapi_userok(authctxt->user, authctxt->pw, kex);
943807
 
943807
 	sshbuf_reset(m);
943807
 	if ((r = sshbuf_put_u32(m, authenticated)) != 0)
943807
@@ -1913,7 +1946,11 @@ mm_answer_gss_userok(struct ssh *ssh, int sock, struct sshbuf *m)
943807
 	debug3_f("sending result %d", authenticated);
943807
 	mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
943807
 
943807
-	auth_method = "gssapi-with-mic";
943807
+	if (kex) {
943807
+		auth_method = "gssapi-keyex";
943807
+	} else {
943807
+		auth_method = "gssapi-with-mic";
943807
+	}
943807
 
943807
 	if ((displayname = ssh_gssapi_displayname()) != NULL)
943807
 		auth2_record_info(authctxt, "%s", displayname);
943807
@@ -1921,5 +1958,84 @@ mm_answer_gss_userok(struct ssh *ssh, int sock, struct sshbuf *m)
943807
 	/* Monitor loop will terminate if authenticated */
943807
 	return (authenticated);
943807
 }
943807
+
943807
+int
943807
+mm_answer_gss_sign(struct ssh *ssh, int socket, struct sshbuf *m)
943807
+{
943807
+	gss_buffer_desc data;
943807
+	gss_buffer_desc hash = GSS_C_EMPTY_BUFFER;
943807
+	OM_uint32 major, minor;
943807
+	size_t len;
943807
+	u_char *p = NULL;
943807
+	int r;
943807
+
943807
+	if (!options.gss_authentication && !options.gss_keyex)
943807
+		fatal_f("GSSAPI not enabled");
943807
+
943807
+	if ((r = sshbuf_get_string(m, &p, &len)) != 0)
943807
+		fatal_fr(r, "buffer error");
943807
+	data.value = p;
943807
+	data.length = len;
943807
+	/* Lengths of SHA-1, SHA-256 and SHA-512 hashes that are used */
943807
+	if (data.length != 20 && data.length != 32 && data.length != 64)
943807
+		fatal_f("data length incorrect: %d", (int) data.length);
943807
+
943807
+	/* Save the session ID on the first time around */
943807
+	if (session_id2_len == 0) {
943807
+		session_id2_len = data.length;
943807
+		session_id2 = xmalloc(session_id2_len);
943807
+		memcpy(session_id2, data.value, session_id2_len);
943807
+	}
943807
+	major = ssh_gssapi_sign(gsscontext, &data, &hash);
943807
+
943807
+	free(data.value);
943807
+
943807
+	sshbuf_reset(m);
943807
+
943807
+	if ((r = sshbuf_put_u32(m, major)) != 0 ||
943807
+	    (r = sshbuf_put_string(m, hash.value, hash.length)) != 0)
943807
+		fatal_fr(r, "buffer error");
943807
+
943807
+	mm_request_send(socket, MONITOR_ANS_GSSSIGN, m);
943807
+
943807
+	gss_release_buffer(&minor, &hash);
943807
+
943807
+	/* Turn on getpwnam permissions */
943807
+	monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
943807
+
943807
+	/* And credential updating, for when rekeying */
943807
+	monitor_permit(mon_dispatch, MONITOR_REQ_GSSUPCREDS, 1);
943807
+
943807
+	return (0);
943807
+}
943807
+
943807
+int
943807
+mm_answer_gss_updatecreds(struct ssh *ssh, int socket, struct sshbuf *m) {
943807
+	ssh_gssapi_ccache store;
943807
+	int r, ok;
943807
+
943807
+	if (!options.gss_authentication && !options.gss_keyex)
943807
+		fatal_f("GSSAPI not enabled");
943807
+
943807
+	if ((r = sshbuf_get_string(m, (u_char **)&store.filename, NULL)) != 0 ||
943807
+	    (r = sshbuf_get_string(m, (u_char **)&store.envvar, NULL)) != 0 ||
943807
+	    (r = sshbuf_get_string(m, (u_char **)&store.envval, NULL)) != 0)
943807
+		fatal_fr(r, "buffer error");
943807
+
943807
+	ok = ssh_gssapi_update_creds(&store);
943807
+
943807
+	free(store.filename);
943807
+	free(store.envvar);
943807
+	free(store.envval);
943807
+
943807
+	sshbuf_reset(m);
943807
+	if ((r = sshbuf_put_u32(m, ok)) != 0)
943807
+		fatal_fr(r, "buffer error");
943807
+
943807
+	mm_request_send(socket, MONITOR_ANS_GSSUPCREDS, m);
943807
+
943807
+	return(0);
943807
+}
943807
+
943807
 #endif /* GSSAPI */
943807
 
943807
diff --git a/monitor.h b/monitor.h
943807
index 683e5e07..2b1a2d59 100644
943807
--- a/monitor.h
943807
+++ b/monitor.h
943807
@@ -63,6 +63,8 @@ enum monitor_reqtype {
943807
 	MONITOR_REQ_PAM_FREE_CTX = 110, MONITOR_ANS_PAM_FREE_CTX = 111,
943807
 	MONITOR_REQ_AUDIT_EVENT = 112, MONITOR_REQ_AUDIT_COMMAND = 113,
943807
 
943807
+	MONITOR_REQ_GSSSIGN = 150, MONITOR_ANS_GSSSIGN = 151,
943807
+	MONITOR_REQ_GSSUPCREDS = 152, MONITOR_ANS_GSSUPCREDS = 153,
943807
 };
943807
 
943807
 struct ssh;
943807
diff --git a/monitor_wrap.c b/monitor_wrap.c
943807
index 001a8fa1..6edb509a 100644
943807
--- a/monitor_wrap.c
943807
+++ b/monitor_wrap.c
943807
@@ -993,13 +993,15 @@ mm_ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
943807
 }
943807
 
943807
 int
943807
-mm_ssh_gssapi_userok(char *user)
943807
+mm_ssh_gssapi_userok(char *user, struct passwd *pw, int kex)
943807
 {
943807
 	struct sshbuf *m;
943807
 	int r, authenticated = 0;
943807
 
943807
 	if ((m = sshbuf_new()) == NULL)
943807
 		fatal_f("sshbuf_new failed");
943807
+	if ((r = sshbuf_put_u32(m, kex)) != 0)
943807
+		fatal_fr(r, "buffer error");
943807
 
943807
 	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSUSEROK, m);
943807
 	mm_request_receive_expect(pmonitor->m_recvfd,
943807
@@ -1012,4 +1014,57 @@ mm_ssh_gssapi_userok(char *user)
943807
 	debug3_f("user %sauthenticated", authenticated ? "" : "not ");
943807
 	return (authenticated);
943807
 }
943807
+
943807
+OM_uint32
943807
+mm_ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_desc *data, gss_buffer_desc *hash)
943807
+{
943807
+	struct sshbuf *m;
943807
+	OM_uint32 major;
943807
+	int r;
943807
+
943807
+	if ((m = sshbuf_new()) == NULL)
943807
+		fatal_f("sshbuf_new failed");
943807
+	if ((r = sshbuf_put_string(m, data->value, data->length)) != 0)
943807
+		fatal_fr(r, "buffer error");
943807
+
943807
+	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSSIGN, m);
943807
+	mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSSIGN, m);
943807
+
943807
+	if ((r = sshbuf_get_u32(m, &major)) != 0 ||
943807
+	    (r = ssh_gssapi_get_buffer_desc(m, hash)) != 0)
943807
+		fatal_fr(r, "buffer error");
943807
+
943807
+	sshbuf_free(m);
943807
+
943807
+	return (major);
943807
+}
943807
+
943807
+int
943807
+mm_ssh_gssapi_update_creds(ssh_gssapi_ccache *store)
943807
+{
943807
+	struct sshbuf *m;
943807
+	int r, ok;
943807
+
943807
+	if ((m = sshbuf_new()) == NULL)
943807
+		fatal_f("sshbuf_new failed");
943807
+
943807
+	if ((r = sshbuf_put_cstring(m,
943807
+	    store->filename ? store->filename : "")) != 0 ||
943807
+	    (r = sshbuf_put_cstring(m,
943807
+	    store->envvar ? store->envvar : "")) != 0 ||
943807
+	    (r = sshbuf_put_cstring(m,
943807
+	    store->envval ? store->envval : "")) != 0)
943807
+		fatal_fr(r, "buffer error");
943807
+
943807
+	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSUPCREDS, m);
943807
+	mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSUPCREDS, m);
943807
+
943807
+	if ((r = sshbuf_get_u32(m, &ok)) != 0)
943807
+		fatal_fr(r, "buffer error");
943807
+
943807
+	sshbuf_free(m);
943807
+
943807
+	return (ok);
943807
+}
943807
+
943807
 #endif /* GSSAPI */
943807
diff --git a/monitor_wrap.h b/monitor_wrap.h
943807
index 23ab096a..485590c1 100644
943807
--- a/monitor_wrap.h
943807
+++ b/monitor_wrap.h
943807
@@ -64,8 +64,10 @@ int mm_sshkey_verify(const struct sshkey *, const u_char *, size_t,
943807
 OM_uint32 mm_ssh_gssapi_server_ctx(Gssctxt **, gss_OID);
943807
 OM_uint32 mm_ssh_gssapi_accept_ctx(Gssctxt *,
943807
    gss_buffer_desc *, gss_buffer_desc *, OM_uint32 *);
943807
-int mm_ssh_gssapi_userok(char *user);
943807
+int mm_ssh_gssapi_userok(char *user, struct passwd *, int kex);
943807
 OM_uint32 mm_ssh_gssapi_checkmic(Gssctxt *, gss_buffer_t, gss_buffer_t);
943807
+OM_uint32 mm_ssh_gssapi_sign(Gssctxt *, gss_buffer_t, gss_buffer_t);
943807
+int mm_ssh_gssapi_update_creds(ssh_gssapi_ccache *);
943807
 #endif
943807
 
943807
 #ifdef USE_PAM
5dbb6f
diff -up a/readconf.c.gsskex b/readconf.c
5dbb6f
--- a/readconf.c.gsskex	2021-08-20 06:03:49.000000000 +0200
5dbb6f
+++ b/readconf.c	2021-08-27 12:25:42.556421509 +0200
943807
@@ -67,6 +67,7 @@
943807
 #include "uidswap.h"
943807
 #include "myproposal.h"
943807
 #include "digest.h"
943807
+#include "ssh-gss.h"
943807
 
943807
 /* Format of the configuration file:
943807
 
5dbb6f
@@ -161,6 +162,8 @@ typedef enum {
943807
 	oClearAllForwardings, oNoHostAuthenticationForLocalhost,
943807
 	oEnableSSHKeysign, oRekeyLimit, oVerifyHostKeyDNS, oConnectTimeout,
943807
 	oAddressFamily, oGssAuthentication, oGssDelegateCreds,
943807
+	oGssTrustDns, oGssKeyEx, oGssClientIdentity, oGssRenewalRekey,
943807
+	oGssServerIdentity, oGssKexAlgorithms,
943807
 	oServerAliveInterval, oServerAliveCountMax, oIdentitiesOnly,
943807
 	oSendEnv, oSetEnv, oControlPath, oControlMaster, oControlPersist,
943807
 	oHashKnownHosts,
5dbb6f
@@ -206,10 +209,22 @@ static struct {
943807
 	/* Sometimes-unsupported options */
943807
 #if defined(GSSAPI)
943807
 	{ "gssapiauthentication", oGssAuthentication },
943807
+	{ "gssapikeyexchange", oGssKeyEx },
943807
 	{ "gssapidelegatecredentials", oGssDelegateCreds },
943807
+	{ "gssapitrustdns", oGssTrustDns },
943807
+	{ "gssapiclientidentity", oGssClientIdentity },
943807
+	{ "gssapiserveridentity", oGssServerIdentity },
943807
+	{ "gssapirenewalforcesrekey", oGssRenewalRekey },
943807
+	{ "gssapikexalgorithms", oGssKexAlgorithms },
943807
 # else
943807
 	{ "gssapiauthentication", oUnsupported },
943807
+	{ "gssapikeyexchange", oUnsupported },
943807
 	{ "gssapidelegatecredentials", oUnsupported },
943807
+	{ "gssapitrustdns", oUnsupported },
943807
+	{ "gssapiclientidentity", oUnsupported },
943807
+	{ "gssapiserveridentity", oUnsupported },
943807
+	{ "gssapirenewalforcesrekey", oUnsupported },
943807
+	{ "gssapikexalgorithms", oUnsupported },
943807
 #endif
943807
 #ifdef ENABLE_PKCS11
943807
 	{ "pkcs11provider", oPKCS11Provider },
5dbb6f
@@ -1113,10 +1128,42 @@ parse_time:
943807
 		intptr = &options->gss_authentication;
943807
 		goto parse_flag;
943807
 
943807
+	case oGssKeyEx:
943807
+		intptr = &options->gss_keyex;
943807
+		goto parse_flag;
943807
+
943807
 	case oGssDelegateCreds:
943807
 		intptr = &options->gss_deleg_creds;
943807
 		goto parse_flag;
943807
 
943807
+	case oGssTrustDns:
943807
+		intptr = &options->gss_trust_dns;
943807
+		goto parse_flag;
943807
+
943807
+	case oGssClientIdentity:
943807
+		charptr = &options->gss_client_identity;
943807
+		goto parse_string;
943807
+
943807
+	case oGssServerIdentity:
943807
+		charptr = &options->gss_server_identity;
943807
+		goto parse_string;
943807
+
943807
+	case oGssRenewalRekey:
943807
+		intptr = &options->gss_renewal_rekey;
943807
+		goto parse_flag;
943807
+
943807
+	case oGssKexAlgorithms:
5dbb6f
+		arg = argv_next(&ac, &av;;
943807
+		if (!arg || *arg == '\0')
943807
+			fatal("%.200s line %d: Missing argument.",
943807
+			    filename, linenum);
943807
+		if (!kex_gss_names_valid(arg))
943807
+			fatal("%.200s line %d: Bad GSSAPI KexAlgorithms '%s'.",
943807
+			    filename, linenum, arg ? arg : "<NONE>");
943807
+		if (*activep && options->gss_kex_algorithms == NULL)
943807
+			options->gss_kex_algorithms = xstrdup(arg);
943807
+		break;
943807
+
943807
 	case oBatchMode:
943807
 		intptr = &options->batch_mode;
943807
 		goto parse_flag;
5dbb6f
@@ -2306,7 +2353,13 @@ initialize_options(Options * options)
5dbb6f
 	options->fwd_opts.streamlocal_bind_unlink = -1;
943807
 	options->pubkey_authentication = -1;
943807
 	options->gss_authentication = -1;
943807
+	options->gss_keyex = -1;
943807
 	options->gss_deleg_creds = -1;
943807
+	options->gss_trust_dns = -1;
943807
+	options->gss_renewal_rekey = -1;
943807
+	options->gss_client_identity = NULL;
943807
+	options->gss_server_identity = NULL;
943807
+	options->gss_kex_algorithms = NULL;
943807
 	options->password_authentication = -1;
943807
 	options->kbd_interactive_authentication = -1;
943807
 	options->kbd_interactive_devices = NULL;
5dbb6f
@@ -2463,8 +2516,18 @@ fill_default_options(Options * options)
5dbb6f
 		options->pubkey_authentication = 1;
943807
 	if (options->gss_authentication == -1)
943807
 		options->gss_authentication = 0;
943807
+	if (options->gss_keyex == -1)
943807
+		options->gss_keyex = 0;
943807
 	if (options->gss_deleg_creds == -1)
943807
 		options->gss_deleg_creds = 0;
943807
+	if (options->gss_trust_dns == -1)
943807
+		options->gss_trust_dns = 0;
943807
+	if (options->gss_renewal_rekey == -1)
943807
+		options->gss_renewal_rekey = 0;
943807
+#ifdef GSSAPI
943807
+	if (options->gss_kex_algorithms == NULL)
943807
+		options->gss_kex_algorithms = strdup(GSS_KEX_DEFAULT_KEX);
943807
+#endif
943807
 	if (options->password_authentication == -1)
943807
 		options->password_authentication = 1;
943807
 	if (options->kbd_interactive_authentication == -1)
5dbb6f
@@ -3246,7 +3309,14 @@ dump_client_config(Options *o, const cha
943807
 	dump_cfg_fmtint(oGatewayPorts, o->fwd_opts.gateway_ports);
943807
 #ifdef GSSAPI
943807
 	dump_cfg_fmtint(oGssAuthentication, o->gss_authentication);
943807
+	dump_cfg_fmtint(oGssKeyEx, o->gss_keyex);
943807
 	dump_cfg_fmtint(oGssDelegateCreds, o->gss_deleg_creds);
943807
+	dump_cfg_fmtint(oGssTrustDns, o->gss_trust_dns);
943807
+	dump_cfg_fmtint(oGssRenewalRekey, o->gss_renewal_rekey);
943807
+	dump_cfg_string(oGssClientIdentity, o->gss_client_identity);
943807
+	dump_cfg_string(oGssServerIdentity, o->gss_server_identity);
943807
+	dump_cfg_string(oGssKexAlgorithms, o->gss_kex_algorithms ?
943807
+	    o->gss_kex_algorithms : GSS_KEX_DEFAULT_KEX);
943807
 #endif /* GSSAPI */
943807
 	dump_cfg_fmtint(oHashKnownHosts, o->hash_known_hosts);
943807
 	dump_cfg_fmtint(oHostbasedAuthentication, o->hostbased_authentication);
5dbb6f
diff -up a/readconf.h.gsskex b/readconf.h
5dbb6f
--- a/readconf.h.gsskex	2021-08-27 12:05:29.248142431 +0200
5dbb6f
+++ b/readconf.h	2021-08-27 12:22:19.270679852 +0200
5dbb6f
@@ -39,7 +39,13 @@ typedef struct {
5dbb6f
 	int     pubkey_authentication;	/* Try ssh2 pubkey authentication. */
5dbb6f
 	int     hostbased_authentication;	/* ssh2's rhosts_rsa */
943807
 	int     gss_authentication;	/* Try GSS authentication */
943807
+	int     gss_keyex;		/* Try GSS key exchange */
943807
 	int     gss_deleg_creds;	/* Delegate GSS credentials */
943807
+	int	gss_trust_dns;		/* Trust DNS for GSS canonicalization */
943807
+	int	gss_renewal_rekey;	/* Credential renewal forces rekey */
943807
+	char    *gss_client_identity;   /* Principal to initiate GSSAPI with */
943807
+	char    *gss_server_identity;   /* GSSAPI target principal */
943807
+	char    *gss_kex_algorithms;	/* GSSAPI kex methods to be offered by client. */
943807
 	int     password_authentication;	/* Try password
943807
 						 * authentication. */
943807
 	int     kbd_interactive_authentication; /* Try keyboard-interactive auth. */
5dbb6f
diff -up a/servconf.c.gsskex b/servconf.c
5dbb6f
--- a/servconf.c.gsskex	2021-08-20 06:03:49.000000000 +0200
5dbb6f
+++ b/servconf.c	2021-08-27 12:28:15.887735189 +0200
5dbb6f
@@ -70,6 +70,7 @@
943807
 #include "auth.h"
943807
 #include "myproposal.h"
943807
 #include "digest.h"
943807
+#include "ssh-gss.h"
943807
 
943807
 static void add_listen_addr(ServerOptions *, const char *,
943807
     const char *, int);
5dbb6f
@@ -136,8 +137,11 @@ initialize_server_options(ServerOptions
943807
 	options->kerberos_ticket_cleanup = -1;
943807
 	options->kerberos_get_afs_token = -1;
943807
 	options->gss_authentication=-1;
943807
+	options->gss_keyex = -1;
943807
 	options->gss_cleanup_creds = -1;
943807
 	options->gss_strict_acceptor = -1;
943807
+	options->gss_store_rekey = -1;
943807
+	options->gss_kex_algorithms = NULL;
943807
 	options->password_authentication = -1;
943807
 	options->kbd_interactive_authentication = -1;
5dbb6f
 	options->permit_empty_passwd = -1;
5dbb6f
@@ -356,10 +360,18 @@ fill_default_server_options(ServerOption
943807
 		options->kerberos_get_afs_token = 0;
943807
 	if (options->gss_authentication == -1)
943807
 		options->gss_authentication = 0;
943807
+	if (options->gss_keyex == -1)
943807
+		options->gss_keyex = 0;
943807
 	if (options->gss_cleanup_creds == -1)
943807
 		options->gss_cleanup_creds = 1;
943807
 	if (options->gss_strict_acceptor == -1)
943807
 		options->gss_strict_acceptor = 1;
943807
+	if (options->gss_store_rekey == -1)
943807
+		options->gss_store_rekey = 0;
943807
+#ifdef GSSAPI
943807
+	if (options->gss_kex_algorithms == NULL)
943807
+		options->gss_kex_algorithms = strdup(GSS_KEX_DEFAULT_KEX);
943807
+#endif
943807
 	if (options->password_authentication == -1)
943807
 		options->password_authentication = 1;
943807
 	if (options->kbd_interactive_authentication == -1)
5dbb6f
@@ -506,6 +518,7 @@ typedef enum {
943807
 	sHostKeyAlgorithms, sPerSourceMaxStartups, sPerSourceNetBlockSize,
943807
 	sClientAliveInterval, sClientAliveCountMax, sAuthorizedKeysFile,
943807
 	sGssAuthentication, sGssCleanupCreds, sGssStrictAcceptor,
943807
+	sGssKeyEx, sGssKexAlgorithms, sGssStoreRekey,
943807
 	sAcceptEnv, sSetEnv, sPermitTunnel,
943807
 	sMatch, sPermitOpen, sPermitListen, sForceCommand, sChrootDirectory,
943807
 	sUsePrivilegeSeparation, sAllowAgentForwarding,
5dbb6f
@@ -587,12 +600,22 @@ static struct {
943807
 #ifdef GSSAPI
943807
 	{ "gssapiauthentication", sGssAuthentication, SSHCFG_ALL },
943807
 	{ "gssapicleanupcredentials", sGssCleanupCreds, SSHCFG_GLOBAL },
943807
+	{ "gssapicleanupcreds", sGssCleanupCreds, SSHCFG_GLOBAL },
943807
 	{ "gssapistrictacceptorcheck", sGssStrictAcceptor, SSHCFG_GLOBAL },
943807
+	{ "gssapikeyexchange", sGssKeyEx, SSHCFG_GLOBAL },
943807
+	{ "gssapistorecredentialsonrekey", sGssStoreRekey, SSHCFG_GLOBAL },
943807
+	{ "gssapikexalgorithms", sGssKexAlgorithms, SSHCFG_GLOBAL },
943807
 #else
943807
 	{ "gssapiauthentication", sUnsupported, SSHCFG_ALL },
943807
 	{ "gssapicleanupcredentials", sUnsupported, SSHCFG_GLOBAL },
943807
+	{ "gssapicleanupcreds", sUnsupported, SSHCFG_GLOBAL },
943807
 	{ "gssapistrictacceptorcheck", sUnsupported, SSHCFG_GLOBAL },
943807
+	{ "gssapikeyexchange", sUnsupported, SSHCFG_GLOBAL },
943807
+	{ "gssapistorecredentialsonrekey", sUnsupported, SSHCFG_GLOBAL },
943807
+	{ "gssapikexalgorithms", sUnsupported, SSHCFG_GLOBAL },
943807
 #endif
943807
+	{ "gssusesessionccache", sUnsupported, SSHCFG_GLOBAL },
943807
+	{ "gssapiusesessioncredcache", sUnsupported, SSHCFG_GLOBAL },
943807
 	{ "passwordauthentication", sPasswordAuthentication, SSHCFG_ALL },
943807
 	{ "kbdinteractiveauthentication", sKbdInteractiveAuthentication, SSHCFG_ALL },
5dbb6f
 	{ "challengeresponseauthentication", sKbdInteractiveAuthentication, SSHCFG_ALL }, /* alias */
5dbb6f
@@ -1576,6 +1599,10 @@ process_server_config_line_depth(ServerO
943807
 		intptr = &options->gss_authentication;
943807
 		goto parse_flag;
943807
 
943807
+	case sGssKeyEx:
943807
+		intptr = &options->gss_keyex;
943807
+		goto parse_flag;
943807
+
943807
 	case sGssCleanupCreds:
943807
 		intptr = &options->gss_cleanup_creds;
943807
 		goto parse_flag;
5dbb6f
@@ -1584,6 +1611,22 @@ process_server_config_line_depth(ServerO
943807
 		intptr = &options->gss_strict_acceptor;
943807
 		goto parse_flag;
943807
 
943807
+	case sGssStoreRekey:
943807
+		intptr = &options->gss_store_rekey;
943807
+		goto parse_flag;
943807
+
943807
+	case sGssKexAlgorithms:
5dbb6f
+		arg = argv_next(&ac, &av;;
943807
+		if (!arg || *arg == '\0')
943807
+			fatal("%.200s line %d: Missing argument.",
943807
+			    filename, linenum);
943807
+		if (!kex_gss_names_valid(arg))
943807
+			fatal("%.200s line %d: Bad GSSAPI KexAlgorithms '%s'.",
943807
+			    filename, linenum, arg ? arg : "<NONE>");
943807
+		if (*activep && options->gss_kex_algorithms == NULL)
943807
+			options->gss_kex_algorithms = xstrdup(arg);
943807
+		break;
943807
+
943807
 	case sPasswordAuthentication:
943807
 		intptr = &options->password_authentication;
943807
 		goto parse_flag;
5dbb6f
@@ -2892,6 +2935,10 @@ dump_config(ServerOptions *o)
943807
 #ifdef GSSAPI
943807
 	dump_cfg_fmtint(sGssAuthentication, o->gss_authentication);
943807
 	dump_cfg_fmtint(sGssCleanupCreds, o->gss_cleanup_creds);
943807
+	dump_cfg_fmtint(sGssKeyEx, o->gss_keyex);
943807
+	dump_cfg_fmtint(sGssStrictAcceptor, o->gss_strict_acceptor);
943807
+	dump_cfg_fmtint(sGssStoreRekey, o->gss_store_rekey);
943807
+	dump_cfg_string(sGssKexAlgorithms, o->gss_kex_algorithms);
943807
 #endif
943807
 	dump_cfg_fmtint(sPasswordAuthentication, o->password_authentication);
943807
 	dump_cfg_fmtint(sKbdInteractiveAuthentication,
943807
diff --git a/servconf.h b/servconf.h
943807
index 4202a2d0..3f47ea25 100644
943807
--- a/servconf.h
943807
+++ b/servconf.h
943807
@@ -132,8 +132,11 @@ typedef struct {
943807
 	int     kerberos_get_afs_token;		/* If true, try to get AFS token if
943807
 						 * authenticated with Kerberos. */
943807
 	int     gss_authentication;	/* If true, permit GSSAPI authentication */
943807
+	int     gss_keyex;		/* If true, permit GSSAPI key exchange */
943807
 	int     gss_cleanup_creds;	/* If true, destroy cred cache on logout */
943807
 	int     gss_strict_acceptor;	/* If true, restrict the GSSAPI acceptor name */
943807
+	int 	gss_store_rekey;
943807
+	char   *gss_kex_algorithms;	/* GSSAPI kex methods to be offered by client. */
943807
 	int     password_authentication;	/* If true, permit password
943807
 						 * authentication. */
943807
 	int     kbd_interactive_authentication;	/* If true, permit */
943807
diff --git a/session.c b/session.c
943807
index 8c0e54f7..06a33442 100644
943807
--- a/session.c
943807
+++ b/session.c
943807
@@ -2678,13 +2678,19 @@ do_cleanup(struct ssh *ssh, Authctxt *authctxt)
943807
 
943807
 #ifdef KRB5
943807
 	if (options.kerberos_ticket_cleanup &&
943807
-	    authctxt->krb5_ctx)
943807
+	    authctxt->krb5_ctx) {
943807
+		temporarily_use_uid(authctxt->pw);
943807
 		krb5_cleanup_proc(authctxt);
943807
+		restore_uid();
943807
+	}
943807
 #endif
943807
 
943807
 #ifdef GSSAPI
943807
-	if (options.gss_cleanup_creds)
943807
+	if (options.gss_cleanup_creds) {
943807
+		temporarily_use_uid(authctxt->pw);
943807
 		ssh_gssapi_cleanup_creds();
943807
+		restore_uid();
943807
+	}
943807
 #endif
943807
 
943807
 	/* remove agent socket */
943807
diff --git a/ssh-gss.h b/ssh-gss.h
943807
index 36180d07..70dd3665 100644
943807
--- a/ssh-gss.h
943807
+++ b/ssh-gss.h
943807
@@ -1,6 +1,6 @@
943807
 /* $OpenBSD: ssh-gss.h,v 1.15 2021/01/27 10:05:28 djm Exp $ */
943807
 /*
943807
- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
943807
+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
943807
  *
943807
  * Redistribution and use in source and binary forms, with or without
943807
  * modification, are permitted provided that the following conditions
943807
@@ -61,10 +61,34 @@
943807
 
943807
 #define SSH_GSS_OIDTYPE 0x06
943807
 
943807
+#define SSH2_MSG_KEXGSS_INIT                            30
943807
+#define SSH2_MSG_KEXGSS_CONTINUE                        31
943807
+#define SSH2_MSG_KEXGSS_COMPLETE                        32
943807
+#define SSH2_MSG_KEXGSS_HOSTKEY                         33
943807
+#define SSH2_MSG_KEXGSS_ERROR                           34
943807
+#define SSH2_MSG_KEXGSS_GROUPREQ			40
943807
+#define SSH2_MSG_KEXGSS_GROUP				41
943807
+#define KEX_GSS_GRP1_SHA1_ID				"gss-group1-sha1-"
943807
+#define KEX_GSS_GRP14_SHA1_ID				"gss-group14-sha1-"
943807
+#define KEX_GSS_GRP14_SHA256_ID			"gss-group14-sha256-"
943807
+#define KEX_GSS_GRP16_SHA512_ID			"gss-group16-sha512-"
943807
+#define KEX_GSS_GEX_SHA1_ID				"gss-gex-sha1-"
943807
+#define KEX_GSS_NISTP256_SHA256_ID			"gss-nistp256-sha256-"
943807
+#define KEX_GSS_C25519_SHA256_ID			"gss-curve25519-sha256-"
943807
+
943807
+#define        GSS_KEX_DEFAULT_KEX \
943807
+	KEX_GSS_GRP14_SHA256_ID "," \
943807
+	KEX_GSS_GRP16_SHA512_ID	"," \
943807
+	KEX_GSS_NISTP256_SHA256_ID "," \
943807
+	KEX_GSS_C25519_SHA256_ID "," \
943807
+	KEX_GSS_GRP14_SHA1_ID "," \
943807
+	KEX_GSS_GEX_SHA1_ID
943807
+
943807
 typedef struct {
943807
 	char *filename;
943807
 	char *envvar;
943807
 	char *envval;
943807
+	struct passwd *owner;
943807
 	void *data;
943807
 } ssh_gssapi_ccache;
943807
 
943807
@@ -72,8 +92,11 @@ typedef struct {
943807
 	gss_buffer_desc displayname;
943807
 	gss_buffer_desc exportedname;
943807
 	gss_cred_id_t creds;
943807
+	gss_name_t name;
943807
 	struct ssh_gssapi_mech_struct *mech;
943807
 	ssh_gssapi_ccache store;
943807
+	int used;
943807
+	int updated;
943807
 } ssh_gssapi_client;
943807
 
943807
 typedef struct ssh_gssapi_mech_struct {
943807
@@ -84,6 +107,7 @@ typedef struct ssh_gssapi_mech_struct {
943807
 	int (*userok) (ssh_gssapi_client *, char *);
943807
 	int (*localname) (ssh_gssapi_client *, char **);
943807
 	void (*storecreds) (ssh_gssapi_client *);
943807
+	int (*updatecreds) (ssh_gssapi_ccache *, ssh_gssapi_client *);
943807
 } ssh_gssapi_mech;
943807
 
943807
 typedef struct {
943807
@@ -94,10 +118,11 @@ typedef struct {
943807
 	gss_OID		oid; /* client */
943807
 	gss_cred_id_t	creds; /* server */
943807
 	gss_name_t	client; /* server */
943807
-	gss_cred_id_t	client_creds; /* server */
943807
+	gss_cred_id_t	client_creds; /* both */
943807
 } Gssctxt;
943807
 
943807
 extern ssh_gssapi_mech *supported_mechs[];
943807
+extern Gssctxt *gss_kex_context;
943807
 
943807
 int  ssh_gssapi_check_oid(Gssctxt *, void *, size_t);
943807
 void ssh_gssapi_set_oid_data(Gssctxt *, void *, size_t);
943807
@@ -109,6 +134,7 @@ OM_uint32 ssh_gssapi_test_oid_supported(OM_uint32 *, gss_OID, int *);
943807
 
943807
 struct sshbuf;
943807
 int ssh_gssapi_get_buffer_desc(struct sshbuf *, gss_buffer_desc *);
943807
+int ssh_gssapi_sshpkt_get_buffer_desc(struct ssh *, gss_buffer_desc *);
943807
 
943807
 OM_uint32 ssh_gssapi_import_name(Gssctxt *, const char *);
943807
 OM_uint32 ssh_gssapi_init_ctx(Gssctxt *, int,
943807
@@ -123,17 +149,33 @@ void ssh_gssapi_delete_ctx(Gssctxt **);
943807
 OM_uint32 ssh_gssapi_sign(Gssctxt *, gss_buffer_t, gss_buffer_t);
943807
 void ssh_gssapi_buildmic(struct sshbuf *, const char *,
943807
     const char *, const char *, const struct sshbuf *);
943807
-int ssh_gssapi_check_mechanism(Gssctxt **, gss_OID, const char *);
943807
+int ssh_gssapi_check_mechanism(Gssctxt **, gss_OID, const char *, const char *);
943807
+OM_uint32 ssh_gssapi_client_identity(Gssctxt *, const char *);
943807
+int ssh_gssapi_credentials_updated(Gssctxt *);
943807
 
943807
 /* In the server */
943807
+typedef int ssh_gssapi_check_fn(Gssctxt **, gss_OID, const char *,
943807
+    const char *);
943807
+char *ssh_gssapi_client_mechanisms(const char *, const char *, const char *);
943807
+char *ssh_gssapi_kex_mechs(gss_OID_set, ssh_gssapi_check_fn *, const char *,
943807
+    const char *, const char *);
943807
+gss_OID ssh_gssapi_id_kex(Gssctxt *, char *, int);
943807
+int ssh_gssapi_server_check_mech(Gssctxt **,gss_OID, const char *,
943807
+    const char *);
943807
 OM_uint32 ssh_gssapi_server_ctx(Gssctxt **, gss_OID);
943807
-int ssh_gssapi_userok(char *name);
943807
+int ssh_gssapi_userok(char *name, struct passwd *, int kex);
943807
 OM_uint32 ssh_gssapi_checkmic(Gssctxt *, gss_buffer_t, gss_buffer_t);
943807
 void ssh_gssapi_do_child(char ***, u_int *);
943807
 void ssh_gssapi_cleanup_creds(void);
943807
 void ssh_gssapi_storecreds(void);
943807
 const char *ssh_gssapi_displayname(void);
943807
 
943807
+char *ssh_gssapi_server_mechanisms(void);
943807
+int ssh_gssapi_oid_table_ok(void);
943807
+
943807
+int ssh_gssapi_update_creds(ssh_gssapi_ccache *store);
943807
+void ssh_gssapi_rekey_creds(void);
943807
+
943807
 #endif /* GSSAPI */
943807
 
943807
 #endif /* _SSH_GSS_H */
943807
diff --git a/ssh.1 b/ssh.1
943807
index 60de6087..db5c65bc 100644
943807
--- a/ssh.1
943807
+++ b/ssh.1
943807
@@ -503,7 +503,13 @@ For full details of the options listed below, and their possible values, see
943807
 .It GatewayPorts
943807
 .It GlobalKnownHostsFile
943807
 .It GSSAPIAuthentication
943807
+.It GSSAPIKeyExchange
943807
+.It GSSAPIClientIdentity
943807
 .It GSSAPIDelegateCredentials
943807
+.It GSSAPIKexAlgorithms
943807
+.It GSSAPIRenewalForcesRekey
943807
+.It GSSAPIServerIdentity
943807
+.It GSSAPITrustDns
943807
 .It HashKnownHosts
943807
 .It Host
943807
 .It HostbasedAcceptedAlgorithms
943807
@@ -579,6 +585,8 @@ flag),
943807
 (supported message integrity codes),
943807
 .Ar kex
943807
 (key exchange algorithms),
943807
+.Ar kex-gss
943807
+(GSSAPI key exchange algorithms),
943807
 .Ar key
943807
 (key types),
943807
 .Ar key-cert
943807
diff --git a/ssh.c b/ssh.c
943807
index 15aee569..110cf9c1 100644
943807
--- a/ssh.c
943807
+++ b/ssh.c
943807
@@ -747,6 +747,8 @@ main(int ac, char **av)
943807
 			else if (strcmp(optarg, "kex") == 0 ||
943807
 			    strcasecmp(optarg, "KexAlgorithms") == 0)
943807
 				cp = kex_alg_list('\n');
943807
+			else if (strcmp(optarg, "kex-gss") == 0)
943807
+				cp = kex_gss_alg_list('\n');
943807
 			else if (strcmp(optarg, "key") == 0)
943807
 				cp = sshkey_alg_list(0, 0, 0, '\n');
943807
 			else if (strcmp(optarg, "key-cert") == 0)
943807
@@ -772,8 +774,8 @@ main(int ac, char **av)
943807
 			} else if (strcmp(optarg, "help") == 0) {
943807
 				cp = xstrdup(
943807
 				    "cipher\ncipher-auth\ncompression\nkex\n"
943807
-				    "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
943807
-				    "protocol-version\nsig");
943807
+				    "kex-gss\nkey\nkey-cert\nkey-plain\n"
943807
+				    "key-sig\nmac\nprotocol-version\nsig");
943807
 			}
943807
 			if (cp == NULL)
943807
 				fatal("Unsupported query \"%s\"", optarg);
943807
diff --git a/ssh_config b/ssh_config
943807
index 5e8ef548..1ff999b6 100644
943807
--- a/ssh_config
943807
+++ b/ssh_config
943807
@@ -24,6 +24,8 @@
943807
 #   HostbasedAuthentication no
943807
 #   GSSAPIAuthentication no
943807
 #   GSSAPIDelegateCredentials no
943807
+#   GSSAPIKeyExchange no
943807
+#   GSSAPITrustDNS no
943807
 #   BatchMode no
943807
 #   CheckHostIP yes
943807
 #   AddressFamily any
943807
diff --git a/ssh_config.5 b/ssh_config.5
943807
index 06a32d31..3f490697 100644
943807
--- a/ssh_config.5
943807
+++ b/ssh_config.5
943807
@@ -766,10 +766,68 @@ The default is
943807
 Specifies whether user authentication based on GSSAPI is allowed.
943807
 The default is
943807
 .Cm no .
943807
+.It Cm GSSAPIClientIdentity
943807
+If set, specifies the GSSAPI client identity that ssh should use when
943807
+connecting to the server. The default is unset, which means that the default
943807
+identity will be used.
943807
 .It Cm GSSAPIDelegateCredentials
943807
 Forward (delegate) credentials to the server.
943807
 The default is
943807
 .Cm no .
943807
+.It Cm GSSAPIKeyExchange
943807
+Specifies whether key exchange based on GSSAPI may be used. When using
943807
+GSSAPI key exchange the server need not have a host key.
943807
+The default is
943807
+.Dq no .
943807
+.It Cm GSSAPIRenewalForcesRekey
943807
+If set to
943807
+.Dq yes
943807
+then renewal of the client's GSSAPI credentials will force the rekeying of the
943807
+ssh connection. With a compatible server, this will delegate the renewed
943807
+credentials to a session on the server.
943807
+.Pp
943807
+Checks are made to ensure that credentials are only propagated when the new
943807
+credentials match the old ones on the originating client and where the
943807
+receiving server still has the old set in its cache.
943807
+.Pp
943807
+The default is
943807
+.Dq no .
943807
+.Pp
943807
+For this to work
943807
+.Cm GSSAPIKeyExchange
943807
+needs to be enabled in the server and also used by the client.
943807
+.It Cm GSSAPIServerIdentity
943807
+If set, specifies the GSSAPI server identity that ssh should expect when
943807
+connecting to the server. The default is unset, which means that the
943807
+expected GSSAPI server identity will be determined from the target
943807
+hostname.
943807
+.It Cm GSSAPITrustDns
943807
+Set to
943807
+.Dq yes
943807
+to indicate that the DNS is trusted to securely canonicalize
943807
+the name of the host being connected to. If
943807
+.Dq no ,
943807
+the hostname entered on the
943807
+command line will be passed untouched to the GSSAPI library.
943807
+The default is
943807
+.Dq no .
943807
+.It Cm GSSAPIKexAlgorithms
943807
+The list of key exchange algorithms that are offered for GSSAPI
943807
+key exchange. Possible values are
943807
+.Bd -literal -offset 3n
943807
+gss-gex-sha1-,
943807
+gss-group1-sha1-,
943807
+gss-group14-sha1-,
943807
+gss-group14-sha256-,
943807
+gss-group16-sha512-,
943807
+gss-nistp256-sha256-,
943807
+gss-curve25519-sha256-
943807
+.Ed
943807
+.Pp
943807
+The default is
943807
+.Dq gss-group14-sha256-,gss-group16-sha512-,gss-nistp256-sha256-,
943807
+gss-curve25519-sha256-,gss-group14-sha1-,gss-gex-sha1- .
943807
+This option only applies to connections using GSSAPI.
943807
 .It Cm HashKnownHosts
943807
 Indicates that
943807
 .Xr ssh 1
943807
diff --git a/sshconnect2.c b/sshconnect2.c
943807
index af00fb30..03bc87eb 100644
943807
--- a/sshconnect2.c
943807
+++ b/sshconnect2.c
943807
@@ -80,8 +80,6 @@
943807
 #endif
943807
 
943807
 /* import */
943807
-extern char *client_version_string;
943807
-extern char *server_version_string;
943807
 extern Options options;
943807
 
943807
 /*
943807
@@ -163,6 +161,11 @@ ssh_kex2(struct ssh *ssh, char *host, struct sockaddr *hostaddr, u_short port)
943807
 	char *s, *all_key;
943807
 	int r, use_known_hosts_order = 0;
943807
 
943807
+#if defined(GSSAPI) && defined(WITH_OPENSSL)
943807
+	char *orig = NULL, *gss = NULL;
943807
+	char *gss_host = NULL;
943807
+#endif
943807
+
943807
 	xxx_host = host;
943807
 	xxx_hostaddr = hostaddr;
943807
 	xxx_conn_info = cinfo;
943807
@@ -206,6 +209,42 @@ ssh_kex2(struct ssh *ssh, char *host, struct sockaddr *hostaddr, u_short port)
943807
 		    compat_pkalg_proposal(ssh, options.hostkeyalgorithms);
943807
 	}
943807
 
943807
+#if defined(GSSAPI) && defined(WITH_OPENSSL)
943807
+	if (options.gss_keyex) {
943807
+		/* Add the GSSAPI mechanisms currently supported on this
943807
+		 * client to the key exchange algorithm proposal */
943807
+		orig = myproposal[PROPOSAL_KEX_ALGS];
943807
+
943807
+		if (options.gss_server_identity) {
943807
+			gss_host = xstrdup(options.gss_server_identity);
943807
+		} else if (options.gss_trust_dns) {
943807
+			gss_host = remote_hostname(ssh);
943807
+			/* Fall back to specified host if we are using proxy command
943807
+			 * and can not use DNS on that socket */
943807
+			if (strcmp(gss_host, "UNKNOWN") == 0) {
943807
+				free(gss_host);
943807
+				gss_host = xstrdup(host);
943807
+			}
943807
+		} else {
943807
+			gss_host = xstrdup(host);
943807
+		}
943807
+
943807
+		gss = ssh_gssapi_client_mechanisms(gss_host,
943807
+		    options.gss_client_identity, options.gss_kex_algorithms);
943807
+		if (gss) {
943807
+			debug("Offering GSSAPI proposal: %s", gss);
943807
+			xasprintf(&myproposal[PROPOSAL_KEX_ALGS],
943807
+			    "%s,%s", gss, orig);
943807
+
943807
+			/* If we've got GSSAPI algorithms, then we also support the
943807
+			 * 'null' hostkey, as a last resort */
943807
+			orig = myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS];
943807
+			xasprintf(&myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS],
943807
+			    "%s,null", orig);
943807
+		}
943807
+	}
943807
+#endif
943807
+
943807
 	if (options.rekey_limit || options.rekey_interval)
943807
 		ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
943807
 		    options.rekey_interval);
943807
@@ -224,16 +256,46 @@ ssh_kex2(struct ssh *ssh, char *host, struct sockaddr *hostaddr, u_short port)
943807
 # ifdef OPENSSL_HAS_ECC
943807
 	ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
943807
 # endif
943807
-#endif
943807
+# ifdef GSSAPI
943807
+	if (options.gss_keyex) {
943807
+		ssh->kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_client;
943807
+		ssh->kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_client;
943807
+		ssh->kex->kex[KEX_GSS_GRP14_SHA256] = kexgss_client;
943807
+		ssh->kex->kex[KEX_GSS_GRP16_SHA512] = kexgss_client;
943807
+		ssh->kex->kex[KEX_GSS_GEX_SHA1] = kexgssgex_client;
943807
+		ssh->kex->kex[KEX_GSS_NISTP256_SHA256] = kexgss_client;
943807
+		ssh->kex->kex[KEX_GSS_C25519_SHA256] = kexgss_client;
943807
+	}
943807
+# endif
943807
+#endif /* WITH_OPENSSL */
943807
 	ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
943807
	ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
943807
 	ssh->kex->verify_host_key=&verify_host_key_callback;
943807
 
943807
+#if defined(GSSAPI) && defined(WITH_OPENSSL)
943807
+	if (options.gss_keyex) {
943807
+		ssh->kex->gss_deleg_creds = options.gss_deleg_creds;
943807
+		ssh->kex->gss_trust_dns = options.gss_trust_dns;
943807
+		ssh->kex->gss_client = options.gss_client_identity;
943807
+		ssh->kex->gss_host = gss_host;
943807
+	}
943807
+#endif
943807
+
943807
 	ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &ssh->kex->done);
943807
 
943807
 	/* remove ext-info from the KEX proposals for rekeying */
943807
 	myproposal[PROPOSAL_KEX_ALGS] =
943807
 	    compat_kex_proposal(ssh, options.kex_algorithms);
943807
+#if defined(GSSAPI) && defined(WITH_OPENSSL)
943807
+	/* repair myproposal after it was crumpled by the */
943807
+	/* ext-info removal above */
943807
+	if (gss) {
943807
+		orig = myproposal[PROPOSAL_KEX_ALGS];
943807
+		xasprintf(&myproposal[PROPOSAL_KEX_ALGS],
943807
+		    "%s,%s", gss, orig);
943807
+		free(gss);
943807
+	}
943807
+#endif
943807
 	if ((r = kex_prop2buf(ssh->kex->my, myproposal)) != 0)
943807
 		fatal_r(r, "kex_prop2buf");
943807
 
943807
@@ -330,6 +392,7 @@ static int input_gssapi_response(int type, u_int32_t, struct ssh *);
943807
 static int input_gssapi_token(int type, u_int32_t, struct ssh *);
943807
 static int input_gssapi_error(int, u_int32_t, struct ssh *);
943807
 static int input_gssapi_errtok(int, u_int32_t, struct ssh *);
943807
+static int userauth_gsskeyex(struct ssh *);
943807
 #endif
943807
 
943807
 void	userauth(struct ssh *, char *);
943807
@@ -346,6 +409,11 @@ static char *authmethods_get(void);
943807
 
943807
 Authmethod authmethods[] = {
943807
 #ifdef GSSAPI
943807
+	{"gssapi-keyex",
943807
+		userauth_gsskeyex,
943807
+		NULL,
943807
+		&options.gss_keyex,
943807
+		NULL},
943807
 	{"gssapi-with-mic",
943807
 		userauth_gssapi,
943807
 		userauth_gssapi_cleanup,
943807
@@ -716,12 +784,32 @@ userauth_gssapi(struct ssh *ssh)
943807
 	OM_uint32 min;
943807
 	int r, ok = 0;
943807
 	gss_OID mech = NULL;
943807
+	char *gss_host = NULL;
943807
+
943807
+	if (options.gss_server_identity) {
943807
+		gss_host = xstrdup(options.gss_server_identity);
943807
+	} else if (options.gss_trust_dns) {
943807
+		gss_host = remote_hostname(ssh);
943807
+		/* Fall back to specified host if we are using proxy command
943807
+		 * and can not use DNS on that socket */
943807
+		if (strcmp(gss_host, "UNKNOWN") == 0) {
943807
+			free(gss_host);
943807
+			gss_host = xstrdup(authctxt->host);
943807
+		}
943807
+	} else {
943807
+		gss_host = xstrdup(authctxt->host);
943807
+	}
943807
 
943807
 	/* Try one GSSAPI method at a time, rather than sending them all at
943807
 	 * once. */
943807
 
943807
 	if (authctxt->gss_supported_mechs == NULL)
943807
-		gss_indicate_mechs(&min, &authctxt->gss_supported_mechs);
943807
+		if (GSS_ERROR(gss_indicate_mechs(&min,
943807
+		    &authctxt->gss_supported_mechs))) {
943807
+			authctxt->gss_supported_mechs = NULL;
943807
+			free(gss_host);
943807
+			return 0;
943807
+		}
943807
 
943807
 	/* Check to see whether the mechanism is usable before we offer it */
943807
 	while (authctxt->mech_tried < authctxt->gss_supported_mechs->count &&
943807
@@ -730,13 +811,15 @@ userauth_gssapi(struct ssh *ssh)
943807
 		    elements[authctxt->mech_tried];
943807
 		/* My DER encoding requires length<128 */
943807
 		if (mech->length < 128 && ssh_gssapi_check_mechanism(&gssctxt,
943807
-		    mech, authctxt->host)) {
943807
+		    mech, gss_host, options.gss_client_identity)) {
943807
 			ok = 1; /* Mechanism works */
943807
 		} else {
943807
 			authctxt->mech_tried++;
943807
 		}
943807
 	}
943807
 
943807
+	free(gss_host);
943807
+
943807
 	if (!ok || mech == NULL)
943807
 		return 0;
943807
 
943807
@@ -976,6 +1059,55 @@ input_gssapi_error(int type, u_int32_t plen, struct ssh *ssh)
943807
 	free(lang);
943807
 	return r;
943807
 }
943807
+
943807
+int
943807
+userauth_gsskeyex(struct ssh *ssh)
943807
+{
943807
+	struct sshbuf *b = NULL;
943807
+	Authctxt *authctxt = ssh->authctxt;
943807
+	gss_buffer_desc gssbuf;
943807
+	gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
943807
+	OM_uint32 ms;
943807
+	int r;
943807
+
943807
+	static int attempt = 0;
943807
+	if (attempt++ >= 1)
943807
+		return (0);
943807
+
943807
+	if (gss_kex_context == NULL) {
943807
+		debug("No valid Key exchange context");
943807
+		return (0);
943807
+	}
943807
+
943807
+	if ((b = sshbuf_new()) == NULL)
943807
+		fatal_f("sshbuf_new failed");
943807
+
943807
+	ssh_gssapi_buildmic(b, authctxt->server_user, authctxt->service,
943807
+	    "gssapi-keyex", ssh->kex->session_id);
943807
+
943807
+	if ((gssbuf.value = sshbuf_mutable_ptr(b)) == NULL)
943807
+		fatal_f("sshbuf_mutable_ptr failed");
943807
+	gssbuf.length = sshbuf_len(b);
943807
+
943807
+	if (GSS_ERROR(ssh_gssapi_sign(gss_kex_context, &gssbuf, &mic))) {
943807
+		sshbuf_free(b);
943807
+		return (0);
943807
+	}
943807
+
943807
+	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
943807
+	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
943807
+	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
943807
+	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
943807
+	    (r = sshpkt_put_string(ssh, mic.value, mic.length)) != 0 ||
943807
+	    (r = sshpkt_send(ssh)) != 0)
943807
+		fatal_fr(r, "parsing");
943807
+
943807
+	sshbuf_free(b);
943807
+	gss_release_buffer(&ms, &mic);
943807
+
943807
+	return (1);
943807
+}
943807
+
943807
 #endif /* GSSAPI */
943807
 
943807
 static int
943807
diff --git a/sshd.c b/sshd.c
943807
index 60b2aaf7..d92f03aa 100644
943807
--- a/sshd.c
943807
+++ b/sshd.c
943807
@@ -817,8 +817,8 @@ notify_hostkeys(struct ssh *ssh)
943807
 	}
943807
 	debug3_f("sent %u hostkeys", nkeys);
943807
 	if (nkeys == 0)
943807
-		fatal_f("no hostkeys");
943807
-	if ((r = sshpkt_send(ssh)) != 0)
943807
+		debug3_f("no hostkeys");
943807
+	else if ((r = sshpkt_send(ssh)) != 0)
943807
 		sshpkt_fatal(ssh, r, "%s: send", __func__);
943807
 	sshbuf_free(buf);
943807
 }
943807
@@ -1852,7 +1852,8 @@ main(int ac, char **av)
943807
 		free(fp);
943807
 	}
943807
 	accumulate_host_timing_secret(cfg, NULL);
943807
-	if (!sensitive_data.have_ssh2_key) {
943807
+	/* The GSSAPI key exchange can run without a host key */
943807
+	if (!sensitive_data.have_ssh2_key && !options.gss_keyex) {
943807
 		logit("sshd: no hostkeys available -- exiting.");
943807
 		exit(1);
943807
 	}
943807
@@ -2347,6 +2348,48 @@ do_ssh2_kex(struct ssh *ssh)
943807
 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
943807
 	    ssh, list_hostkey_types());
943807
 
943807
+#if defined(GSSAPI) && defined(WITH_OPENSSL)
943807
+	{
943807
+	char *orig;
943807
+	char *gss = NULL;
943807
+	char *newstr = NULL;
943807
+	orig = myproposal[PROPOSAL_KEX_ALGS];
943807
+
943807
+	/*
943807
+	 * If we don't have a host key, then there's no point advertising
943807
+	 * the other key exchange algorithms
943807
+	 */
943807
+
943807
+	if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]) == 0)
943807
+		orig = NULL;
943807
+
943807
+	if (options.gss_keyex)
943807
+		gss = ssh_gssapi_server_mechanisms();
943807
+	else
943807
+		gss = NULL;
943807
+
943807
+	if (gss && orig)
943807
+		xasprintf(&newstr, "%s,%s", gss, orig);
943807
+	else if (gss)
943807
+		newstr = gss;
943807
+	else if (orig)
943807
+		newstr = orig;
943807
+
943807
+	/*
943807
+	 * If we've got GSSAPI mechanisms, then we've got the 'null' host
943807
+	 * key alg, but we can't tell people about it unless its the only
943807
+	 * host key algorithm we support
943807
+	 */
943807
+	if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0)
943807
+		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = "null";
943807
+
943807
+	if (newstr)
943807
+		myproposal[PROPOSAL_KEX_ALGS] = newstr;
943807
+	else
943807
+		fatal("No supported key exchange algorithms");
943807
+	}
943807
+#endif
943807
+
943807
 	/* start key exchange */
943807
 	if ((r = kex_setup(ssh, myproposal)) != 0)
943807
 		fatal_r(r, "kex_setup");
943807
@@ -2362,7 +2405,18 @@ do_ssh2_kex(struct ssh *ssh)
943807
 # ifdef OPENSSL_HAS_ECC
943807
 	kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
943807
 # endif
943807
-#endif
943807
+# ifdef GSSAPI
943807
+	if (options.gss_keyex) {
943807
+		kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
943807
+		kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
943807
+		kex->kex[KEX_GSS_GRP14_SHA256] = kexgss_server;
943807
+		kex->kex[KEX_GSS_GRP16_SHA512] = kexgss_server;
943807
+		kex->kex[KEX_GSS_GEX_SHA1] = kexgssgex_server;
943807
+		kex->kex[KEX_GSS_NISTP256_SHA256] = kexgss_server;
943807
+		kex->kex[KEX_GSS_C25519_SHA256] = kexgss_server;
943807
+	}
943807
+# endif
943807
+#endif /* WITH_OPENSSL */
943807
 	kex->kex[KEX_C25519_SHA256] = kex_gen_server;
943807
 	kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
943807
 	kex->load_host_public_key=&get_hostkey_public_by_type;
943807
diff --git a/sshd_config b/sshd_config
943807
index 19b7c91a..2c48105f 100644
943807
--- a/sshd_config
943807
+++ b/sshd_config
943807
@@ -69,6 +69,8 @@ AuthorizedKeysFile	.ssh/authorized_keys
943807
 # GSSAPI options
943807
 #GSSAPIAuthentication no
943807
 #GSSAPICleanupCredentials yes
943807
+#GSSAPIStrictAcceptorCheck yes
943807
+#GSSAPIKeyExchange no
943807
 
943807
 # Set this to 'yes' to enable PAM authentication, account processing,
943807
 # and session processing. If this is enabled, PAM authentication will
943807
diff --git a/sshd_config.5 b/sshd_config.5
943807
index 70ccea44..f6b41a2f 100644
943807
--- a/sshd_config.5
943807
+++ b/sshd_config.5
943807
@@ -646,6 +646,11 @@ Specifies whether to automatically destroy the user's credentials cache
943807
 on logout.
943807
 The default is
943807
 .Cm yes .
943807
+.It Cm GSSAPIKeyExchange
943807
+Specifies whether key exchange based on GSSAPI is allowed. GSSAPI key exchange
943807
+doesn't rely on ssh keys to verify host identity.
943807
+The default is
943807
+.Cm no .
943807
 .It Cm GSSAPIStrictAcceptorCheck
943807
 Determines whether to be strict about the identity of the GSSAPI acceptor
943807
 a client authenticates against.
943807
@@ -660,6 +665,32 @@ machine's default store.
943807
 This facility is provided to assist with operation on multi homed machines.
943807
 The default is
943807
 .Cm yes .
943807
+.It Cm GSSAPIStoreCredentialsOnRekey
943807
+Controls whether the user's GSSAPI credentials should be updated following a
943807
+successful connection rekeying. This option can be used to accepted renewed
943807
+or updated credentials from a compatible client. The default is
943807
+.Dq no .
943807
+.Pp
943807
+For this to work
943807
+.Cm GSSAPIKeyExchange
943807
+needs to be enabled in the server and also used by the client.
943807
+.It Cm GSSAPIKexAlgorithms
943807
+The list of key exchange algorithms that are accepted by GSSAPI
943807
+key exchange. Possible values are
943807
+.Bd -literal -offset 3n
943807
+gss-gex-sha1-,
943807
+gss-group1-sha1-,
943807
+gss-group14-sha1-,
943807
+gss-group14-sha256-,
943807
+gss-group16-sha512-,
943807
+gss-nistp256-sha256-,
943807
+gss-curve25519-sha256-
943807
+.Ed
943807
+.Pp
943807
+The default is
943807
+.Dq gss-group14-sha256-,gss-group16-sha512-,gss-nistp256-sha256-,
943807
+gss-curve25519-sha256-,gss-group14-sha1-,gss-gex-sha1- .
943807
+This option only applies to connections using GSSAPI.
943807
 .It Cm HostbasedAcceptedAlgorithms
943807
 Specifies the signature algorithms that will be accepted for hostbased
943807
 authentication as a list of comma-separated patterns.
943807
diff --git a/sshkey.c b/sshkey.c
943807
index 57995ee6..fd5b7724 100644
943807
--- a/sshkey.c
943807
+++ b/sshkey.c
943807
@@ -154,6 +154,7 @@ static const struct keytype keytypes[] = {
943807
 	    KEY_ECDSA_SK_CERT, NID_X9_62_prime256v1, 1, 0 },
943807
 # endif /* OPENSSL_HAS_ECC */
943807
 #endif /* WITH_OPENSSL */
943807
+	{ "null", "null", NULL, KEY_NULL, 0, 0, 0 },
943807
 	{ NULL, NULL, NULL, -1, -1, 0, 0 }
943807
 };
943807
 
943807
@@ -255,7 +256,7 @@ sshkey_alg_list(int certs_only, int plain_only, int include_sigonly, char sep)
943807
 	const struct keytype *kt;
943807
 
943807
 	for (kt = keytypes; kt->type != -1; kt++) {
943807
-		if (kt->name == NULL)
943807
+		if (kt->name == NULL || kt->type == KEY_NULL)
943807
 			continue;
943807
 		if (!include_sigonly && kt->sigonly)
943807
 			continue;
943807
diff --git a/sshkey.h b/sshkey.h
943807
index 71a3fddc..37a43a67 100644
943807
--- a/sshkey.h
943807
+++ b/sshkey.h
943807
@@ -69,6 +69,7 @@ enum sshkey_types {
943807
 	KEY_ECDSA_SK_CERT,
943807
 	KEY_ED25519_SK,
943807
 	KEY_ED25519_SK_CERT,
943807
+	KEY_NULL,
943807
 	KEY_UNSPEC
943807
 };
943807