def1de
diff --git a/Makefile.in b/Makefile.in
def1de
index 6f001bb3..c31821ac 100644
def1de
--- a/Makefile.in
def1de
+++ b/Makefile.in
def1de
@@ -100,6 +100,7 @@ LIBSSH_OBJS=${LIBOPENSSH_OBJS} \
def1de
 	kex.o kexdh.o kexgex.o kexecdh.o kexc25519.o \
def1de
 	kexgexc.o kexgexs.o \
def1de
 	sntrup4591761.o kexsntrup4591761x25519.o kexgen.o \
def1de
+	kexgssc.o \
def1de
 	platform-pledge.o platform-tracing.o platform-misc.o
def1de
 
def1de
 
def1de
@@ -114,7 +115,7 @@ SSHDOBJS=sshd.o auth-rhosts.o auth-passwd.o \
def1de
 	auth-bsdauth.o auth2-hostbased.o auth2-kbdint.o \
def1de
 	auth2-none.o auth2-passwd.o auth2-pubkey.o \
def1de
 	monitor.o monitor_wrap.o auth-krb5.o \
def1de
-	auth2-gss.o gss-serv.o gss-serv-krb5.o \
def1de
+	auth2-gss.o gss-serv.o gss-serv-krb5.o kexgsss.o \
def1de
 	loginrec.o auth-pam.o auth-shadow.o auth-sia.o md5crypt.o \
def1de
 	sftp-server.o sftp-common.o \
def1de
 	sandbox-null.o sandbox-rlimit.o sandbox-systrace.o sandbox-darwin.o \
def1de
diff --git a/auth.c b/auth.c
def1de
index 332b6220..7664aaac 100644
def1de
--- a/auth.c
def1de
+++ b/auth.c
def1de
@@ -399,7 +399,8 @@ auth_root_allowed(struct ssh *ssh, const char *method)
def1de
 	case PERMIT_NO_PASSWD:
def1de
 		if (strcmp(method, "publickey") == 0 ||
def1de
 		    strcmp(method, "hostbased") == 0 ||
def1de
-		    strcmp(method, "gssapi-with-mic") == 0)
def1de
+		    strcmp(method, "gssapi-with-mic") == 0 ||
def1de
+		    strcmp(method, "gssapi-keyex") == 0)
def1de
 			return 1;
def1de
 		break;
def1de
 	case PERMIT_FORCED_ONLY:
def1de
@@ -723,99 +724,6 @@ fakepw(void)
def1de
 	return (&fake);
def1de
 }
def1de
 
def1de
-/*
def1de
- * Returns the remote DNS hostname as a string. The returned string must not
def1de
- * be freed. NB. this will usually trigger a DNS query the first time it is
def1de
- * called.
def1de
- * This function does additional checks on the hostname to mitigate some
def1de
- * attacks on legacy rhosts-style authentication.
def1de
- * XXX is RhostsRSAAuthentication vulnerable to these?
def1de
- * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
def1de
- */
def1de
-
def1de
-static char *
def1de
-remote_hostname(struct ssh *ssh)
def1de
-{
def1de
-	struct sockaddr_storage from;
def1de
-	socklen_t fromlen;
def1de
-	struct addrinfo hints, *ai, *aitop;
def1de
-	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
def1de
-	const char *ntop = ssh_remote_ipaddr(ssh);
def1de
-
def1de
-	/* Get IP address of client. */
def1de
-	fromlen = sizeof(from);
def1de
-	memset(&from, 0, sizeof(from));
def1de
-	if (getpeername(ssh_packet_get_connection_in(ssh),
def1de
-	    (struct sockaddr *)&from, &fromlen) < 0) {
def1de
-		debug("getpeername failed: %.100s", strerror(errno));
def1de
-		return strdup(ntop);
def1de
-	}
def1de
-
def1de
-	ipv64_normalise_mapped(&from, &fromlen);
def1de
-	if (from.ss_family == AF_INET6)
def1de
-		fromlen = sizeof(struct sockaddr_in6);
def1de
-
def1de
-	debug3("Trying to reverse map address %.100s.", ntop);
def1de
-	/* Map the IP address to a host name. */
def1de
-	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
def1de
-	    NULL, 0, NI_NAMEREQD) != 0) {
def1de
-		/* Host name not found.  Use ip address. */
def1de
-		return strdup(ntop);
def1de
-	}
def1de
-
def1de
-	/*
def1de
-	 * if reverse lookup result looks like a numeric hostname,
def1de
-	 * someone is trying to trick us by PTR record like following:
def1de
-	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
def1de
-	 */
def1de
-	memset(&hints, 0, sizeof(hints));
def1de
-	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
def1de
-	hints.ai_flags = AI_NUMERICHOST;
def1de
-	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
def1de
-		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
def1de
-		    name, ntop);
def1de
-		freeaddrinfo(ai);
def1de
-		return strdup(ntop);
def1de
-	}
def1de
-
def1de
-	/* Names are stored in lowercase. */
def1de
-	lowercase(name);
def1de
-
def1de
-	/*
def1de
-	 * Map it back to an IP address and check that the given
def1de
-	 * address actually is an address of this host.  This is
def1de
-	 * necessary because anyone with access to a name server can
def1de
-	 * define arbitrary names for an IP address. Mapping from
def1de
-	 * name to IP address can be trusted better (but can still be
def1de
-	 * fooled if the intruder has access to the name server of
def1de
-	 * the domain).
def1de
-	 */
def1de
-	memset(&hints, 0, sizeof(hints));
def1de
-	hints.ai_family = from.ss_family;
def1de
-	hints.ai_socktype = SOCK_STREAM;
def1de
-	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
def1de
-		logit("reverse mapping checking getaddrinfo for %.700s "
def1de
-		    "[%s] failed.", name, ntop);
def1de
-		return strdup(ntop);
def1de
-	}
def1de
-	/* Look for the address from the list of addresses. */
def1de
-	for (ai = aitop; ai; ai = ai->ai_next) {
def1de
-		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
def1de
-		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
def1de
-		    (strcmp(ntop, ntop2) == 0))
def1de
-				break;
def1de
-	}
def1de
-	freeaddrinfo(aitop);
def1de
-	/* If we reached the end of the list, the address was not there. */
def1de
-	if (ai == NULL) {
def1de
-		/* Address not found for the host name. */
def1de
-		logit("Address %.100s maps to %.600s, but this does not "
def1de
-		    "map back to the address.", ntop, name);
def1de
-		return strdup(ntop);
def1de
-	}
def1de
-	return strdup(name);
def1de
-}
def1de
-
def1de
 /*
def1de
  * Return the canonical name of the host in the other side of the current
def1de
  * connection.  The host name is cached, so it is efficient to call this
def1de
diff --git a/auth2-gss.c b/auth2-gss.c
def1de
index 9351e042..d6446c0c 100644
def1de
--- a/auth2-gss.c
def1de
+++ b/auth2-gss.c
def1de
@@ -1,7 +1,7 @@
def1de
 /* $OpenBSD: auth2-gss.c,v 1.29 2018/07/31 03:10:27 djm Exp $ */
def1de
 
def1de
 /*
def1de
- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
def1de
+ * Copyright (c) 2001-2007 Simon Wilkinson. All rights reserved.
def1de
  *
def1de
  * Redistribution and use in source and binary forms, with or without
def1de
  * modification, are permitted provided that the following conditions
def1de
@@ -54,6 +54,48 @@ static int input_gssapi_mic(int type, u_int32_t plen, struct ssh *ssh);
def1de
 static int input_gssapi_exchange_complete(int type, u_int32_t plen, struct ssh *ssh);
def1de
 static int input_gssapi_errtok(int, u_int32_t, struct ssh *);
def1de
 
def1de
+/*
def1de
+ * The 'gssapi_keyex' userauth mechanism.
def1de
+ */
def1de
+static int
def1de
+userauth_gsskeyex(struct ssh *ssh)
def1de
+{
def1de
+	Authctxt *authctxt = ssh->authctxt;
def1de
+	int r, authenticated = 0;
def1de
+	struct sshbuf *b = NULL;
def1de
+	gss_buffer_desc mic, gssbuf;
def1de
+	u_char *p;
def1de
+	size_t len;
def1de
+
def1de
+	if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
def1de
+	    (r = sshpkt_get_end(ssh)) != 0)
def1de
+		fatal("%s: %s", __func__, ssh_err(r));
def1de
+
def1de
+	if ((b = sshbuf_new()) == NULL)
def1de
+		fatal("%s: sshbuf_new failed", __func__);
def1de
+
def1de
+	mic.value = p;
def1de
+	mic.length = len;
def1de
+
def1de
+	ssh_gssapi_buildmic(b, authctxt->user, authctxt->service,
def1de
+	    "gssapi-keyex");
def1de
+
def1de
+	if ((gssbuf.value = sshbuf_mutable_ptr(b)) == NULL)
def1de
+		fatal("%s: sshbuf_mutable_ptr failed", __func__);
def1de
+	gssbuf.length = sshbuf_len(b);
def1de
+
def1de
+	/* gss_kex_context is NULL with privsep, so we can't check it here */
def1de
+	if (!GSS_ERROR(PRIVSEP(ssh_gssapi_checkmic(gss_kex_context,
def1de
+	    &gssbuf, &mic))))
def1de
+		authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user,
def1de
+		    authctxt->pw, 1));
def1de
+
def1de
+	sshbuf_free(b);
def1de
+	free(mic.value);
def1de
+
def1de
+	return (authenticated);
def1de
+}
def1de
+
def1de
 /*
def1de
  * We only support those mechanisms that we know about (ie ones that we know
def1de
  * how to check local user kuserok and the like)
def1de
@@ -260,7 +302,8 @@ input_gssapi_exchange_complete(int type, u_int32_t plen, struct ssh *ssh)
def1de
 	if ((r = sshpkt_get_end(ssh)) != 0)
def1de
 		fatal("%s: %s", __func__, ssh_err(r));
def1de
 
def1de
-	authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user));
def1de
+	authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user,
def1de
+	    authctxt->pw, 1));
def1de
 
def1de
 	if ((!use_privsep || mm_is_monitor()) &&
def1de
 	    (displayname = ssh_gssapi_displayname()) != NULL)
def1de
@@ -306,7 +349,8 @@ input_gssapi_mic(int type, u_int32_t plen, struct ssh *ssh)
def1de
 	gssbuf.length = sshbuf_len(b);
def1de
 
def1de
 	if (!GSS_ERROR(PRIVSEP(ssh_gssapi_checkmic(gssctxt, &gssbuf, &mic))))
def1de
-		authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user));
def1de
+		authenticated = PRIVSEP(ssh_gssapi_userok(authctxt->user,
def1de
+		    authctxt->pw, 0));
def1de
 	else
def1de
 		logit("GSSAPI MIC check failed");
def1de
 
def1de
@@ -326,6 +370,12 @@ input_gssapi_mic(int type, u_int32_t plen, struct ssh *ssh)
def1de
 	return 0;
def1de
 }
def1de
 
def1de
+Authmethod method_gsskeyex = {
def1de
+	"gssapi-keyex",
def1de
+	userauth_gsskeyex,
def1de
+	&options.gss_authentication
def1de
+};
def1de
+
def1de
 Authmethod method_gssapi = {
def1de
 	"gssapi-with-mic",
def1de
 	userauth_gssapi,
def1de
diff --git a/auth2.c b/auth2.c
def1de
index 16ae1a36..7417eafa 100644
def1de
--- a/auth2.c
def1de
+++ b/auth2.c
def1de
@@ -75,6 +75,7 @@ extern Authmethod method_passwd;
def1de
 extern Authmethod method_kbdint;
def1de
 extern Authmethod method_hostbased;
def1de
 #ifdef GSSAPI
def1de
+extern Authmethod method_gsskeyex;
def1de
 extern Authmethod method_gssapi;
def1de
 #endif
def1de
 
def1de
@@ -82,6 +83,7 @@ Authmethod *authmethods[] = {
def1de
 	&method_none,
def1de
 	&method_pubkey,
def1de
 #ifdef GSSAPI
def1de
+	&method_gsskeyex,
def1de
 	&method_gssapi,
def1de
 #endif
def1de
 	&method_passwd,
def1de
diff --git a/canohost.c b/canohost.c
def1de
index f71a0856..404731d2 100644
def1de
--- a/canohost.c
def1de
+++ b/canohost.c
def1de
@@ -35,6 +35,99 @@
def1de
 #include "canohost.h"
def1de
 #include "misc.h"
def1de
 
def1de
+/*
def1de
+ * Returns the remote DNS hostname as a string. The returned string must not
def1de
+ * be freed. NB. this will usually trigger a DNS query the first time it is
def1de
+ * called.
def1de
+ * This function does additional checks on the hostname to mitigate some
def1de
+ * attacks on legacy rhosts-style authentication.
def1de
+ * XXX is RhostsRSAAuthentication vulnerable to these?
def1de
+ * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
def1de
+ */
def1de
+
def1de
+char *
def1de
+remote_hostname(struct ssh *ssh)
def1de
+{
def1de
+	struct sockaddr_storage from;
def1de
+	socklen_t fromlen;
def1de
+	struct addrinfo hints, *ai, *aitop;
def1de
+	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
def1de
+	const char *ntop = ssh_remote_ipaddr(ssh);
def1de
+
def1de
+	/* Get IP address of client. */
def1de
+	fromlen = sizeof(from);
def1de
+	memset(&from, 0, sizeof(from));
def1de
+	if (getpeername(ssh_packet_get_connection_in(ssh),
def1de
+	    (struct sockaddr *)&from, &fromlen) < 0) {
def1de
+		debug("getpeername failed: %.100s", strerror(errno));
def1de
+		return strdup(ntop);
def1de
+	}
def1de
+
def1de
+	ipv64_normalise_mapped(&from, &fromlen);
def1de
+	if (from.ss_family == AF_INET6)
def1de
+		fromlen = sizeof(struct sockaddr_in6);
def1de
+
def1de
+	debug3("Trying to reverse map address %.100s.", ntop);
def1de
+	/* Map the IP address to a host name. */
def1de
+	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
def1de
+	    NULL, 0, NI_NAMEREQD) != 0) {
def1de
+		/* Host name not found.  Use ip address. */
def1de
+		return strdup(ntop);
def1de
+	}
def1de
+
def1de
+	/*
def1de
+	 * if reverse lookup result looks like a numeric hostname,
def1de
+	 * someone is trying to trick us by PTR record like following:
def1de
+	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
def1de
+	 */
def1de
+	memset(&hints, 0, sizeof(hints));
def1de
+	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
def1de
+	hints.ai_flags = AI_NUMERICHOST;
def1de
+	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
def1de
+		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
def1de
+		    name, ntop);
def1de
+		freeaddrinfo(ai);
def1de
+		return strdup(ntop);
def1de
+	}
def1de
+
def1de
+	/* Names are stored in lowercase. */
def1de
+	lowercase(name);
def1de
+
def1de
+	/*
def1de
+	 * Map it back to an IP address and check that the given
def1de
+	 * address actually is an address of this host.  This is
def1de
+	 * necessary because anyone with access to a name server can
def1de
+	 * define arbitrary names for an IP address. Mapping from
def1de
+	 * name to IP address can be trusted better (but can still be
def1de
+	 * fooled if the intruder has access to the name server of
def1de
+	 * the domain).
def1de
+	 */
def1de
+	memset(&hints, 0, sizeof(hints));
def1de
+	hints.ai_family = from.ss_family;
def1de
+	hints.ai_socktype = SOCK_STREAM;
def1de
+	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
def1de
+		logit("reverse mapping checking getaddrinfo for %.700s "
def1de
+		    "[%s] failed.", name, ntop);
def1de
+		return strdup(ntop);
def1de
+	}
def1de
+	/* Look for the address from the list of addresses. */
def1de
+	for (ai = aitop; ai; ai = ai->ai_next) {
def1de
+		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
def1de
+		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
def1de
+		    (strcmp(ntop, ntop2) == 0))
def1de
+				break;
def1de
+	}
def1de
+	freeaddrinfo(aitop);
def1de
+	/* If we reached the end of the list, the address was not there. */
def1de
+	if (ai == NULL) {
def1de
+		/* Address not found for the host name. */
def1de
+		logit("Address %.100s maps to %.600s, but this does not "
def1de
+		    "map back to the address.", ntop, name);
def1de
+		return strdup(ntop);
def1de
+	}
def1de
+	return strdup(name);
def1de
+}
def1de
+
def1de
 void
