bmh10 / rpms / openssh

Forked from rpms/openssh 2 days ago
Clone

Blame SOURCES/openssh-8.0p1-gssapi-keyex.patch

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