bmh10 / rpms / openssh

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