def1de
 ipv64_normalise_mapped(struct sockaddr_storage *addr, socklen_t *len)
def1de
 {
def1de
diff --git a/canohost.h b/canohost.h
def1de
index 26d62855..0cadc9f1 100644
def1de
--- a/canohost.h
def1de
+++ b/canohost.h
def1de
@@ -15,6 +15,9 @@
def1de
 #ifndef _CANOHOST_H
def1de
 #define _CANOHOST_H
def1de
 
def1de
+struct ssh;
def1de
+
def1de
+char		*remote_hostname(struct ssh *);
def1de
 char		*get_peer_ipaddr(int);
def1de
 int		 get_peer_port(int);
def1de
 char		*get_local_ipaddr(int);
def1de
diff --git a/clientloop.c b/clientloop.c
def1de
index 521467bd..a0578e9d 100644
def1de
--- a/clientloop.c
def1de
+++ b/clientloop.c
def1de
@@ -112,6 +112,10 @@
def1de
 #include "ssherr.h"
def1de
 #include "hostfile.h"
def1de
 
def1de
+#ifdef GSSAPI
def1de
+#include "ssh-gss.h"
def1de
+#endif
def1de
+
def1de
 /* import options */
def1de
 extern Options options;
def1de
 
def1de
@@ -1374,9 +1378,18 @@ client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
def1de
 			break;
def1de
 
def1de
 		/* Do channel operations unless rekeying in progress. */
def1de
-		if (!ssh_packet_is_rekeying(ssh))
def1de
+		if (!ssh_packet_is_rekeying(ssh)) {
def1de
 			channel_after_select(ssh, readset, writeset);
def1de
 
def1de
+#ifdef GSSAPI
def1de
+			if (options.gss_renewal_rekey &&
def1de
+			    ssh_gssapi_credentials_updated(NULL)) {
def1de
+				debug("credentials updated - forcing rekey");
def1de
+				need_rekeying = 1;
def1de
+			}
def1de
+#endif
def1de
+		}
def1de
+
def1de
 		/* Buffer input from the connection.  */
def1de
 		client_process_net_input(ssh, readset);
def1de
 
def1de
diff --git a/configure.ac b/configure.ac
def1de
index 30be6c18..2869f704 100644
def1de
--- a/configure.ac
def1de
+++ b/configure.ac
def1de
@@ -665,6 +665,30 @@ main() { if (NSVersionOfRunTimeLibrary("System") >= (60 << 16))
def1de
 	    [Use tunnel device compatibility to OpenBSD])
def1de
 	AC_DEFINE([SSH_TUN_PREPEND_AF], [1],
def1de
 	    [Prepend the address family to IP tunnel traffic])
def1de
+	AC_MSG_CHECKING([if we have the Security Authorization Session API])
def1de
+	AC_TRY_COMPILE([#include <Security/AuthSession.h>],
def1de
+		[SessionCreate(0, 0);],
def1de
+		[ac_cv_use_security_session_api="yes"
def1de
+		 AC_DEFINE([USE_SECURITY_SESSION_API], [1],
def1de
+			[platform has the Security Authorization Session API])
def1de
+		 LIBS="$LIBS -framework Security"
def1de
+		 AC_MSG_RESULT([yes])],
def1de
+		[ac_cv_use_security_session_api="no"
def1de
+		 AC_MSG_RESULT([no])])
def1de
+	AC_MSG_CHECKING([if we have an in-memory credentials cache])
def1de
+	AC_TRY_COMPILE(
def1de
+		[#include <Kerberos/Kerberos.h>],
def1de
+		[cc_context_t c;
def1de
+		 (void) cc_initialize (&c, 0, NULL, NULL);],
def1de
+		[AC_DEFINE([USE_CCAPI], [1],
def1de
+			[platform uses an in-memory credentials cache])
def1de
+		 LIBS="$LIBS -framework Security"
def1de
+		 AC_MSG_RESULT([yes])
def1de
+		 if test "x$ac_cv_use_security_session_api" = "xno"; then
def1de
+			AC_MSG_ERROR([*** Need a security framework to use the credentials cache API ***])
def1de
+		fi],
def1de
+		[AC_MSG_RESULT([no])]
def1de
+	)
def1de
 	m4_pattern_allow([AU_IPv])
def1de
 	AC_CHECK_DECL([AU_IPv4], [],
def1de
 	    AC_DEFINE([AU_IPv4], [0], [System only supports IPv4 audit records])
def1de
diff --git a/gss-genr.c b/gss-genr.c
def1de
index d56257b4..3eaa5fa5 100644
def1de
--- a/gss-genr.c
def1de
+++ b/gss-genr.c
def1de
@@ -1,7 +1,7 @@
def1de
 /* $OpenBSD: gss-genr.c,v 1.26 2018/07/10 09:13:30 djm Exp $ */
def1de
 
def1de
 /*
def1de
- * Copyright (c) 2001-2007 Simon Wilkinson. All rights reserved.
def1de
+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
def1de
  *
def1de
  * Redistribution and use in source and binary forms, with or without
def1de
  * modification, are permitted provided that the following conditions
def1de
@@ -41,12 +41,36 @@
def1de
 #include "sshbuf.h"
def1de
 #include "log.h"
def1de
 #include "ssh2.h"
def1de
+#include "cipher.h"
def1de
+#include "sshkey.h"
def1de
+#include "kex.h"
def1de
+#include "digest.h"
def1de
+#include "packet.h"
def1de
 
def1de
 #include "ssh-gss.h"
def1de
 
def1de
 extern u_char *session_id2;
def1de
 extern u_int session_id2_len;
def1de
 
def1de
+typedef struct {
def1de
+	char *encoded;
def1de
+	gss_OID oid;
def1de
+} ssh_gss_kex_mapping;
def1de
+
def1de
+/*
def1de
+ * XXX - It would be nice to find a more elegant way of handling the
def1de
+ * XXX   passing of the key exchange context to the userauth routines
def1de
+ */
def1de
+
def1de
+Gssctxt *gss_kex_context = NULL;
def1de
+
def1de
+static ssh_gss_kex_mapping *gss_enc2oid = NULL;
def1de
+
def1de
+int
def1de
+ssh_gssapi_oid_table_ok(void) {
def1de
+	return (gss_enc2oid != NULL);
def1de
+}
def1de
+
def1de
 /* sshbuf_get for gss_buffer_desc */
def1de
 int
def1de
 ssh_gssapi_get_buffer_desc(struct sshbuf *b, gss_buffer_desc *g)
def1de
@@ -62,6 +86,161 @@ ssh_gssapi_get_buffer_desc(struct sshbuf *b, gss_buffer_desc *g)
def1de
 	return 0;
def1de
 }
def1de
 
def1de
+/* sshpkt_get of gss_buffer_desc */
def1de
+int
def1de
+ssh_gssapi_sshpkt_get_buffer_desc(struct ssh *ssh, gss_buffer_desc *g)
def1de
+{
def1de
+	int r;
def1de
+	u_char *p;
def1de
+	size_t len;
def1de
+
def1de
+	if ((r = sshpkt_get_string(ssh, &p, &len)) != 0)
def1de
+		return r;
def1de
+	g->value = p;
def1de
+	g->length = len;
def1de
+	return 0;
def1de
+}
def1de
+
def1de
+/*
def1de
+ * Return a list of the gss-group1-sha1 mechanisms supported by this program
def1de
+ *
def1de
+ * We test mechanisms to ensure that we can use them, to avoid starting
def1de
+ * a key exchange with a bad mechanism
def1de
+ */
def1de
+
def1de
+char *
def1de
+ssh_gssapi_client_mechanisms(const char *host, const char *client,
def1de
+    const char *kex) {
def1de
+	gss_OID_set gss_supported = NULL;
def1de
+	OM_uint32 min_status;
def1de
+
def1de
+	if (GSS_ERROR(gss_indicate_mechs(&min_status, &gss_supported)))
def1de
+		return NULL;
def1de
+
def1de
+	return ssh_gssapi_kex_mechs(gss_supported, ssh_gssapi_check_mechanism,
def1de
+	    host, client, kex);
def1de
+}
def1de
+
def1de
+char *
def1de
+ssh_gssapi_kex_mechs(gss_OID_set gss_supported, ssh_gssapi_check_fn *check,
def1de
+    const char *host, const char *client, const char *kex) {
def1de
+	struct sshbuf *buf = NULL;
def1de
+	size_t i;
def1de
+	int r, oidpos, enclen;
def1de
+	char *mechs, *encoded;
def1de
+	u_char digest[SSH_DIGEST_MAX_LENGTH];
def1de
+	char deroid[2];
def1de
+	struct ssh_digest_ctx *md = NULL;
def1de
+	char *s, *cp, *p;
def1de
+
def1de
+	if (gss_enc2oid != NULL) {
def1de
+		for (i = 0; gss_enc2oid[i].encoded != NULL; i++)
def1de
+			free(gss_enc2oid[i].encoded);
def1de
+		free(gss_enc2oid);
def1de
+	}
def1de
+
def1de
+	gss_enc2oid = xmalloc(sizeof(ssh_gss_kex_mapping) *
def1de
+	    (gss_supported->count + 1));
def1de
+
def1de
+	if ((buf = sshbuf_new()) == NULL)
def1de
+		fatal("%s: sshbuf_new failed", __func__);
def1de
+
def1de
+	oidpos = 0;
def1de
+	s = cp = xstrdup(kex);
def1de
+	for (i = 0; i < gss_supported->count; i++) {
def1de
+		if (gss_supported->elements[i].length < 128 &&
def1de
+		    (*check)(NULL, &(gss_supported->elements[i]), host, client)) {
def1de
+
def1de
+			deroid[0] = SSH_GSS_OIDTYPE;
def1de
+			deroid[1] = gss_supported->elements[i].length;
def1de
+
def1de
+			if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
def1de
+			    (r = ssh_digest_update(md, deroid, 2)) != 0 ||
def1de
+			    (r = ssh_digest_update(md,
def1de
+			        gss_supported->elements[i].elements,
def1de
+			        gss_supported->elements[i].length)) != 0 ||
def1de
+			    (r = ssh_digest_final(md, digest, sizeof(digest))) != 0)
def1de
+				fatal("%s: digest failed: %s", __func__,
def1de
+				    ssh_err(r));
def1de
+			ssh_digest_free(md);
def1de
+			md = NULL;
def1de
+
def1de
+			encoded = xmalloc(ssh_digest_bytes(SSH_DIGEST_MD5)
def1de
+			    * 2);
def1de
+			enclen = __b64_ntop(digest,
def1de
+			    ssh_digest_bytes(SSH_DIGEST_MD5), encoded,
def1de
+			    ssh_digest_bytes(SSH_DIGEST_MD5) * 2);
def1de
+
def1de
+			cp = strncpy(s, kex, strlen(kex));
def1de
+			for ((p = strsep(&cp, ",")); p && *p != '\0';
def1de
+				(p = strsep(&cp, ","))) {
def1de
+				if (sshbuf_len(buf) != 0 &&
def1de
+				    (r = sshbuf_put_u8(buf, ',')) != 0)
def1de
+					fatal("%s: sshbuf_put_u8 error: %s",
def1de
+					    __func__, ssh_err(r));
def1de
+				if ((r = sshbuf_put(buf, p, strlen(p))) != 0 ||
def1de
+				    (r = sshbuf_put(buf, encoded, enclen)) != 0)
def1de
+					fatal("%s: sshbuf_put error: %s",
def1de
+					    __func__, ssh_err(r));
def1de
+			}
def1de
+
def1de
+			gss_enc2oid[oidpos].oid = &(gss_supported->elements[i]);
def1de
+			gss_enc2oid[oidpos].encoded = encoded;
def1de
+			oidpos++;
def1de
+		}
def1de
+	}
def1de
+	free(s);
def1de
+	gss_enc2oid[oidpos].oid = NULL;
def1de
+	gss_enc2oid[oidpos].encoded = NULL;
def1de
+
def1de
+	if ((mechs = sshbuf_dup_string(buf)) == NULL)
def1de
+		fatal("%s: sshbuf_dup_string failed", __func__);
def1de
+
def1de
+	sshbuf_free(buf);
def1de
+
def1de
+	if (strlen(mechs) == 0) {
def1de
+		free(mechs);
def1de
+		mechs = NULL;
def1de
+	}
def1de
+
def1de
+	return (mechs);
def1de
+}
def1de
+
def1de
+gss_OID
def1de
+ssh_gssapi_id_kex(Gssctxt *ctx, char *name, int kex_type) {
def1de
+	int i = 0;
def1de
+
def1de
+#define SKIP_KEX_NAME(type) \
def1de
+	case type: \
def1de
+		if (strlen(name) < sizeof(type##_ID)) \
def1de
+			return GSS_C_NO_OID; \
def1de
+		name += sizeof(type##_ID) - 1; \
def1de
+		break;
def1de
+
def1de
+	switch (kex_type) {
def1de
+	SKIP_KEX_NAME(KEX_GSS_GRP1_SHA1)
def1de
+	SKIP_KEX_NAME(KEX_GSS_GRP14_SHA1)
def1de
+	SKIP_KEX_NAME(KEX_GSS_GRP14_SHA256)
def1de
+	SKIP_KEX_NAME(KEX_GSS_GRP16_SHA512)
def1de
+	SKIP_KEX_NAME(KEX_GSS_GEX_SHA1)
def1de
+	SKIP_KEX_NAME(KEX_GSS_NISTP256_SHA256)
def1de
+	SKIP_KEX_NAME(KEX_GSS_C25519_SHA256)
def1de
+	default:
def1de
+		return GSS_C_NO_OID;
def1de
+	}
def1de
+
def1de
+#undef SKIP_KEX_NAME
def1de
+
def1de
+	while (gss_enc2oid[i].encoded != NULL &&
def1de
+	    strcmp(name, gss_enc2oid[i].encoded) != 0)
def1de
+		i++;
def1de
+
def1de
+	if (gss_enc2oid[i].oid != NULL && ctx != NULL)
def1de
+		ssh_gssapi_set_oid(ctx, gss_enc2oid[i].oid);
def1de
+
def1de
+	return gss_enc2oid[i].oid;
def1de
+}
def1de
+
def1de
 /* Check that the OID in a data stream matches that in the context */
def1de
 int
def1de
 ssh_gssapi_check_oid(Gssctxt *ctx, void *data, size_t len)
def1de
@@ -218,7 +397,7 @@ ssh_gssapi_init_ctx(Gssctxt *ctx, int deleg_creds, gss_buffer_desc *recv_tok,
def1de
 	}
def1de
 
def1de
 	ctx->major = gss_init_sec_context(&ctx->minor,
def1de
-	    GSS_C_NO_CREDENTIAL, &ctx->context, ctx->name, ctx->oid,
def1de
+	    ctx->client_creds, &ctx->context, ctx->name, ctx->oid,
def1de
 	    GSS_C_MUTUAL_FLAG | GSS_C_INTEG_FLAG | deleg_flag,
def1de
 	    0, NULL, recv_tok, NULL, send_tok, flags, NULL);
def1de
 
def1de
@@ -247,9 +426,43 @@ ssh_gssapi_import_name(Gssctxt *ctx, const char *host)
def1de
 	return (ctx->major);
def1de
 }
def1de
 
def1de
+OM_uint32
def1de
+ssh_gssapi_client_identity(Gssctxt *ctx, const char *name)
def1de
+{
def1de
+	gss_buffer_desc gssbuf;
def1de
+	gss_name_t gssname;
def1de
+	OM_uint32 status;
def1de
+	gss_OID_set oidset;
def1de
+
def1de
+	gssbuf.value = (void *) name;
def1de
+	gssbuf.length = strlen(gssbuf.value);
def1de
+
def1de
+	gss_create_empty_oid_set(&status, &oidset);
def1de
+	gss_add_oid_set_member(&status, ctx->oid, &oidset);
def1de
+
def1de
+	ctx->major = gss_import_name(&ctx->minor, &gssbuf,
def1de
+	    GSS_C_NT_USER_NAME, &gssname);
def1de
+
def1de
+	if (!ctx->major)
def1de
+		ctx->major = gss_acquire_cred(&ctx->minor,
def1de
+		    gssname, 0, oidset, GSS_C_INITIATE,
def1de
+		    &ctx->client_creds, NULL, NULL);
def1de
+
def1de
+	gss_release_name(&status, &gssname);
def1de
+	gss_release_oid_set(&status, &oidset);
def1de
+
def1de
+	if (ctx->major)
def1de
+		ssh_gssapi_error(ctx);
def1de
+
def1de
+	return(ctx->major);
def1de
+}
def1de
+
def1de
 OM_uint32
def1de
 ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_t buffer, gss_buffer_t hash)
def1de
 {
def1de
+	if (ctx == NULL)
def1de
+		return -1;
def1de
+
def1de
 	if ((ctx->major = gss_get_mic(&ctx->minor, ctx->context,
def1de
 	    GSS_C_QOP_DEFAULT, buffer, hash)))
def1de
 		ssh_gssapi_error(ctx);
def1de
@@ -257,6 +470,19 @@ ssh_gssapi_sign(Gssctxt *ctx, gss_buffer_t buffer, gss_buffer_t hash)
def1de
 	return (ctx->major);
def1de
 }
def1de
 
def1de
+/* Priviledged when used by server */
def1de
+OM_uint32
def1de
+ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
def1de
+{
def1de
+	if (ctx == NULL)
def1de
+		return -1;
def1de
+
def1de
+	ctx->major = gss_verify_mic(&ctx->minor, ctx->context,
def1de
+	    gssbuf, gssmic, NULL);
def1de
+
def1de
+	return (ctx->major);
def1de
+}
def1de
+
def1de
 void
def1de
 ssh_gssapi_buildmic(struct sshbuf *b, const char *user, const char *service,
def1de
     const char *context)
def1de
@@ -273,11 +499,16 @@ ssh_gssapi_buildmic(struct sshbuf *b, const char *user, const char *service,
def1de
 }
def1de
 
def1de
 int
def1de
-ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host)
def1de
+ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host,
def1de
+    const char *client)
def1de
 {
def1de
 	gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
def1de
 	OM_uint32 major, minor;
def1de
 	gss_OID_desc spnego_oid = {6, (void *)"\x2B\x06\x01\x05\x05\x02"};
def1de
+	Gssctxt *intctx = NULL;
def1de
+
def1de
+	if (ctx == NULL)
def1de
+		ctx = &intct;;
def1de
 
def1de
 	/* RFC 4462 says we MUST NOT do SPNEGO */
def1de
 	if (oid->length == spnego_oid.length && 
def1de
@@ -287,6 +518,10 @@ ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host)
def1de
 	ssh_gssapi_build_ctx(ctx);
def1de
 	ssh_gssapi_set_oid(*ctx, oid);
def1de
 	major = ssh_gssapi_import_name(*ctx, host);
def1de
+
def1de
+	if (!GSS_ERROR(major) && client)
def1de
+		major = ssh_gssapi_client_identity(*ctx, client);
def1de
+
def1de
 	if (!GSS_ERROR(major)) {
def1de
 		major = ssh_gssapi_init_ctx(*ctx, 0, GSS_C_NO_BUFFER, &token, 
def1de
 		    NULL);
def1de
@@ -296,10 +531,66 @@ ssh_gssapi_check_mechanism(Gssctxt **ctx, gss_OID oid, const char *host)
def1de
 			    GSS_C_NO_BUFFER);
def1de
 	}
def1de
 
def1de
-	if (GSS_ERROR(major)) 
def1de
+	if (GSS_ERROR(major) || intctx != NULL)
def1de
 		ssh_gssapi_delete_ctx(ctx);
def1de
 
def1de
 	return (!GSS_ERROR(major));
def1de
 }
