kentpeacock / rpms / openssh

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