rcolebaugh / rpms / openssh

Forked from rpms/openssh 2 years ago
Clone

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

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