def1de
 
def1de
+int
def1de
+ssh_gssapi_credentials_updated(Gssctxt *ctxt) {
def1de
+	static gss_name_t saved_name = GSS_C_NO_NAME;
def1de
+	static OM_uint32 saved_lifetime = 0;
def1de
+	static gss_OID saved_mech = GSS_C_NO_OID;
def1de
+	static gss_name_t name;
def1de
+	static OM_uint32 last_call = 0;
def1de
+	OM_uint32 lifetime, now, major, minor;
def1de
+	int equal;
def1de
+
def1de
+	now = time(NULL);
def1de
+
def1de
+	if (ctxt) {
def1de
+		debug("Rekey has happened - updating saved versions");
def1de
+
def1de
+		if (saved_name != GSS_C_NO_NAME)
def1de
+			gss_release_name(&minor, &saved_name);
def1de
+
def1de
+		major = gss_inquire_cred(&minor, GSS_C_NO_CREDENTIAL,
def1de
+		    &saved_name, &saved_lifetime, NULL, NULL);
def1de
+
def1de
+		if (!GSS_ERROR(major)) {
def1de
+			saved_mech = ctxt->oid;
def1de
+		        saved_lifetime+= now;
def1de
+		} else {
def1de
+			/* Handle the error */
def1de
+		}
def1de
+		return 0;
def1de
+	}
def1de
+
def1de
+	if (now - last_call < 10)
def1de
+		return 0;
def1de
+
def1de
+	last_call = now;
def1de
+
def1de
+	if (saved_mech == GSS_C_NO_OID)
def1de
+		return 0;
def1de
+
def1de
+	major = gss_inquire_cred(&minor, GSS_C_NO_CREDENTIAL,
def1de
+	    &name, &lifetime, NULL, NULL);
def1de
+	if (major == GSS_S_CREDENTIALS_EXPIRED)
def1de
+		return 0;
def1de
+	else if (GSS_ERROR(major))
def1de
+		return 0;
def1de
+
def1de
+	major = gss_compare_name(&minor, saved_name, name, &equal);
def1de
+	gss_release_name(&minor, &name);
def1de
+	if (GSS_ERROR(major))
def1de
+		return 0;
def1de
+
def1de
+	if (equal && (saved_lifetime < lifetime + now - 10))
def1de
+		return 1;
def1de
+
def1de
+	return 0;
def1de
+}
def1de
+
def1de
 #endif /* GSSAPI */
def1de
diff --git a/gss-serv-krb5.c b/gss-serv-krb5.c
def1de
index a151bc1e..8d2b677f 100644
def1de
--- a/gss-serv-krb5.c
def1de
+++ b/gss-serv-krb5.c
def1de
@@ -1,7 +1,7 @@
def1de
 /* $OpenBSD: gss-serv-krb5.c,v 1.9 2018/07/09 21:37:55 markus Exp $ */
def1de
 
def1de
 /*
def1de
- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
def1de
+ * Copyright (c) 2001-2007 Simon Wilkinson. All rights reserved.
def1de
  *
def1de
  * Redistribution and use in source and binary forms, with or without
def1de
  * modification, are permitted provided that the following conditions
def1de
@@ -120,7 +120,7 @@ ssh_gssapi_krb5_storecreds(ssh_gssapi_client *client)
def1de
 	krb5_error_code problem;
def1de
 	krb5_principal princ;
def1de
 	OM_uint32 maj_status, min_status;
def1de
-	int len;
def1de
+	const char *new_ccname, *new_cctype;
def1de
 	const char *errmsg;
def1de
 
def1de
 	if (client->creds == NULL) {
def1de
@@ -180,11 +180,26 @@ ssh_gssapi_krb5_storecreds(ssh_gssapi_client *client)
def1de
 		return;
def1de
 	}
def1de
 
def1de
-	client->store.filename = xstrdup(krb5_cc_get_name(krb_context, ccache));
def1de
+	new_cctype = krb5_cc_get_type(krb_context, ccache);
def1de
+	new_ccname = krb5_cc_get_name(krb_context, ccache);
def1de
+
def1de
 	client->store.envvar = "KRB5CCNAME";
def1de
-	len = strlen(client->store.filename) + 6;
def1de
-	client->store.envval = xmalloc(len);
def1de
-	snprintf(client->store.envval, len, "FILE:%s", client->store.filename);
def1de
+#ifdef USE_CCAPI
def1de
+	xasprintf(&client->store.envval, "API:%s", new_ccname);
def1de
+	client->store.filename = NULL;
def1de
+#else
def1de
+	if (new_ccname[0] == ':')
def1de
+		new_ccname++;
def1de
+	xasprintf(&client->store.envval, "%s:%s", new_cctype, new_ccname);
def1de
+	if (strcmp(new_cctype, "DIR") == 0) {
def1de
+		char *p;
def1de
+		p = strrchr(client->store.envval, '/');
def1de
+		if (p)
def1de
+			*p = '\0';
def1de
+	}
def1de
+	if ((strcmp(new_cctype, "FILE") == 0) || (strcmp(new_cctype, "DIR") == 0))
def1de
+		client->store.filename = xstrdup(new_ccname);
def1de
+#endif
def1de
 
def1de
 #ifdef USE_PAM
def1de
 	if (options.use_pam)
def1de
@@ -193,9 +208,76 @@ ssh_gssapi_krb5_storecreds(ssh_gssapi_client *client)
def1de
 
def1de
 	krb5_cc_close(krb_context, ccache);
def1de
 
def1de
+	client->store.data = krb_context;
def1de
+
def1de
 	return;
def1de
 }
def1de
 
def1de
+int
def1de
+ssh_gssapi_krb5_updatecreds(ssh_gssapi_ccache *store,
def1de
+    ssh_gssapi_client *client)
def1de
+{
def1de
+	krb5_ccache ccache = NULL;
def1de
+	krb5_principal principal = NULL;
def1de
+	char *name = NULL;
def1de
+	krb5_error_code problem;
def1de
+	OM_uint32 maj_status, min_status;
def1de
+
def1de
+	if ((problem = krb5_cc_resolve(krb_context, store->envval, &ccache))) {
def1de
+                logit("krb5_cc_resolve(): %.100s",
def1de
+                    krb5_get_err_text(krb_context, problem));
def1de
+                return 0;
def1de
+	}
def1de
+
def1de
+	/* Find out who the principal in this cache is */
def1de
+	if ((problem = krb5_cc_get_principal(krb_context, ccache,
def1de
+	    &principal))) {
def1de
+		logit("krb5_cc_get_principal(): %.100s",
def1de
+		    krb5_get_err_text(krb_context, problem));
def1de
+		krb5_cc_close(krb_context, ccache);
def1de
+		return 0;
def1de
+	}
def1de
+
def1de
+	if ((problem = krb5_unparse_name(krb_context, principal, &name))) {
def1de
+		logit("krb5_unparse_name(): %.100s",
def1de
+		    krb5_get_err_text(krb_context, problem));
def1de
+		krb5_free_principal(krb_context, principal);
def1de
+		krb5_cc_close(krb_context, ccache);
def1de
+		return 0;
def1de
+	}
def1de
+
def1de
+
def1de
+	if (strcmp(name,client->exportedname.value)!=0) {
def1de
+		debug("Name in local credentials cache differs. Not storing");
def1de
+		krb5_free_principal(krb_context, principal);
def1de
+		krb5_cc_close(krb_context, ccache);
def1de
+		krb5_free_unparsed_name(krb_context, name);
def1de
+		return 0;
def1de
+	}
def1de
+	krb5_free_unparsed_name(krb_context, name);
def1de
+
def1de
+	/* Name matches, so lets get on with it! */
def1de
+
def1de
+	if ((problem = krb5_cc_initialize(krb_context, ccache, principal))) {
def1de
+		logit("krb5_cc_initialize(): %.100s",
def1de
+		    krb5_get_err_text(krb_context, problem));
def1de
+		krb5_free_principal(krb_context, principal);
def1de
+		krb5_cc_close(krb_context, ccache);
def1de
+		return 0;
def1de
+	}
def1de
+
def1de
+	krb5_free_principal(krb_context, principal);
def1de
+
def1de
+	if ((maj_status = gss_krb5_copy_ccache(&min_status, client->creds,
def1de
+	    ccache))) {
def1de
+		logit("gss_krb5_copy_ccache() failed. Sorry!");
def1de
+		krb5_cc_close(krb_context, ccache);
def1de
+		return 0;
def1de
+	}
def1de
+
def1de
+	return 1;
def1de
+}
def1de
+
def1de
 ssh_gssapi_mech gssapi_kerberos_mech = {
def1de
 	"toWM5Slw5Ew8Mqkay+al2g==",
def1de
 	"Kerberos",
def1de
@@ -203,7 +285,8 @@ ssh_gssapi_mech gssapi_kerberos_mech = {
def1de
 	NULL,
def1de
 	&ssh_gssapi_krb5_userok,
def1de
 	NULL,
def1de
-	&ssh_gssapi_krb5_storecreds
def1de
+	&ssh_gssapi_krb5_storecreds,
def1de
+	&ssh_gssapi_krb5_updatecreds
def1de
 };
def1de
 
def1de
 #endif /* KRB5 */
def1de
diff --git a/gss-serv.c b/gss-serv.c
def1de
index ab3a15f0..6ce56e92 100644
def1de
--- a/gss-serv.c
def1de
+++ b/gss-serv.c
def1de
@@ -1,7 +1,7 @@
def1de
 /* $OpenBSD: gss-serv.c,v 1.31 2018/07/09 21:37:55 markus Exp $ */
def1de
 
def1de
 /*
def1de
- * Copyright (c) 2001-2003 Simon Wilkinson. All rights reserved.
def1de
+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
def1de
  *
def1de
  * Redistribution and use in source and binary forms, with or without
def1de
  * modification, are permitted provided that the following conditions
def1de
@@ -44,17 +44,19 @@
def1de
 #include "session.h"
def1de
 #include "misc.h"
def1de
 #include "servconf.h"
def1de
+#include "uidswap.h"
def1de
 
def1de
 #include "ssh-gss.h"
def1de
+#include "monitor_wrap.h"
def1de
 
def1de
 extern ServerOptions options;
def1de
 
def1de
 static ssh_gssapi_client gssapi_client =
def1de
-    { GSS_C_EMPTY_BUFFER, GSS_C_EMPTY_BUFFER,
def1de
-    GSS_C_NO_CREDENTIAL, NULL, {NULL, NULL, NULL, NULL}};
def1de
+    { GSS_C_EMPTY_BUFFER, GSS_C_EMPTY_BUFFER, GSS_C_NO_CREDENTIAL,
def1de
+    GSS_C_NO_NAME, NULL, {NULL, NULL, NULL, NULL, NULL}, 0, 0};
def1de
 
def1de
 ssh_gssapi_mech gssapi_null_mech =
def1de
-    { NULL, NULL, {0, NULL}, NULL, NULL, NULL, NULL};
def1de
+    { NULL, NULL, {0, NULL}, NULL, NULL, NULL, NULL, NULL};
def1de
 
def1de
 #ifdef KRB5
def1de
 extern ssh_gssapi_mech gssapi_kerberos_mech;
def1de
@@ -140,6 +142,29 @@ ssh_gssapi_server_ctx(Gssctxt **ctx, gss_OID oid)
def1de
 	return (ssh_gssapi_acquire_cred(*ctx));
def1de
 }
def1de
 
def1de
+/* Unprivileged */
def1de
+char *
def1de
+ssh_gssapi_server_mechanisms(void) {
def1de
+	if (supported_oids == NULL)
def1de
+		ssh_gssapi_prepare_supported_oids();
def1de
+	return (ssh_gssapi_kex_mechs(supported_oids,
def1de
+	    &ssh_gssapi_server_check_mech, NULL, NULL,
def1de
+	    options.gss_kex_algorithms));
def1de
+}
def1de
+
def1de
+/* Unprivileged */
def1de
+int
def1de
+ssh_gssapi_server_check_mech(Gssctxt **dum, gss_OID oid, const char *data,
def1de
+    const char *dummy) {
def1de
+	Gssctxt *ctx = NULL;
def1de
+	int res;
def1de
+
def1de
+	res = !GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctx, oid)));
def1de
+	ssh_gssapi_delete_ctx(&ctx;;
def1de
+
def1de
+	return (res);
def1de
+}
def1de
+
def1de
 /* Unprivileged */
def1de
 void
def1de
 ssh_gssapi_supported_oids(gss_OID_set *oidset)
def1de
@@ -150,7 +175,9 @@ ssh_gssapi_supported_oids(gss_OID_set *oidset)
def1de
 	gss_OID_set supported;
def1de
 
def1de
 	gss_create_empty_oid_set(&min_status, oidset);
def1de
-	gss_indicate_mechs(&min_status, &supported);
def1de
+
def1de
+	if (GSS_ERROR(gss_indicate_mechs(&min_status, &supported)))
def1de
+		return;
def1de
 
def1de
 	while (supported_mechs[i]->name != NULL) {
def1de
 		if (GSS_ERROR(gss_test_oid_set_member(&min_status,
def1de
@@ -276,8 +303,48 @@ OM_uint32
def1de
 ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
def1de
 {
def1de
 	int i = 0;
def1de
+	int equal = 0;
def1de
+	gss_name_t new_name = GSS_C_NO_NAME;
def1de
+	gss_buffer_desc ename = GSS_C_EMPTY_BUFFER;
def1de
+
def1de
+	if (options.gss_store_rekey && client->used && ctx->client_creds) {
def1de
+		if (client->mech->oid.length != ctx->oid->length ||
def1de
+		    (memcmp(client->mech->oid.elements,
def1de
+		     ctx->oid->elements, ctx->oid->length) !=0)) {
def1de
+			debug("Rekeyed credentials have different mechanism");
def1de
+			return GSS_S_COMPLETE;
def1de
+		}
def1de
+
def1de
+		if ((ctx->major = gss_inquire_cred_by_mech(&ctx->minor,
def1de
+		    ctx->client_creds, ctx->oid, &new_name,
def1de
+		    NULL, NULL, NULL))) {
def1de
+			ssh_gssapi_error(ctx);
def1de
+			return (ctx->major);
def1de
+		}
def1de
 
def1de
-	gss_buffer_desc ename;
def1de
+		ctx->major = gss_compare_name(&ctx->minor, client->name,
def1de
+		    new_name, &equal);
def1de
+
def1de
+		if (GSS_ERROR(ctx->major)) {
def1de
+			ssh_gssapi_error(ctx);
def1de
+			return (ctx->major);
def1de
+		}
def1de
+
def1de
+		if (!equal) {
def1de
+			debug("Rekeyed credentials have different name");
def1de
+			return GSS_S_COMPLETE;
def1de
+		}
def1de
+
def1de
+		debug("Marking rekeyed credentials for export");
def1de
+
def1de
+		gss_release_name(&ctx->minor, &client->name);
def1de
+		gss_release_cred(&ctx->minor, &client->creds);
def1de
+		client->name = new_name;
def1de
+		client->creds = ctx->client_creds;
def1de
+		ctx->client_creds = GSS_C_NO_CREDENTIAL;
def1de
+		client->updated = 1;
def1de
+		return GSS_S_COMPLETE;
def1de
+	}
def1de
 
def1de
 	client->mech = NULL;
def1de
 
def1de
@@ -292,6 +359,13 @@ ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
def1de
 	if (client->mech == NULL)
def1de
 		return GSS_S_FAILURE;
def1de
 
def1de
+	if (ctx->client_creds &&
def1de
+	    (ctx->major = gss_inquire_cred_by_mech(&ctx->minor,
def1de
+	     ctx->client_creds, ctx->oid, &client->name, NULL, NULL, NULL))) {
def1de
+		ssh_gssapi_error(ctx);
def1de
+		return (ctx->major);
def1de
+	}
def1de
+
def1de
 	if ((ctx->major = gss_display_name(&ctx->minor, ctx->client,
def1de
 	    &client->displayname, NULL))) {
def1de
 		ssh_gssapi_error(ctx);
def1de
@@ -309,6 +383,8 @@ ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
def1de
 		return (ctx->major);
def1de
 	}
def1de
 
def1de
+	gss_release_buffer(&ctx->minor, &ename);
def1de
+
def1de
 	/* We can't copy this structure, so we just move the pointer to it */
def1de
 	client->creds = ctx->client_creds;
def1de
 	ctx->client_creds = GSS_C_NO_CREDENTIAL;
def1de
@@ -319,11 +395,20 @@ ssh_gssapi_getclient(Gssctxt *ctx, ssh_gssapi_client *client)
def1de
 void
def1de
 ssh_gssapi_cleanup_creds(void)
def1de
 {
def1de
-	if (gssapi_client.store.filename != NULL) {
def1de
-		/* Unlink probably isn't sufficient */
def1de
-		debug("removing gssapi cred file\"%s\"",
def1de
-		    gssapi_client.store.filename);
def1de
-		unlink(gssapi_client.store.filename);
def1de
+	krb5_ccache ccache = NULL;
def1de
+	krb5_error_code problem;
def1de
+
def1de
+	if (gssapi_client.store.data != NULL) {
def1de
+		if ((problem = krb5_cc_resolve(gssapi_client.store.data, gssapi_client.store.envval, &ccache))) {
def1de
+			debug("%s: krb5_cc_resolve(): %.100s", __func__,
def1de
+				krb5_get_err_text(gssapi_client.store.data, problem));
def1de
+		} else if ((problem = krb5_cc_destroy(gssapi_client.store.data, ccache))) {
def1de
+			debug("%s: krb5_cc_destroy(): %.100s", __func__,
def1de
+				krb5_get_err_text(gssapi_client.store.data, problem));
def1de
+		} else {
def1de
+			krb5_free_context(gssapi_client.store.data);
def1de
+			gssapi_client.store.data = NULL;
def1de
+		}
def1de
 	}
def1de
 }
def1de
 
def1de
@@ -356,19 +441,23 @@ ssh_gssapi_do_child(char ***envp, u_int *envsizep)
def1de
 
def1de
 /* Privileged */
def1de
 int
def1de
-ssh_gssapi_userok(char *user)
def1de
+ssh_gssapi_userok(char *user, struct passwd *pw, int kex)
def1de
 {
def1de
 	OM_uint32 lmin;
def1de
 
def1de
+	(void) kex; /* used in privilege separation */
def1de
+
def1de
 	if (gssapi_client.exportedname.length == 0 ||
def1de
 	    gssapi_client.exportedname.value == NULL) {
def1de
 		debug("No suitable client data");
def1de
 		return 0;
def1de
 	}
def1de
 	if (gssapi_client.mech && gssapi_client.mech->userok)
def1de
-		if ((*gssapi_client.mech->userok)(&gssapi_client, user))
def1de
+		if ((*gssapi_client.mech->userok)(&gssapi_client, user)) {
def1de
+			gssapi_client.used = 1;
def1de
+			gssapi_client.store.owner = pw;
def1de
 			return 1;
def1de
-		else {
def1de
+		} else {
def1de
 			/* Destroy delegated credentials if userok fails */
def1de
 			gss_release_buffer(&lmin, &gssapi_client.displayname);
def1de
 			gss_release_buffer(&lmin, &gssapi_client.exportedname);
def1de
@@ -382,14 +471,90 @@ ssh_gssapi_userok(char *user)
def1de
 	return (0);
def1de
 }
def1de
 
def1de
-/* Privileged */
def1de
-OM_uint32
def1de
-ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic)
def1de
+/* These bits are only used for rekeying. The unpriviledged child is running
def1de
+ * as the user, the monitor is root.
def1de
+ *
def1de
+ * In the child, we want to :
def1de
+ *    *) Ask the monitor to store our credentials into the store we specify
def1de
+ *    *) If it succeeds, maybe do a PAM update
def1de
+ */
def1de
+
def1de
+/* Stuff for PAM */
def1de
+
def1de
+#ifdef USE_PAM
def1de
+static int ssh_gssapi_simple_conv(int n, const struct pam_message **msg,
def1de
+    struct pam_response **resp, void *data)
def1de
 {
def1de
-	ctx->major = gss_verify_mic(&ctx->minor, ctx->context,
def1de
-	    gssbuf, gssmic, NULL);
def1de
+	return (PAM_CONV_ERR);
def1de
+}
def1de
+#endif
def1de
 
def1de
-	return (ctx->major);
def1de
+void
def1de
+ssh_gssapi_rekey_creds(void) {
def1de
+	int ok;
def1de
+#ifdef USE_PAM
def1de
+	int ret;
def1de
+	pam_handle_t *pamh = NULL;
def1de
+	struct pam_conv pamconv = {ssh_gssapi_simple_conv, NULL};
def1de
+	char *envstr;
def1de
+#endif
def1de
+
def1de
+	if (gssapi_client.store.filename == NULL &&
def1de
+	    gssapi_client.store.envval == NULL &&
def1de
+	    gssapi_client.store.envvar == NULL)
def1de
+		return;
def1de
+
def1de
+	ok = PRIVSEP(ssh_gssapi_update_creds(&gssapi_client.store));
def1de
+
def1de
+	if (!ok)
def1de
+		return;
def1de
+
def1de
+	debug("Rekeyed credentials stored successfully");
def1de
+
def1de
+	/* Actually managing to play with the ssh pam stack from here will
def1de
+	 * be next to impossible. In any case, we may want different options
def1de
+	 * for rekeying. So, use our own :)
def1de
+	 */
def1de
+#ifdef USE_PAM	
def1de
+	if (!use_privsep) {
def1de
+		debug("Not even going to try and do PAM with privsep disabled");
def1de
+		return;
def1de
+	}
def1de
+
def1de
+	ret = pam_start("sshd-rekey", gssapi_client.store.owner->pw_name,
def1de
+ 	    &pamconv, &pamh);
def1de
+	if (ret)
def1de
+		return;
def1de
+
def1de
+	xasprintf(&envstr, "%s=%s", gssapi_client.store.envvar,
def1de
+	    gssapi_client.store.envval);
def1de
+
def1de
+	ret = pam_putenv(pamh, envstr);
def1de
+	if (!ret)
def1de
+		pam_setcred(pamh, PAM_REINITIALIZE_CRED);
def1de
+	pam_end(pamh, PAM_SUCCESS);
def1de
+#endif
def1de
+}
def1de
+
def1de
+int
def1de
+ssh_gssapi_update_creds(ssh_gssapi_ccache *store) {
def1de
+	int ok = 0;
def1de
+
def1de
+	/* Check we've got credentials to store */
def1de
+	if (!gssapi_client.updated)
def1de
+		return 0;
def1de
+
def1de
+	gssapi_client.updated = 0;
def1de
+
def1de
+	temporarily_use_uid(gssapi_client.store.owner);
def1de
+	if (gssapi_client.mech && gssapi_client.mech->updatecreds)
def1de
+		ok = (*gssapi_client.mech->updatecreds)(store, &gssapi_client);
def1de
+	else
def1de
+		debug("No update function for this mechanism");
def1de
+
def1de
+	restore_uid();
def1de
+
def1de
+	return ok;
def1de
 }
def1de
 
def1de
 /* Privileged */
def1de
diff --git a/hmac.c b/hmac.c
def1de
index 1c879640..a29f32c5 100644
def1de
--- a/hmac.c
def1de
+++ b/hmac.c
def1de
@@ -19,6 +19,7 @@
def1de
 
def1de
 #include <sys/types.h>
def1de
 #include <string.h>
def1de
+#include <stdlib.h>
def1de
 
def1de
 #include "sshbuf.h"
def1de
 #include "digest.h"
def1de
diff --git a/kex.c b/kex.c
def1de
index 34808b5c..a2a4794e 100644
def1de
--- a/kex.c
def1de
+++ b/kex.c
def1de
@@ -55,11 +55,16 @@
def1de
 #include "misc.h"
def1de
 #include "dispatch.h"
def1de
 #include "monitor.h"
def1de
+#include "xmalloc.h"
def1de
 
def1de
 #include "ssherr.h"
def1de
 #include "sshbuf.h"
def1de
 #include "digest.h"
def1de
 
def1de
+#ifdef GSSAPI
def1de
+#include "ssh-gss.h"
def1de
+#endif
def1de
+
def1de
 /* prototype */
def1de
 static int kex_choose_conf(struct ssh *);
def1de
 static int kex_input_newkeys(int, u_int32_t, struct ssh *);
def1de
@@ -113,15 +118,28 @@ static const struct kexalg kexalgs[] = {
def1de
 #endif /* HAVE_EVP_SHA256 || !WITH_OPENSSL */
def1de
 	{ NULL, -1, -1, -1},
def1de
 };
def1de
+static const struct kexalg gss_kexalgs[] = {
def1de
+#ifdef GSSAPI
def1de
+	{ KEX_GSS_GEX_SHA1_ID, KEX_GSS_GEX_SHA1, 0, SSH_DIGEST_SHA1 },
def1de
+	{ KEX_GSS_GRP1_SHA1_ID, KEX_GSS_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
def1de
+	{ KEX_GSS_GRP14_SHA1_ID, KEX_GSS_GRP14_SHA1, 0, SSH_DIGEST_SHA1 },
def1de
+	{ KEX_GSS_GRP14_SHA256_ID, KEX_GSS_GRP14_SHA256, 0, SSH_DIGEST_SHA256 },
def1de
+	{ KEX_GSS_GRP16_SHA512_ID, KEX_GSS_GRP16_SHA512, 0, SSH_DIGEST_SHA512 },
def1de
+	{ KEX_GSS_NISTP256_SHA256_ID, KEX_GSS_NISTP256_SHA256,
def1de
+	    NID_X9_62_prime256v1, SSH_DIGEST_SHA256 },
def1de
+	{ KEX_GSS_C25519_SHA256_ID, KEX_GSS_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
def1de
+#endif
def1de
+	{ NULL, -1, -1, -1 },
def1de
+};
def1de
 
def1de
-char *
def1de
-kex_alg_list(char sep)
def1de
+static char *
def1de
+kex_alg_list_internal(char sep, const struct kexalg *algs)
def1de
 {
def1de
 	char *ret = NULL, *tmp;
def1de
 	size_t nlen, rlen = 0;
def1de
 	const struct kexalg *k;
def1de
 
def1de
-	for (k = kexalgs; k->name != NULL; k++) {
def1de
+	for (k = algs; k->name != NULL; k++) {
def1de
 		if (ret != NULL)
def1de
 			ret[rlen++] = sep;
def1de
 		nlen = strlen(k->name);
def1de
@@ -136,6 +154,18 @@ kex_alg_list(char sep)
def1de
 	return ret;
def1de
 }
def1de
 
def1de
+char *
def1de
+kex_alg_list(char sep)
def1de
+{
def1de
+	return kex_alg_list_internal(sep, kexalgs);
def1de
+}
def1de
+
def1de
+char *
def1de
+kex_gss_alg_list(char sep)
def1de
+{
def1de
+	return kex_alg_list_internal(sep, gss_kexalgs);
def1de
+}
def1de
+
def1de
 static const struct kexalg *
def1de
 kex_alg_by_name(const char *name)
def1de
 {
def1de
@@ -145,6 +175,10 @@ kex_alg_by_name(const char *name)
def1de
 		if (strcmp(k->name, name) == 0)
def1de
 			return k;
def1de
 	}
def1de
+	for (k = gss_kexalgs; k->name != NULL; k++) {
def1de
+		if (strncmp(k->name, name, strlen(k->name)) == 0)
def1de
+			return k;
def1de
+	}
def1de
 	return NULL;
def1de
 }
def1de
 
def1de
@@ -301,6 +335,29 @@ kex_assemble_names(char **listp, const char *def, const char *all)
def1de
 	return r;
def1de
 }
def1de
 
def1de
+/* Validate GSS KEX method name list */
def1de
+int
def1de
+kex_gss_names_valid(const char *names)
def1de
+{
def1de
+	char *s, *cp, *p;
def1de
+
def1de
+	if (names == NULL || *names == '\0')
def1de
+		return 0;
def1de
+	s = cp = xstrdup(names);
def1de
+	for ((p = strsep(&cp, ",")); p && *p != '\0';
def1de
+	    (p = strsep(&cp, ","))) {
def1de
+		if (strncmp(p, "gss-", 4) != 0
def1de
+		  || kex_alg_by_name(p) == NULL) {
def1de
+			error("Unsupported KEX algorithm \"%.100s\"", p);
def1de
+			free(s);
def1de
+			return 0;
def1de
+		}
def1de
+	}
def1de
+	debug3("gss kex names ok: [%s]", names);
def1de
+	free(s);
def1de
+	return 1;
def1de
+}
def1de
+
def1de
 /* put algorithm proposal into buffer */
def1de
 int
def1de
 kex_prop2buf(struct sshbuf *b, char *proposal[PROPOSAL_MAX])
def1de
@@ -657,6 +714,9 @@ kex_free(struct kex *kex)
def1de
 	sshbuf_free(kex->server_version);
def1de
 	sshbuf_free(kex->client_pub);
def1de
 	free(kex->session_id);
def1de
+#ifdef GSSAPI
def1de
+	free(kex->gss_host);
def1de
+#endif /* GSSAPI */
def1de
 	free(kex->failed_choice);
def1de
 	free(kex->hostkey_alg);
def1de
 	free(kex->name);
def1de
diff --git a/kex.h b/kex.h
def1de
index 6d446d1c..f95dc02c 100644
def1de
--- a/kex.h
def1de
+++ b/kex.h
def1de
@@ -103,6 +103,15 @@ enum kex_exchange {
def1de
 	KEX_ECDH_SHA2,
def1de
 	KEX_C25519_SHA256,
def1de
 	KEX_KEM_SNTRUP4591761X25519_SHA512,
def1de
+#ifdef GSSAPI
def1de
+	KEX_GSS_GRP1_SHA1,
def1de
+	KEX_GSS_GRP14_SHA1,
def1de
+	KEX_GSS_GRP14_SHA256,
def1de
+	KEX_GSS_GRP16_SHA512,
def1de
+	KEX_GSS_GEX_SHA1,
def1de
+	KEX_GSS_NISTP256_SHA256,
def1de
+	KEX_GSS_C25519_SHA256,
def1de
+#endif
def1de
 	KEX_MAX
def1de
 };
def1de
 
def1de
@@ -154,6 +163,12 @@ struct kex {
def1de
 	u_int	flags;
def1de
 	int	hash_alg;
def1de
 	int	ec_nid;
def1de
+#ifdef GSSAPI
def1de
+	int	gss_deleg_creds;
def1de
+	int	gss_trust_dns;
def1de
+	char    *gss_host;
def1de
+	char	*gss_client;
def1de
+#endif
def1de
 	char	*failed_choice;
def1de
 	int	(*verify_host_key)(struct sshkey *, struct ssh *);
def1de
 	struct sshkey *(*load_host_public_key)(int, int, struct ssh *);
def1de
@@ -175,8 +190,10 @@ struct kex {
def1de
 
def1de
 int	 kex_names_valid(const char *);
def1de
 char	*kex_alg_list(char);
def1de
+char	*kex_gss_alg_list(char);
def1de
 char	*kex_names_cat(const char *, const char *);
def1de
 int	 kex_assemble_names(char **, const char *, const char *);
def1de
+int	 kex_gss_names_valid(const char *);
def1de
 
def1de
 int	 kex_exchange_identification(struct ssh *, int, const char *);
def1de
 
def1de
@@ -203,6 +220,12 @@ int	 kexgex_client(struct ssh *);
def1de
 int	 kexgex_server(struct ssh *);
def1de
 int	 kex_gen_client(struct ssh *);
def1de
 int	 kex_gen_server(struct ssh *);
def1de
+#ifdef GSSAPI
def1de
+int	 kexgssgex_client(struct ssh *);
def1de
+int	 kexgssgex_server(struct ssh *);
def1de
+int	 kexgss_client(struct ssh *);
def1de
+int	 kexgss_server(struct ssh *);
def1de
+#endif
def1de
 
def1de
 int	 kex_dh_keypair(struct kex *);
def1de
 int	 kex_dh_enc(struct kex *, const struct sshbuf *, struct sshbuf **,
def1de
@@ -235,6 +258,12 @@ int	 kexgex_hash(int, const struct sshbuf *, const struct sshbuf *,
def1de
     const BIGNUM *, const u_char *, size_t,
def1de
     u_char *, size_t *);
def1de
 
def1de
+int	 kex_gen_hash(int hash_alg, const struct sshbuf *client_version,
def1de
+    const struct sshbuf *server_version, const struct sshbuf *client_kexinit,
def1de
+    const struct sshbuf *server_kexinit, const struct sshbuf *server_host_key_blob,
def1de
+    const struct sshbuf *client_pub, const struct sshbuf *server_pub,
def1de
+    const struct sshbuf *shared_secret, u_char *hash, size_t *hashlen);
def1de
+
def1de
 void	kexc25519_keygen(u_char key[CURVE25519_SIZE], u_char pub[CURVE25519_SIZE])
def1de
 	__attribute__((__bounded__(__minbytes__, 1, CURVE25519_SIZE)))
def1de
 	__attribute__((__bounded__(__minbytes__, 2, CURVE25519_SIZE)));
def1de
diff --git a/kexdh.c b/kexdh.c
def1de
index 67133e33..edaa4676 100644
def1de
--- a/kexdh.c
def1de
+++ b/kexdh.c
def1de
@@ -48,13 +48,23 @@ kex_dh_keygen(struct kex *kex)
def1de
 {
def1de
 	switch (kex->kex_type) {
def1de
 	case KEX_DH_GRP1_SHA1:
def1de
+#ifdef GSSAPI
def1de
+	case KEX_GSS_GRP1_SHA1:
def1de
+#endif
def1de
 		kex->dh = dh_new_group1();
def1de
 		break;
def1de
 	case KEX_DH_GRP14_SHA1:
def1de
 	case KEX_DH_GRP14_SHA256:
def1de
+#ifdef GSSAPI
def1de
+	case KEX_GSS_GRP14_SHA1:
def1de
+	case KEX_GSS_GRP14_SHA256:
def1de
+#endif
def1de
 		kex->dh = dh_new_group14();
def1de
 		break;
def1de
 	case KEX_DH_GRP16_SHA512:
def1de
+#ifdef GSSAPI
def1de
+	case KEX_GSS_GRP16_SHA512:
def1de
+#endif
def1de
 		kex->dh = dh_new_group16();
def1de
 		break;
def1de
 	case KEX_DH_GRP18_SHA512:
def1de
diff --git a/kexgen.c b/kexgen.c
def1de
index 2abbb9ef..569dc83f 100644
def1de
--- a/kexgen.c
def1de
+++ b/kexgen.c
def1de
@@ -43,7 +43,7 @@
def1de
 static int input_kex_gen_init(int, u_int32_t, struct ssh *);
def1de
 static int input_kex_gen_reply(int type, u_int32_t seq, struct ssh *ssh);
def1de
 
def1de
-static int
def1de
+int
def1de
 kex_gen_hash(
def1de
     int hash_alg,
def1de
     const struct sshbuf *client_version,
def1de
diff --git a/kexgssc.c b/kexgssc.c
def1de
new file mode 100644
def1de
index 00000000..0b2f6a56
def1de
--- /dev/null
def1de
+++ b/kexgssc.c
def1de
@@ -0,0 +1,595 @@
def1de
+/*
def1de
+ * Copyright (c) 2001-2009 Simon Wilkinson. All rights reserved.
def1de
+ *
def1de
+ * Redistribution and use in source and binary forms, with or without
def1de
+ * modification, are permitted provided that the following conditions
def1de
+ * are met:
def1de
+ * 1. Redistributions of source code must retain the above copyright
def1de
+ *    notice, this list of conditions and the following disclaimer.
def1de
+ * 2. Redistributions in binary form must reproduce the above copyright
def1de
+ *    notice, this list of conditions and the following disclaimer in the
def1de
+ *    documentation and/or other materials provided with the distribution.
def1de
+ *
def1de
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR
def1de
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
def1de
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
def1de
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
def1de
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
def1de
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
def1de
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
def1de
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
def1de
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
def1de
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
def1de
+ */
def1de
+
def1de
+#include "includes.h"
def1de
+
def1de
+#if defined(GSSAPI) && defined(WITH_OPENSSL)
def1de
+
def1de
+#include "includes.h"
def1de
+
def1de
+#include <openssl/crypto.h>
def1de
+#include <openssl/bn.h>
def1de
+
def1de
+#include <string.h>
def1de
+
def1de
+#include "xmalloc.h"
def1de
+#include "sshbuf.h"
def1de
+#include "ssh2.h"
def1de
+#include "sshkey.h"
def1de
+#include "cipher.h"
def1de
+#include "kex.h"
def1de
+#include "log.h"
def1de
+#include "packet.h"
def1de
+#include "dh.h"
def1de
+#include "digest.h"
def1de
+#include "ssherr.h"
def1de
+
def1de
+#include "ssh-gss.h"
def1de
+
def1de
+int
def1de
+kexgss_client(struct ssh *ssh)
def1de
+{
def1de
+	struct kex *kex = ssh->kex;
def1de
+	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER,
def1de
+	    recv_tok = GSS_C_EMPTY_BUFFER,
def1de
+	    gssbuf, msg_tok = GSS_C_EMPTY_BUFFER, *token_ptr;
def1de
+	Gssctxt *ctxt;
def1de
+	OM_uint32 maj_status, min_status, ret_flags;
def1de
+	struct sshbuf *server_blob = NULL;
def1de
+	struct sshbuf *shared_secret = NULL;
def1de
+	struct sshbuf *server_host_key_blob = NULL;
def1de
+	struct sshbuf *empty = sshbuf_new();
def1de
+	u_char *msg;
def1de
+	int type = 0;
def1de
+	int first = 1;
def1de
+	u_char hash[SSH_DIGEST_MAX_LENGTH];
def1de
+	size_t hashlen;
def1de
+	u_char c;
def1de
+	int r;
def1de
+
def1de
+	/* Initialise our GSSAPI world */
def1de
+	ssh_gssapi_build_ctx(&ctxt);
def1de
+	if (ssh_gssapi_id_kex(ctxt, kex->name, kex->kex_type)
def1de
+	    == GSS_C_NO_OID)
def1de
+		fatal("Couldn't identify host exchange");
def1de
+
def1de
+	if (ssh_gssapi_import_name(ctxt, kex->gss_host))
def1de
+		fatal("Couldn't import hostname");
def1de
+
def1de
+	if (kex->gss_client &&
def1de
+	    ssh_gssapi_client_identity(ctxt, kex->gss_client))
def1de
+		fatal("Couldn't acquire client credentials");
def1de
+
def1de
+	/* Step 1 */
def1de
+	switch (kex->kex_type) {
def1de
+	case KEX_GSS_GRP1_SHA1:
def1de
+	case KEX_GSS_GRP14_SHA1:
def1de
+	case KEX_GSS_GRP14_SHA256:
def1de
+	case KEX_GSS_GRP16_SHA512:
def1de
+		r = kex_dh_keypair(kex);
def1de
+		break;
def1de
+	case KEX_GSS_NISTP256_SHA256:
def1de
+		r = kex_ecdh_keypair(kex);
def1de
+		break;
def1de
+	case KEX_GSS_C25519_SHA256:
def1de
+		r = kex_c25519_keypair(kex);
def1de
+		break;
def1de
+	default:
def1de
+		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
def1de
+	}
def1de
+	if (r != 0)
def1de
+		return r;
def1de
+
def1de
+	token_ptr = GSS_C_NO_BUFFER;
def1de
+
def1de
+	do {
def1de
+		debug("Calling gss_init_sec_context");
def1de
+
def1de
+		maj_status = ssh_gssapi_init_ctx(ctxt,
def1de
+		    kex->gss_deleg_creds, token_ptr, &send_tok,
def1de
+		    &ret_flags);
def1de
+
def1de
+		if (GSS_ERROR(maj_status)) {
def1de
+			/* XXX Useles code: Missing send? */
def1de
+			if (send_tok.length != 0) {
def1de
+				if ((r = sshpkt_start(ssh,
def1de
+				        SSH2_MSG_KEXGSS_CONTINUE)) != 0 ||
def1de
+				    (r = sshpkt_put_string(ssh, send_tok.value,
def1de
+				        send_tok.length)) != 0)
def1de
+					fatal("sshpkt failed: %s", ssh_err(r));
def1de
+			}
def1de
+			fatal("gss_init_context failed");
def1de
+		}
def1de
+
def1de
+		/* If we've got an old receive buffer get rid of it */
def1de
+		if (token_ptr != GSS_C_NO_BUFFER)
def1de
+			gss_release_buffer(&min_status, &recv_tok);
def1de
+
def1de
+		if (maj_status == GSS_S_COMPLETE) {
def1de
+			/* If mutual state flag is not true, kex fails */
def1de
+			if (!(ret_flags & GSS_C_MUTUAL_FLAG))
def1de
+				fatal("Mutual authentication failed");
def1de
+
def1de
+			/* If integ avail flag is not true kex fails */
def1de
+			if (!(ret_flags & GSS_C_INTEG_FLAG))
def1de
+				fatal("Integrity check failed");
def1de
+		}
def1de
+
def1de
+		/*
def1de
+		 * If we have data to send, then the last message that we
def1de
+		 * received cannot have been a 'complete'.
def1de
+		 */
def1de
+		if (send_tok.length != 0) {
def1de
+			if (first) {
def1de
+				if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_INIT)) != 0 ||
def1de
+				    (r = sshpkt_put_string(ssh, send_tok.value,
def1de
+				        send_tok.length)) != 0 ||
def1de
+				    (r = sshpkt_put_stringb(ssh, kex->client_pub)) != 0)
def1de
+					fatal("failed to construct packet: %s", ssh_err(r));
def1de
+				first = 0;
def1de
+			} else {
def1de
+				if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_CONTINUE)) != 0 ||
def1de
+				    (r = sshpkt_put_string(ssh, send_tok.value,
def1de
+				        send_tok.length)) != 0)
def1de
+					fatal("failed to construct packet: %s", ssh_err(r));
def1de
+			}
def1de
+			if ((r = sshpkt_send(ssh)) != 0)
def1de
+				fatal("failed to send packet: %s", ssh_err(r));
def1de
+			gss_release_buffer(&min_status, &send_tok);
def1de
+
def1de
+			/* If we've sent them data, they should reply */
def1de
+			do {
def1de
+				type = ssh_packet_read(ssh);
def1de
+				if (type == SSH2_MSG_KEXGSS_HOSTKEY) {
def1de
+					debug("Received KEXGSS_HOSTKEY");
def1de
+					if (server_host_key_blob)
def1de
+						fatal("Server host key received more than once");
def1de
+					if ((r = sshpkt_getb_froms(ssh, &server_host_key_blob)) != 0)
def1de
+						fatal("Failed to read server host key: %s", ssh_err(r));
def1de
+				}
def1de
+			} while (type == SSH2_MSG_KEXGSS_HOSTKEY);
def1de
+
def1de
+			switch (type) {
def1de
+			case SSH2_MSG_KEXGSS_CONTINUE:
def1de
+				debug("Received GSSAPI_CONTINUE");
def1de
+				if (maj_status == GSS_S_COMPLETE)
def1de
+					fatal("GSSAPI Continue received from server when complete");
def1de
+				if ((r = ssh_gssapi_sshpkt_get_buffer_desc(ssh,
def1de
+				        &recv_tok)) != 0 ||
def1de
+				    (r = sshpkt_get_end(ssh)) != 0)
def1de
+					fatal("Failed to read token: %s", ssh_err(r));
def1de
+				break;
def1de
+			case SSH2_MSG_KEXGSS_COMPLETE:
def1de
+				debug("Received GSSAPI_COMPLETE");
def1de
+				if (msg_tok.value != NULL)
def1de
+				        fatal("Received GSSAPI_COMPLETE twice?");
def1de
+				if ((r = sshpkt_getb_froms(ssh, &server_blob)) != 0 ||
def1de
+				    (r = ssh_gssapi_sshpkt_get_buffer_desc(ssh,
def1de
+				        &msg_tok)) != 0)
def1de
+					fatal("Failed to read message: %s", ssh_err(r));
def1de
+
def1de
+				/* Is there a token included? */
def1de
+				if ((r = sshpkt_get_u8(ssh, &c)) != 0)
def1de
+					fatal("sshpkt failed: %s", ssh_err(r));
def1de
+				if (c) {
def1de
+					if ((r = ssh_gssapi_sshpkt_get_buffer_desc(
def1de
+					    ssh, &recv_tok)) != 0)
def1de
+						fatal("Failed to read token: %s", ssh_err(r));
def1de
+					/* If we're already complete - protocol error */
def1de
+					if (maj_status == GSS_S_COMPLETE)
def1de
+						sshpkt_disconnect(ssh, "Protocol error: received token when complete");
def1de
+				} else {
def1de
+					/* No token included */
def1de
+					if (maj_status != GSS_S_COMPLETE)
def1de
+						sshpkt_disconnect(ssh, "Protocol error: did not receive final token");
def1de
+				}
def1de
+				if ((r = sshpkt_get_end(ssh)) != 0) {
def1de
+					fatal("Expecting end of packet.");
def1de
+				}
def1de
+				break;
def1de
+			case SSH2_MSG_KEXGSS_ERROR:
def1de
+				debug("Received Error");
def1de
+				if ((r = sshpkt_get_u32(ssh, &maj_status)) != 0 ||
def1de
+				    (r = sshpkt_get_u32(ssh, &min_status)) != 0 ||
def1de
+				    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
def1de
+				    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 || /* lang tag */
def1de
+				    (r = sshpkt_get_end(ssh)) != 0)
def1de
+					fatal("sshpkt_get failed: %s", ssh_err(r));
def1de
+				fatal("GSSAPI Error: \n%.400s", msg);
def1de
+			default:
def1de
+				sshpkt_disconnect(ssh, "Protocol error: didn't expect packet type %d",
def1de
+				    type);
def1de
+			}
def1de
+			token_ptr = &recv_tok;
def1de
+		} else {
def1de
+			/* No data, and not complete */
def1de
+			if (maj_status != GSS_S_COMPLETE)
def1de
+				fatal("Not complete, and no token output");
def1de
+		}
def1de
+	} while (maj_status & GSS_S_CONTINUE_NEEDED);
def1de
+
def1de
+	/*
def1de
+	 * We _must_ have received a COMPLETE message in reply from the
def1de
+	 * server, which will have set server_blob and msg_tok
def1de
+	 */
def1de
+
def1de
+	if (type != SSH2_MSG_KEXGSS_COMPLETE)
def1de
+		fatal("Didn't receive a SSH2_MSG_KEXGSS_COMPLETE when I expected it");
def1de
+
def1de
+	/* compute shared secret */
def1de
+	switch (kex->kex_type) {
def1de
+	case KEX_GSS_GRP1_SHA1:
def1de
+	case KEX_GSS_GRP14_SHA1:
def1de
+	case KEX_GSS_GRP14_SHA256:
def1de
+	case KEX_GSS_GRP16_SHA512:
def1de
+		r = kex_dh_dec(kex, server_blob, &shared_secret);
def1de
+		break;
def1de
+	case KEX_GSS_C25519_SHA256:
def1de
+		if (sshbuf_ptr(server_blob)[sshbuf_len(server_blob)] & 0x80)
def1de
+			fatal("The received key has MSB of last octet set!");
def1de
+		r = kex_c25519_dec(kex, server_blob, &shared_secret);
def1de
+		break;
def1de
+	case KEX_GSS_NISTP256_SHA256:
def1de
+		if (sshbuf_len(server_blob) != 65)
def1de
+			fatal("The received NIST-P256 key did not match"
def1de
+			    "expected length (expected 65, got %zu)", sshbuf_len(server_blob));
def1de
+
def1de
+		if (sshbuf_ptr(server_blob)[0] != POINT_CONVERSION_UNCOMPRESSED)
def1de
+			fatal("The received NIST-P256 key does not have first octet 0x04");
def1de
+
def1de
+		r = kex_ecdh_dec(kex, server_blob, &shared_secret);
def1de
+		break;
def1de
+	default:
def1de
+		r = SSH_ERR_INVALID_ARGUMENT;
def1de
+		break;
def1de
+	}
def1de
+	if (r != 0)
def1de
+		goto out;
def1de
+
def1de
+	hashlen = sizeof(hash);
def1de
+	if ((r = kex_gen_hash(
def1de
+	    kex->hash_alg,
def1de
+	    kex->client_version,
def1de
+	    kex->server_version,
def1de
+	    kex->my,
def1de
+	    kex->peer,
def1de
+	    (server_host_key_blob ? server_host_key_blob : empty),
def1de
+	    kex->client_pub,
def1de
+	    server_blob,
def1de
+	    shared_secret,
def1de
+	    hash, &hashlen)) != 0)
def1de
+		fatal("%s: Unexpected KEX type %d", __func__, kex->kex_type);
def1de
+
def1de
+	gssbuf.value = hash;
def1de
+	gssbuf.length = hashlen;
def1de
+
def1de
+	/* Verify that the hash matches the MIC we just got. */
def1de
+	if (GSS_ERROR(ssh_gssapi_checkmic(ctxt, &gssbuf, &msg_tok)))
def1de
+		sshpkt_disconnect(ssh, "Hash's MIC didn't verify");
def1de
+
def1de
+	gss_release_buffer(&min_status, &msg_tok);
def1de
+
def1de
+	if (kex->gss_deleg_creds)
def1de
+		ssh_gssapi_credentials_updated(ctxt);
def1de
+
def1de
+	if (gss_kex_context == NULL)
def1de
+		gss_kex_context = ctxt;
def1de
+	else
def1de
+		ssh_gssapi_delete_ctx(&ctxt);
def1de
+
def1de
+	if ((r = kex_derive_keys(ssh, hash, hashlen, shared_secret)) == 0)
def1de
+		r = kex_send_newkeys(ssh);
def1de
+
def1de
+out:
def1de
+	explicit_bzero(hash, sizeof(hash));
def1de
+	explicit_bzero(kex->c25519_client_key, sizeof(kex->c25519_client_key));
def1de
+	sshbuf_free(empty);
def1de
+	sshbuf_free(server_host_key_blob);
def1de
+	sshbuf_free(server_blob);
def1de
+	sshbuf_free(shared_secret);
def1de
+	sshbuf_free(kex->client_pub);
def1de
+	kex->client_pub = NULL;
def1de
+	return r;
def1de
+}
def1de
+
def1de
+int
def1de
+kexgssgex_client(struct ssh *ssh)
def1de
+{
def1de
+	struct kex *kex = ssh->kex;
def1de
+	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER,
def1de
+	    recv_tok = GSS_C_EMPTY_BUFFER, gssbuf,
def1de
+            msg_tok = GSS_C_EMPTY_BUFFER, *token_ptr;
def1de
+	Gssctxt *ctxt;
def1de
+	OM_uint32 maj_status, min_status, ret_flags;
def1de
+	struct sshbuf *shared_secret = NULL;
def1de
+	BIGNUM *p = NULL;
def1de
+	BIGNUM *g = NULL;
def1de
+	struct sshbuf *buf = NULL;
def1de
+	struct sshbuf *server_host_key_blob = NULL;
def1de
+	struct sshbuf *server_blob = NULL;
def1de
+	BIGNUM *dh_server_pub = NULL;
def1de
+	u_char *msg;
def1de
+	int type = 0;
def1de
+	int first = 1;
def1de
+	u_char hash[SSH_DIGEST_MAX_LENGTH];
def1de
+	size_t hashlen;
def1de
+	const BIGNUM *pub_key, *dh_p, *dh_g;
def1de
+	int nbits = 0, min = DH_GRP_MIN, max = DH_GRP_MAX;
def1de
+	struct sshbuf *empty = sshbuf_new();
def1de
+	u_char c;
def1de
+	int r;
def1de
+
def1de
+	/* Initialise our GSSAPI world */
def1de
+	ssh_gssapi_build_ctx(&ctxt);
def1de
+	if (ssh_gssapi_id_kex(ctxt, kex->name, kex->kex_type)
def1de
+	    == GSS_C_NO_OID)
def1de
+		fatal("Couldn't identify host exchange");
def1de
+
def1de
+	if (ssh_gssapi_import_name(ctxt, kex->gss_host))
def1de
+		fatal("Couldn't import hostname");
def1de
+
def1de
+	if (kex->gss_client &&
def1de
+	    ssh_gssapi_client_identity(ctxt, kex->gss_client))
def1de
+		fatal("Couldn't acquire client credentials");
def1de
+
def1de
+	debug("Doing group exchange");
def1de
+	nbits = dh_estimate(kex->dh_need * 8);
def1de
+
def1de
+	kex->min = DH_GRP_MIN;
def1de
+	kex->max = DH_GRP_MAX;
def1de
+	kex->nbits = nbits;
def1de
+	if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_GROUPREQ)) != 0 ||
def1de
+	    (r = sshpkt_put_u32(ssh, min)) != 0 ||
def1de
+	    (r = sshpkt_put_u32(ssh, nbits)) != 0 ||
def1de
+	    (r = sshpkt_put_u32(ssh, max)) != 0 ||
def1de
+	    (r = sshpkt_send(ssh)) != 0)
def1de
+		fatal("Failed to construct a packet: %s", ssh_err(r));
def1de
+
def1de
+	if ((r = ssh_packet_read_expect(ssh, SSH2_MSG_KEXGSS_GROUP)) != 0)
def1de
+		fatal("Error: %s", ssh_err(r));
def1de
+
def1de
+	if ((r = sshpkt_get_bignum2(ssh, &p)) != 0 ||
def1de
+	    (r = sshpkt_get_bignum2(ssh, &g)) != 0 ||
def1de
+	    (r = sshpkt_get_end(ssh)) != 0)
def1de
+		fatal("shpkt_get_bignum2 failed: %s", ssh_err(r));
def1de
+
def1de
+	if (BN_num_bits(p) < min || BN_num_bits(p) > max)
def1de
+		fatal("GSSGRP_GEX group out of range: %d !< %d !< %d",
def1de
+		    min, BN_num_bits(p), max);
def1de
+
def1de
+	if ((kex->dh = dh_new_group(g, p)) == NULL)
def1de
+		fatal("dn_new_group() failed");
def1de
+	p = g = NULL; /* belong to kex->dh now */
def1de
+
def1de
+	if ((r = dh_gen_key(kex->dh, kex->we_need * 8)) != 0)
def1de
+		goto out;
def1de
+	DH_get0_key(kex->dh, &pub_key, NULL);
def1de
+
def1de
+	token_ptr = GSS_C_NO_BUFFER;
def1de
+
def1de
+	do {
def1de
+		/* Step 2 - call GSS_Init_sec_context() */
def1de
+		debug("Calling gss_init_sec_context");
def1de
+
def1de
+		maj_status = ssh_gssapi_init_ctx(ctxt,
def1de
+		    kex->gss_deleg_creds, token_ptr, &send_tok,
def1de
+		    &ret_flags);
def1de
+
def1de
+		if (GSS_ERROR(maj_status)) {
def1de
+			/* XXX Useles code: Missing send? */
def1de
+			if (send_tok.length != 0) {
def1de
+				if ((r = sshpkt_start(ssh,
def1de
+				        SSH2_MSG_KEXGSS_CONTINUE)) != 0 ||
def1de
+				    (r = sshpkt_put_string(ssh, send_tok.value,
def1de
+				        send_tok.length)) != 0)
def1de
+					fatal("sshpkt failed: %s", ssh_err(r));
def1de
+			}
def1de
+			fatal("gss_init_context failed");
def1de
+		}
def1de
+
def1de
+		/* If we've got an old receive buffer get rid of it */
def1de
+		if (token_ptr != GSS_C_NO_BUFFER)
def1de
+			gss_release_buffer(&min_status, &recv_tok);
def1de
+
def1de
+		if (maj_status == GSS_S_COMPLETE) {
def1de
+			/* If mutual state flag is not true, kex fails */
def1de
+			if (!(ret_flags & GSS_C_MUTUAL_FLAG))
def1de
+				fatal("Mutual authentication failed");
def1de
+
def1de
+			/* If integ avail flag is not true kex fails */
def1de
+			if (!(ret_flags & GSS_C_INTEG_FLAG))
def1de
+				fatal("Integrity check failed");
def1de
+		}
def1de
+
def1de
+		/*
def1de
+		 * If we have data to send, then the last message that we
def1de
+		 * received cannot have been a 'complete'.
def1de
+		 */
def1de
+		if (send_tok.length != 0) {
def1de
+			if (first) {
def1de
+				if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_INIT)) != 0 ||
def1de
+				    (r = sshpkt_put_string(ssh, send_tok.value,
def1de
+				        send_tok.length)) != 0 ||
def1de
+				    (r = sshpkt_put_bignum2(ssh, pub_key)) != 0)
def1de
+					fatal("sshpkt failed: %s", ssh_err(r));
def1de
+				first = 0;
def1de
+			} else {
def1de
+				if ((r = sshpkt_start(ssh, SSH2_MSG_KEXGSS_CONTINUE)) != 0 ||
def1de
+				    (r = sshpkt_put_string(ssh,send_tok.value,
def1de
+				        send_tok.length)) != 0)
def1de
+					fatal("sshpkt failed: %s", ssh_err(r));
def1de
+			}
def1de
+			if ((r = sshpkt_send(ssh)) != 0)
def1de
+				fatal("sshpkt_send failed: %s", ssh_err(r));
def1de
+			gss_release_buffer(&min_status, &send_tok);
def1de
+
def1de
+			/* If we've sent them data, they should reply */
def1de
+			do {
def1de
+				type = ssh_packet_read(ssh);
def1de
+				if (type == SSH2_MSG_KEXGSS_HOSTKEY) {
def1de
+					debug("Received KEXGSS_HOSTKEY");
def1de
+					if (server_host_key_blob)
def1de
+						fatal("Server host key received more than once");
def1de
+					if ((r = sshpkt_getb_froms(ssh, &server_host_key_blob)) != 0)
def1de
+						fatal("sshpkt failed: %s", ssh_err(r));
def1de
+				}
def1de
+			} while (type == SSH2_MSG_KEXGSS_HOSTKEY);
def1de
+
def1de
+			switch (type) {
def1de
+			case SSH2_MSG_KEXGSS_CONTINUE:
def1de
+				debug("Received GSSAPI_CONTINUE");
def1de
+				if (maj_status == GSS_S_COMPLETE)
def1de
+					fatal("GSSAPI Continue received from server when complete");
def1de
+				if ((r = ssh_gssapi_sshpkt_get_buffer_desc(ssh,
def1de
+				        &recv_tok)) != 0 ||
def1de
+				    (r = sshpkt_get_end(ssh)) != 0)
def1de
+					fatal("sshpkt failed: %s", ssh_err(r));
def1de
+				break;
def1de
+			case SSH2_MSG_KEXGSS_COMPLETE:
def1de
+				debug("Received GSSAPI_COMPLETE");
def1de
+				if (msg_tok.value != NULL)
def1de
+				        fatal("Received GSSAPI_COMPLETE twice?");
def1de
+				if ((r = sshpkt_getb_froms(ssh, &server_blob)) != 0 ||
def1de
+				    (r = ssh_gssapi_sshpkt_get_buffer_desc(ssh,
def1de
+				        &msg_tok)) != 0)
def1de
+					fatal("sshpkt failed: %s", ssh_err(r));
def1de
+
def1de
+				/* Is there a token included? */
def1de
+				if ((r = sshpkt_get_u8(ssh, &c)) != 0)
def1de
+					fatal("sshpkt failed: %s", ssh_err(r));
def1de
+				if (c) {
def1de
+					if ((r = ssh_gssapi_sshpkt_get_buffer_desc(
def1de
+					        ssh, &recv_tok)) != 0 ||
def1de
+					    (r = sshpkt_get_end(ssh)) != 0)
def1de
+						fatal("sshpkt failed: %s", ssh_err(r));
def1de
+					/* If we're already complete - protocol error */
def1de
+					if (maj_status == GSS_S_COMPLETE)
def1de
+						sshpkt_disconnect(ssh, "Protocol error: received token when complete");
def1de
+				} else {
def1de
+					/* No token included */
def1de
+					if (maj_status != GSS_S_COMPLETE)
def1de
+						sshpkt_disconnect(ssh, "Protocol error: did not receive final token");
def1de
+				}
def1de
+				break;
def1de
+			case SSH2_MSG_KEXGSS_ERROR:
def1de
+				debug("Received Error");
def1de
+				if ((r = sshpkt_get_u32(ssh, &maj_status)) != 0 ||
def1de
+				    (r = sshpkt_get_u32(ssh, &min_status)) != 0 ||
def1de
+				    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
def1de
+				    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 || /* lang tag */
def1de
+				    (r = sshpkt_get_end(ssh)) != 0)
def1de
+					fatal("sshpkt failed: %s", ssh_err(r));
def1de
+				fatal("GSSAPI Error: \n%.400s", msg);
def1de
+			default:
def1de
+				sshpkt_disconnect(ssh, "Protocol error: didn't expect packet type %d",
def1de
+				    type);
def1de
+			}
def1de
+			token_ptr = &recv_tok;
def1de
+		} else {
def1de
+			/* No data, and not complete */
def1de
+			if (maj_status != GSS_S_COMPLETE)
def1de
+				fatal("Not complete, and no token output");
def1de
+		}
def1de
+	} while (maj_status & GSS_S_CONTINUE_NEEDED);
def1de
+
def1de
+	/*
def1de
+	 * We _must_ have received a COMPLETE message in reply from the
def1de
+	 * server, which will have set dh_server_pub and msg_tok
def1de
+	 */
def1de
+
def1de
+	if (type != SSH2_MSG_KEXGSS_COMPLETE)
def1de
+		fatal("Didn't receive a SSH2_MSG_KEXGSS_COMPLETE when I expected it");
def1de
+
def1de
+	/* 7. C verifies that the key Q_S is valid */
def1de
+	/* 8. C computes shared secret */
def1de
+	if ((buf = sshbuf_new()) == NULL ||
def1de
+	    (r = sshbuf_put_stringb(buf, server_blob)) != 0 ||
def1de
+	    (r = sshbuf_get_bignum2(buf, &dh_server_pub)) != 0)
def1de
+		goto out;
def1de
+	sshbuf_free(buf);
def1de
+
def1de
+	if ((shared_secret = sshbuf_new()) == NULL) {
def1de
+		r = SSH_ERR_ALLOC_FAIL;
def1de
+		goto out;
def1de
+	}
def1de
+
def1de
+	if ((r = kex_dh_compute_key(kex, dh_server_pub, shared_secret)) != 0)
def1de
+		goto out;
def1de
+
def1de
+	DH_get0_pqg(kex->dh, &dh_p, NULL, &dh_g);
def1de
+	hashlen = sizeof(hash);
def1de
+	if ((r = kexgex_hash(
def1de
+	    kex->hash_alg,
def1de
+	    kex->client_version,
def1de
+	    kex->server_version,
def1de
+	    kex->my,
def1de
+	    kex->peer,
def1de
+	    (server_host_key_blob ? server_host_key_blob : empty),
def1de
+ 	    kex->min, kex->nbits, kex->max,
def1de
+	    dh_p, dh_g,
def1de
+	    pub_key,
def1de
+	    dh_server_pub,
def1de
+	    sshbuf_ptr(shared_secret), sshbuf_len(shared_secret),
def1de
+	    hash, &hashlen)) != 0)
def1de
+		fatal("Failed to calculate hash: %s", ssh_err(r));
def1de
+
def1de
+	gssbuf.value = hash;
def1de
+	gssbuf.length = hashlen;
def1de
+
def1de
+	/* Verify that the hash matches the MIC we just got. */
def1de
+	if (GSS_ERROR(ssh_gssapi_checkmic(ctxt, &gssbuf, &msg_tok)))
def1de
+		sshpkt_disconnect(ssh, "Hash's MIC didn't verify");
def1de
+
def1de
+	gss_release_buffer(&min_status, &msg_tok);
def1de
+
def1de
+	/* save session id */
def1de
+	if (kex->session_id == NULL) {
def1de
+		kex->session_id_len = hashlen;
def1de
+		kex->session_id = xmalloc(kex->session_id_len);
def1de
+		memcpy(kex->session_id, hash, kex->session_id_len);
def1de
+	}
def1de
+
def1de
+	if (kex->gss_deleg_creds)
def1de
+		ssh_gssapi_credentials_updated(ctxt);
def1de
+
def1de
+	if (gss_kex_context == NULL)
def1de
+		gss_kex_context = ctxt;
def1de
+	else