external/openssh: update to 6.8p1.

In preparation for some updates to external/openssh to make it work with
BoringSSL, this change updates the code to a recent version. The current
version (5.9p1) is coming up on four years old now.

  * Confirmed that f5c67b478bef9992de9e9ec91ce10af4f6205e0d matches
    OpenSSH 5.9p1 exactly (save for the removal of the scard
    subdirectory).

  * Downloaded openssh-6.8p1.tar.gz (SHA256:
    3ff64ce73ee124480b5bf767b9830d7d3c03bbcb6abe716b78f0192c37ce160e)
    and verified with PGP signature. (I've verified Damien's key in
    person previously.)

  * Applied changes between f5c67b478bef9992de9e9ec91ce10af4f6205e0d and
    OpenSSH 5.9p1 to 6.8p1 and updated the build as best I can. The
    ugliest change is probably the duplication of umac.c to umac128.c
    because Android conditionally compiles that file twice. See the
    comment in those files.

Change-Id: I63cb07a8118afb5a377f116087a0882914cea486
diff --git a/kex.c b/kex.c
index c65e28f..2a00d28 100644
--- a/kex.c
+++ b/kex.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: kex.c,v 1.86 2010/09/22 05:01:29 djm Exp $ */
+/* $OpenBSD: kex.c,v 1.105 2015/01/30 00:22:25 djm Exp $ */
 /*
  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
  *
@@ -25,7 +25,7 @@
 
 #include "includes.h"
 
-#include <sys/param.h>
+#include <sys/param.h>	/* MAX roundup */
 
 #include <signal.h>
 #include <stdarg.h>
@@ -33,23 +33,29 @@
 #include <stdlib.h>
 #include <string.h>
 
+#ifdef WITH_OPENSSL
 #include <openssl/crypto.h>
+#include <openssl/dh.h>
+#endif
 
-#include "xmalloc.h"
 #include "ssh2.h"
-#include "buffer.h"
 #include "packet.h"
 #include "compat.h"
 #include "cipher.h"
-#include "key.h"
+#include "sshkey.h"
 #include "kex.h"
 #include "log.h"
 #include "mac.h"
 #include "match.h"
+#include "misc.h"
 #include "dispatch.h"
 #include "monitor.h"
 #include "roaming.h"
 
+#include "ssherr.h"
+#include "sshbuf.h"
+#include "digest.h"
+
 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
 # if defined(HAVE_EVP_SHA256)
 # define evp_ssh_sha256 EVP_sha256
@@ -59,8 +65,73 @@
 #endif
 
 /* prototype */
-static void kex_kexinit_finish(Kex *);
-static void kex_choose_conf(Kex *);
+static int kex_choose_conf(struct ssh *);
+static int kex_input_newkeys(int, u_int32_t, void *);
+
+struct kexalg {
+	char *name;
+	u_int type;
+	int ec_nid;
+	int hash_alg;
+};
+static const struct kexalg kexalgs[] = {
+#ifdef WITH_OPENSSL
+	{ KEX_DH1, KEX_DH_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
+	{ KEX_DH14, KEX_DH_GRP14_SHA1, 0, SSH_DIGEST_SHA1 },
+	{ KEX_DHGEX_SHA1, KEX_DH_GEX_SHA1, 0, SSH_DIGEST_SHA1 },
+#ifdef HAVE_EVP_SHA256
+	{ KEX_DHGEX_SHA256, KEX_DH_GEX_SHA256, 0, SSH_DIGEST_SHA256 },
+#endif /* HAVE_EVP_SHA256 */
+#ifdef OPENSSL_HAS_ECC
+	{ KEX_ECDH_SHA2_NISTP256, KEX_ECDH_SHA2,
+	    NID_X9_62_prime256v1, SSH_DIGEST_SHA256 },
+	{ KEX_ECDH_SHA2_NISTP384, KEX_ECDH_SHA2, NID_secp384r1,
+	    SSH_DIGEST_SHA384 },
+# ifdef OPENSSL_HAS_NISTP521
+	{ KEX_ECDH_SHA2_NISTP521, KEX_ECDH_SHA2, NID_secp521r1,
+	    SSH_DIGEST_SHA512 },
+# endif /* OPENSSL_HAS_NISTP521 */
+#endif /* OPENSSL_HAS_ECC */
+#endif /* WITH_OPENSSL */
+#if defined(HAVE_EVP_SHA256) || !defined(WITH_OPENSSL)
+	{ KEX_CURVE25519_SHA256, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
+#endif /* HAVE_EVP_SHA256 || !WITH_OPENSSL */
+	{ NULL, -1, -1, -1},
+};
+
+char *
+kex_alg_list(char sep)
+{
+	char *ret = NULL, *tmp;
+	size_t nlen, rlen = 0;
+	const struct kexalg *k;
+
+	for (k = kexalgs; k->name != NULL; k++) {
+		if (ret != NULL)
+			ret[rlen++] = sep;
+		nlen = strlen(k->name);
+		if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
+			free(ret);
+			return NULL;
+		}
+		ret = tmp;
+		memcpy(ret + rlen, k->name, nlen + 1);
+		rlen += nlen;
+	}
+	return ret;
+}
+
+static const struct kexalg *
+kex_alg_by_name(const char *name)
+{
+	const struct kexalg *k;
+
+	for (k = kexalgs; k->name != NULL; k++) {
+		if (strcmp(k->name, name) == 0)
+			return k;
+	}
+	return NULL;
+}
 
 /* Validate KEX method name list */
 int
@@ -70,258 +141,374 @@
 
 	if (names == NULL || strcmp(names, "") == 0)
 		return 0;
-	s = cp = xstrdup(names);
+	if ((s = cp = strdup(names)) == NULL)
+		return 0;
 	for ((p = strsep(&cp, ",")); p && *p != '\0';
 	    (p = strsep(&cp, ","))) {
-	    	if (strcmp(p, KEX_DHGEX_SHA256) != 0 &&
-		    strcmp(p, KEX_DHGEX_SHA1) != 0 &&
-		    strcmp(p, KEX_DH14) != 0 &&
-		    strcmp(p, KEX_DH1) != 0 &&
-		    (strncmp(p, KEX_ECDH_SHA2_STEM,
-		    sizeof(KEX_ECDH_SHA2_STEM) - 1) != 0 ||
-		    kex_ecdh_name_to_nid(p) == -1)) {
+		if (kex_alg_by_name(p) == NULL) {
 			error("Unsupported KEX algorithm \"%.100s\"", p);
-			xfree(s);
+			free(s);
 			return 0;
 		}
 	}
 	debug3("kex names ok: [%s]", names);
-	xfree(s);
+	free(s);
 	return 1;
 }
 
 /* put algorithm proposal into buffer */
-static void
-kex_prop2buf(Buffer *b, char *proposal[PROPOSAL_MAX])
+int
+kex_prop2buf(struct sshbuf *b, char *proposal[PROPOSAL_MAX])
 {
 	u_int i;
+	int r;
 
-	buffer_clear(b);
+	sshbuf_reset(b);
+
 	/*
 	 * add a dummy cookie, the cookie will be overwritten by
 	 * kex_send_kexinit(), each time a kexinit is set
 	 */
-	for (i = 0; i < KEX_COOKIE_LEN; i++)
-		buffer_put_char(b, 0);
-	for (i = 0; i < PROPOSAL_MAX; i++)
-		buffer_put_cstring(b, proposal[i]);
-	buffer_put_char(b, 0);			/* first_kex_packet_follows */
-	buffer_put_int(b, 0);			/* uint32 reserved */
+	for (i = 0; i < KEX_COOKIE_LEN; i++) {
+		if ((r = sshbuf_put_u8(b, 0)) != 0)
+			return r;
+	}
+	for (i = 0; i < PROPOSAL_MAX; i++) {
+		if ((r = sshbuf_put_cstring(b, proposal[i])) != 0)
+			return r;
+	}
+	if ((r = sshbuf_put_u8(b, 0)) != 0 ||	/* first_kex_packet_follows */
+	    (r = sshbuf_put_u32(b, 0)) != 0)	/* uint32 reserved */
+		return r;
+	return 0;
 }
 
 /* parse buffer and return algorithm proposal */
-static char **
-kex_buf2prop(Buffer *raw, int *first_kex_follows)
+int
+kex_buf2prop(struct sshbuf *raw, int *first_kex_follows, char ***propp)
 {
-	Buffer b;
+	struct sshbuf *b = NULL;
+	u_char v;
 	u_int i;
-	char **proposal;
+	char **proposal = NULL;
+	int r;
 
-	proposal = xcalloc(PROPOSAL_MAX, sizeof(char *));
-
-	buffer_init(&b);
-	buffer_append(&b, buffer_ptr(raw), buffer_len(raw));
-	/* skip cookie */
-	for (i = 0; i < KEX_COOKIE_LEN; i++)
-		buffer_get_char(&b);
+	*propp = NULL;
+	if ((proposal = calloc(PROPOSAL_MAX, sizeof(char *))) == NULL)
+		return SSH_ERR_ALLOC_FAIL;
+	if ((b = sshbuf_fromb(raw)) == NULL) {
+		r = SSH_ERR_ALLOC_FAIL;
+		goto out;
+	}
+	if ((r = sshbuf_consume(b, KEX_COOKIE_LEN)) != 0) /* skip cookie */
+		goto out;
 	/* extract kex init proposal strings */
 	for (i = 0; i < PROPOSAL_MAX; i++) {
-		proposal[i] = buffer_get_cstring(&b,NULL);
+		if ((r = sshbuf_get_cstring(b, &(proposal[i]), NULL)) != 0)
+			goto out;
 		debug2("kex_parse_kexinit: %s", proposal[i]);
 	}
 	/* first kex follows / reserved */
-	i = buffer_get_char(&b);
+	if ((r = sshbuf_get_u8(b, &v)) != 0 ||
+	    (r = sshbuf_get_u32(b, &i)) != 0)
+		goto out;
 	if (first_kex_follows != NULL)
 		*first_kex_follows = i;
-	debug2("kex_parse_kexinit: first_kex_follows %d ", i);
-	i = buffer_get_int(&b);
+	debug2("kex_parse_kexinit: first_kex_follows %d ", v);
 	debug2("kex_parse_kexinit: reserved %u ", i);
-	buffer_free(&b);
-	return proposal;
+	r = 0;
+	*propp = proposal;
+ out:
+	if (r != 0 && proposal != NULL)
+		kex_prop_free(proposal);
+	sshbuf_free(b);
+	return r;
 }
 
-static void
+void
 kex_prop_free(char **proposal)
 {
 	u_int i;
 
 	for (i = 0; i < PROPOSAL_MAX; i++)
-		xfree(proposal[i]);
-	xfree(proposal);
+		free(proposal[i]);
+	free(proposal);
 }
 
 /* ARGSUSED */
-static void
+static int
 kex_protocol_error(int type, u_int32_t seq, void *ctxt)
 {
 	error("Hm, kex protocol error: type %d seq %u", type, seq);
+	return 0;
 }
 
 static void
-kex_reset_dispatch(void)
+kex_reset_dispatch(struct ssh *ssh)
 {
-	dispatch_range(SSH2_MSG_TRANSPORT_MIN,
+	ssh_dispatch_range(ssh, SSH2_MSG_TRANSPORT_MIN,
 	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
-	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
+	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
 }
 
-void
-kex_finish(Kex *kex)
+int
+kex_send_newkeys(struct ssh *ssh)
 {
-	kex_reset_dispatch();
+	int r;
 
-	packet_start(SSH2_MSG_NEWKEYS);
-	packet_send();
-	/* packet_write_wait(); */
+	kex_reset_dispatch(ssh);
+	if ((r = sshpkt_start(ssh, SSH2_MSG_NEWKEYS)) != 0 ||
+	    (r = sshpkt_send(ssh)) != 0)
+		return r;
 	debug("SSH2_MSG_NEWKEYS sent");
-
 	debug("expecting SSH2_MSG_NEWKEYS");
-	packet_read_expect(SSH2_MSG_NEWKEYS);
-	packet_check_eom();
-	debug("SSH2_MSG_NEWKEYS received");
-
-	kex->done = 1;
-	buffer_clear(&kex->peer);
-	/* buffer_clear(&kex->my); */
-	kex->flags &= ~KEX_INIT_SENT;
-	xfree(kex->name);
-	kex->name = NULL;
+	ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_input_newkeys);
+	return 0;
 }
 
-void
-kex_send_kexinit(Kex *kex)
+static int
+kex_input_newkeys(int type, u_int32_t seq, void *ctxt)
 {
-	u_int32_t rnd = 0;
-	u_char *cookie;
-	u_int i;
+	struct ssh *ssh = ctxt;
+	struct kex *kex = ssh->kex;
+	int r;
 
-	if (kex == NULL) {
-		error("kex_send_kexinit: no kex, cannot rekey");
-		return;
-	}
-	if (kex->flags & KEX_INIT_SENT) {
-		debug("KEX_INIT_SENT");
-		return;
-	}
+	debug("SSH2_MSG_NEWKEYS received");
+	ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error);
+	if ((r = sshpkt_get_end(ssh)) != 0)
+		return r;
+	kex->done = 1;
+	sshbuf_reset(kex->peer);
+	/* sshbuf_reset(kex->my); */
+	kex->flags &= ~KEX_INIT_SENT;
+	free(kex->name);
+	kex->name = NULL;
+	return 0;
+}
+
+int
+kex_send_kexinit(struct ssh *ssh)
+{
+	u_char *cookie;
+	struct kex *kex = ssh->kex;
+	int r;
+
+	if (kex == NULL)
+		return SSH_ERR_INTERNAL_ERROR;
+	if (kex->flags & KEX_INIT_SENT)
+		return 0;
 	kex->done = 0;
 
 	/* generate a random cookie */
-	if (buffer_len(&kex->my) < KEX_COOKIE_LEN)
-		fatal("kex_send_kexinit: kex proposal too short");
-	cookie = buffer_ptr(&kex->my);
-	for (i = 0; i < KEX_COOKIE_LEN; i++) {
-		if (i % 4 == 0)
-			rnd = arc4random();
-		cookie[i] = rnd;
-		rnd >>= 8;
-	}
-	packet_start(SSH2_MSG_KEXINIT);
-	packet_put_raw(buffer_ptr(&kex->my), buffer_len(&kex->my));
-	packet_send();
+	if (sshbuf_len(kex->my) < KEX_COOKIE_LEN)
+		return SSH_ERR_INVALID_FORMAT;
+	if ((cookie = sshbuf_mutable_ptr(kex->my)) == NULL)
+		return SSH_ERR_INTERNAL_ERROR;
+	arc4random_buf(cookie, KEX_COOKIE_LEN);
+
+	if ((r = sshpkt_start(ssh, SSH2_MSG_KEXINIT)) != 0 ||
+	    (r = sshpkt_putb(ssh, kex->my)) != 0 ||
+	    (r = sshpkt_send(ssh)) != 0)
+		return r;
 	debug("SSH2_MSG_KEXINIT sent");
 	kex->flags |= KEX_INIT_SENT;
+	return 0;
 }
 
 /* ARGSUSED */
-void
+int
 kex_input_kexinit(int type, u_int32_t seq, void *ctxt)
 {
-	char *ptr;
-	u_int i, dlen;
-	Kex *kex = (Kex *)ctxt;
+	struct ssh *ssh = ctxt;
+	struct kex *kex = ssh->kex;
+	const u_char *ptr;
+	u_int i;
+	size_t dlen;
+	int r;
 
 	debug("SSH2_MSG_KEXINIT received");
 	if (kex == NULL)
-		fatal("kex_input_kexinit: no kex, cannot rekey");
+		return SSH_ERR_INVALID_ARGUMENT;
 
-	ptr = packet_get_raw(&dlen);
-	buffer_append(&kex->peer, ptr, dlen);
+	ptr = sshpkt_ptr(ssh, &dlen);
+	if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0)
+		return r;
 
 	/* discard packet */
 	for (i = 0; i < KEX_COOKIE_LEN; i++)
-		packet_get_char();
+		if ((r = sshpkt_get_u8(ssh, NULL)) != 0)
+			return r;
 	for (i = 0; i < PROPOSAL_MAX; i++)
-		xfree(packet_get_string(NULL));
-	(void) packet_get_char();
-	(void) packet_get_int();
-	packet_check_eom();
+		if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0)
+			return r;
+	/*
+	 * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
+	 * KEX method has the server move first, but a server might be using
+	 * a custom method or one that we otherwise don't support. We should
+	 * be prepared to remember first_kex_follows here so we can eat a
+	 * packet later.
+	 * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
+	 * for cases where the server *doesn't* go first. I guess we should
+	 * ignore it when it is set for these cases, which is what we do now.
+	 */
+	if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||	/* first_kex_follows */
+	    (r = sshpkt_get_u32(ssh, NULL)) != 0 ||	/* reserved */
+	    (r = sshpkt_get_end(ssh)) != 0)
+			return r;
 
-	kex_kexinit_finish(kex);
-}
-
-Kex *
-kex_setup(char *proposal[PROPOSAL_MAX])
-{
-	Kex *kex;
-
-	kex = xcalloc(1, sizeof(*kex));
-	buffer_init(&kex->peer);
-	buffer_init(&kex->my);
-	kex_prop2buf(&kex->my, proposal);
-	kex->done = 0;
-
-	kex_send_kexinit(kex);					/* we start */
-	kex_reset_dispatch();
-
-	return kex;
-}
-
-static void
-kex_kexinit_finish(Kex *kex)
-{
 	if (!(kex->flags & KEX_INIT_SENT))
-		kex_send_kexinit(kex);
+		if ((r = kex_send_kexinit(ssh)) != 0)
+			return r;
+	if ((r = kex_choose_conf(ssh)) != 0)
+		return r;
 
-	kex_choose_conf(kex);
+	if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL)
+		return (kex->kex[kex->kex_type])(ssh);
 
-	if (kex->kex_type >= 0 && kex->kex_type < KEX_MAX &&
-	    kex->kex[kex->kex_type] != NULL) {
-		(kex->kex[kex->kex_type])(kex);
-	} else {
-		fatal("Unsupported key exchange %d", kex->kex_type);
-	}
+	return SSH_ERR_INTERNAL_ERROR;
 }
 
-static void
-choose_enc(Enc *enc, char *client, char *server)
+int
+kex_new(struct ssh *ssh, char *proposal[PROPOSAL_MAX], struct kex **kexp)
+{
+	struct kex *kex;
+	int r;
+
+	*kexp = NULL;
+	if ((kex = calloc(1, sizeof(*kex))) == NULL)
+		return SSH_ERR_ALLOC_FAIL;
+	if ((kex->peer = sshbuf_new()) == NULL ||
+	    (kex->my = sshbuf_new()) == NULL) {
+		r = SSH_ERR_ALLOC_FAIL;
+		goto out;
+	}
+	if ((r = kex_prop2buf(kex->my, proposal)) != 0)
+		goto out;
+	kex->done = 0;
+	kex_reset_dispatch(ssh);
+	r = 0;
+	*kexp = kex;
+ out:
+	if (r != 0)
+		kex_free(kex);
+	return r;
+}
+
+void
+kex_free_newkeys(struct newkeys *newkeys)
+{
+	if (newkeys == NULL)
+		return;
+	if (newkeys->enc.key) {
+		explicit_bzero(newkeys->enc.key, newkeys->enc.key_len);
+		free(newkeys->enc.key);
+		newkeys->enc.key = NULL;
+	}
+	if (newkeys->enc.iv) {
+		explicit_bzero(newkeys->enc.iv, newkeys->enc.block_size);
+		free(newkeys->enc.iv);
+		newkeys->enc.iv = NULL;
+	}
+	free(newkeys->enc.name);
+	explicit_bzero(&newkeys->enc, sizeof(newkeys->enc));
+	free(newkeys->comp.name);
+	explicit_bzero(&newkeys->comp, sizeof(newkeys->comp));
+	mac_clear(&newkeys->mac);
+	if (newkeys->mac.key) {
+		explicit_bzero(newkeys->mac.key, newkeys->mac.key_len);
+		free(newkeys->mac.key);
+		newkeys->mac.key = NULL;
+	}
+	free(newkeys->mac.name);
+	explicit_bzero(&newkeys->mac, sizeof(newkeys->mac));
+	explicit_bzero(newkeys, sizeof(*newkeys));
+	free(newkeys);
+}
+
+void
+kex_free(struct kex *kex)
+{
+	u_int mode;
+
+#ifdef WITH_OPENSSL
+	if (kex->dh)
+		DH_free(kex->dh);
+#ifdef OPENSSL_HAS_ECC
+	if (kex->ec_client_key)
+		EC_KEY_free(kex->ec_client_key);
+#endif /* OPENSSL_HAS_ECC */
+#endif /* WITH_OPENSSL */
+	for (mode = 0; mode < MODE_MAX; mode++) {
+		kex_free_newkeys(kex->newkeys[mode]);
+		kex->newkeys[mode] = NULL;
+	}
+	sshbuf_free(kex->peer);
+	sshbuf_free(kex->my);
+	free(kex->session_id);
+	free(kex->client_version_string);
+	free(kex->server_version_string);
+	free(kex);
+}
+
+int
+kex_setup(struct ssh *ssh, char *proposal[PROPOSAL_MAX])
+{
+	int r;
+
+	if ((r = kex_new(ssh, proposal, &ssh->kex)) != 0)
+		return r;
+	if ((r = kex_send_kexinit(ssh)) != 0) {		/* we start */
+		kex_free(ssh->kex);
+		ssh->kex = NULL;
+		return r;
+	}
+	return 0;
+}
+
+static int
+choose_enc(struct sshenc *enc, char *client, char *server)
 {
 	char *name = match_list(client, server, NULL);
+
 	if (name == NULL)
-		fatal("no matching cipher found: client %s server %s",
-		    client, server);
+		return SSH_ERR_NO_CIPHER_ALG_MATCH;
 	if ((enc->cipher = cipher_by_name(name)) == NULL)
-		fatal("matching cipher is not supported: %s", name);
+		return SSH_ERR_INTERNAL_ERROR;
 	enc->name = name;
 	enc->enabled = 0;
 	enc->iv = NULL;
+	enc->iv_len = cipher_ivlen(enc->cipher);
 	enc->key = NULL;
 	enc->key_len = cipher_keylen(enc->cipher);
 	enc->block_size = cipher_blocksize(enc->cipher);
+	return 0;
 }
 
-static void
-choose_mac(Mac *mac, char *client, char *server)
+static int
+choose_mac(struct ssh *ssh, struct sshmac *mac, char *client, char *server)
 {
 	char *name = match_list(client, server, NULL);
+
 	if (name == NULL)
-		fatal("no matching mac found: client %s server %s",
-		    client, server);
+		return SSH_ERR_NO_MAC_ALG_MATCH;
 	if (mac_setup(mac, name) < 0)
-		fatal("unsupported mac %s", name);
+		return SSH_ERR_INTERNAL_ERROR;
 	/* truncate the key */
-	if (datafellows & SSH_BUG_HMAC)
+	if (ssh->compat & SSH_BUG_HMAC)
 		mac->key_len = 16;
 	mac->name = name;
 	mac->key = NULL;
 	mac->enabled = 0;
+	return 0;
 }
 
-static void
-choose_comp(Comp *comp, char *client, char *server)
+static int
+choose_comp(struct sshcomp *comp, char *client, char *server)
 {
 	char *name = match_list(client, server, NULL);
+
 	if (name == NULL)
-		fatal("no matching comp found: client %s server %s", client, server);
+		return SSH_ERR_NO_COMPRESS_ALG_MATCH;
 	if (strcmp(name, "zlib@openssh.com") == 0) {
 		comp->type = COMP_DELAYED;
 	} else if (strcmp(name, "zlib") == 0) {
@@ -329,49 +516,42 @@
 	} else if (strcmp(name, "none") == 0) {
 		comp->type = COMP_NONE;
 	} else {
-		fatal("unsupported comp %s", name);
+		return SSH_ERR_INTERNAL_ERROR;
 	}
 	comp->name = name;
+	return 0;
 }
 
-static void
-choose_kex(Kex *k, char *client, char *server)
+static int
+choose_kex(struct kex *k, char *client, char *server)
 {
+	const struct kexalg *kexalg;
+
 	k->name = match_list(client, server, NULL);
+
 	if (k->name == NULL)
-		fatal("Unable to negotiate a key exchange method");
-	if (strcmp(k->name, KEX_DH1) == 0) {
-		k->kex_type = KEX_DH_GRP1_SHA1;
-		k->evp_md = EVP_sha1();
-	} else if (strcmp(k->name, KEX_DH14) == 0) {
-		k->kex_type = KEX_DH_GRP14_SHA1;
-		k->evp_md = EVP_sha1();
-	} else if (strcmp(k->name, KEX_DHGEX_SHA1) == 0) {
-		k->kex_type = KEX_DH_GEX_SHA1;
-		k->evp_md = EVP_sha1();
-#if OPENSSL_VERSION_NUMBER >= 0x00907000L
-	} else if (strcmp(k->name, KEX_DHGEX_SHA256) == 0) {
-		k->kex_type = KEX_DH_GEX_SHA256;
-		k->evp_md = evp_ssh_sha256();
-	} else if (strncmp(k->name, KEX_ECDH_SHA2_STEM,
-	    sizeof(KEX_ECDH_SHA2_STEM) - 1) == 0) {
- 		k->kex_type = KEX_ECDH_SHA2;
-		k->evp_md = kex_ecdh_name_to_evpmd(k->name);
-#endif
-	} else
-		fatal("bad kex alg %s", k->name);
+		return SSH_ERR_NO_KEX_ALG_MATCH;
+	if ((kexalg = kex_alg_by_name(k->name)) == NULL)
+		return SSH_ERR_INTERNAL_ERROR;
+	k->kex_type = kexalg->type;
+	k->hash_alg = kexalg->hash_alg;
+	k->ec_nid = kexalg->ec_nid;
+	return 0;
 }
 
-static void
-choose_hostkeyalg(Kex *k, char *client, char *server)
+static int
+choose_hostkeyalg(struct kex *k, char *client, char *server)
 {
 	char *hostkeyalg = match_list(client, server, NULL);
+
 	if (hostkeyalg == NULL)
-		fatal("no hostkey alg");
-	k->hostkey_type = key_type_from_name(hostkeyalg);
+		return SSH_ERR_NO_HOSTKEY_ALG_MATCH;
+	k->hostkey_type = sshkey_type_from_name(hostkeyalg);
 	if (k->hostkey_type == KEY_UNSPEC)
-		fatal("bad hostkey alg '%s'", hostkeyalg);
-	xfree(hostkeyalg);
+		return SSH_ERR_INTERNAL_ERROR;
+	k->hostkey_nid = sshkey_ecdsa_nid_from_name(hostkeyalg);
+	free(hostkeyalg);
+	return 0;
 }
 
 static int
@@ -398,18 +578,20 @@
 	return (1);
 }
 
-static void
-kex_choose_conf(Kex *kex)
+static int
+kex_choose_conf(struct ssh *ssh)
 {
-	Newkeys *newkeys;
-	char **my, **peer;
+	struct kex *kex = ssh->kex;
+	struct newkeys *newkeys;
+	char **my = NULL, **peer = NULL;
 	char **cprop, **sprop;
 	int nenc, nmac, ncomp;
-	u_int mode, ctos, need;
-	int first_kex_follows, type;
+	u_int mode, ctos, need, dh_need, authlen;
+	int r, first_kex_follows;
 
-	my   = kex_buf2prop(&kex->my, NULL);
-	peer = kex_buf2prop(&kex->peer, &first_kex_follows);
+	if ((r = kex_buf2prop(kex->my, NULL, &my)) != 0 ||
+	    (r = kex_buf2prop(kex->peer, &first_kex_follows, &peer)) != 0)
+		goto out;
 
 	if (kex->server) {
 		cprop=peer;
@@ -421,85 +603,109 @@
 
 	/* Check whether server offers roaming */
 	if (!kex->server) {
-		char *roaming;
-		roaming = match_list(KEX_RESUME, peer[PROPOSAL_KEX_ALGS], NULL);
+		char *roaming = match_list(KEX_RESUME,
+		    peer[PROPOSAL_KEX_ALGS], NULL);
+
 		if (roaming) {
 			kex->roaming = 1;
-			xfree(roaming);
+			free(roaming);
 		}
 	}
 
 	/* Algorithm Negotiation */
 	for (mode = 0; mode < MODE_MAX; mode++) {
-		newkeys = xcalloc(1, sizeof(*newkeys));
+		if ((newkeys = calloc(1, sizeof(*newkeys))) == NULL) {
+			r = SSH_ERR_ALLOC_FAIL;
+			goto out;
+		}
 		kex->newkeys[mode] = newkeys;
 		ctos = (!kex->server && mode == MODE_OUT) ||
 		    (kex->server && mode == MODE_IN);
 		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
 		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
 		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
-		choose_enc (&newkeys->enc,  cprop[nenc],  sprop[nenc]);
-		choose_mac (&newkeys->mac,  cprop[nmac],  sprop[nmac]);
-		choose_comp(&newkeys->comp, cprop[ncomp], sprop[ncomp]);
+		if ((r = choose_enc(&newkeys->enc, cprop[nenc],
+		    sprop[nenc])) != 0)
+			goto out;
+		authlen = cipher_authlen(newkeys->enc.cipher);
+		/* ignore mac for authenticated encryption */
+		if (authlen == 0 &&
+		    (r = choose_mac(ssh, &newkeys->mac, cprop[nmac],
+		    sprop[nmac])) != 0)
+			goto out;
+		if ((r = choose_comp(&newkeys->comp, cprop[ncomp],
+		    sprop[ncomp])) != 0)
+			goto out;
 		debug("kex: %s %s %s %s",
 		    ctos ? "client->server" : "server->client",
 		    newkeys->enc.name,
-		    newkeys->mac.name,
+		    authlen == 0 ? newkeys->mac.name : "<implicit>",
 		    newkeys->comp.name);
 	}
-	choose_kex(kex, cprop[PROPOSAL_KEX_ALGS], sprop[PROPOSAL_KEX_ALGS]);
-	choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
-	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS]);
-	need = 0;
+	if ((r = choose_kex(kex, cprop[PROPOSAL_KEX_ALGS],
+	    sprop[PROPOSAL_KEX_ALGS])) != 0 ||
+	    (r = choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
+	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS])) != 0)
+		goto out;
+	need = dh_need = 0;
 	for (mode = 0; mode < MODE_MAX; mode++) {
 		newkeys = kex->newkeys[mode];
-		if (need < newkeys->enc.key_len)
-			need = newkeys->enc.key_len;
-		if (need < newkeys->enc.block_size)
-			need = newkeys->enc.block_size;
-		if (need < newkeys->mac.key_len)
-			need = newkeys->mac.key_len;
+		need = MAX(need, newkeys->enc.key_len);
+		need = MAX(need, newkeys->enc.block_size);
+		need = MAX(need, newkeys->enc.iv_len);
+		need = MAX(need, newkeys->mac.key_len);
+		dh_need = MAX(dh_need, cipher_seclen(newkeys->enc.cipher));
+		dh_need = MAX(dh_need, newkeys->enc.block_size);
+		dh_need = MAX(dh_need, newkeys->enc.iv_len);
+		dh_need = MAX(dh_need, newkeys->mac.key_len);
 	}
 	/* XXX need runden? */
 	kex->we_need = need;
+	kex->dh_need = dh_need;
 
 	/* ignore the next message if the proposals do not match */
 	if (first_kex_follows && !proposals_match(my, peer) &&
-	    !(datafellows & SSH_BUG_FIRSTKEX)) {
-		type = packet_read();
-		debug2("skipping next packet (type %u)", type);
-	}
-
+	    !(ssh->compat & SSH_BUG_FIRSTKEX))
+		ssh->dispatch_skip_packets = 1;
+	r = 0;
+ out:
 	kex_prop_free(my);
 	kex_prop_free(peer);
+	return r;
 }
 
-static u_char *
-derive_key(Kex *kex, int id, u_int need, u_char *hash, u_int hashlen,
-    BIGNUM *shared_secret)
+static int
+derive_key(struct ssh *ssh, int id, u_int need, u_char *hash, u_int hashlen,
+    const struct sshbuf *shared_secret, u_char **keyp)
 {
-	Buffer b;
-	EVP_MD_CTX md;
+	struct kex *kex = ssh->kex;
+	struct ssh_digest_ctx *hashctx = NULL;
 	char c = id;
 	u_int have;
-	int mdsz;
+	size_t mdsz;
 	u_char *digest;
+	int r;
 
-	if ((mdsz = EVP_MD_size(kex->evp_md)) <= 0)
-		fatal("bad kex md size %d", mdsz);
-	digest = xmalloc(roundup(need, mdsz));
-
-	buffer_init(&b);
-	buffer_put_bignum2(&b, shared_secret);
+	if ((mdsz = ssh_digest_bytes(kex->hash_alg)) == 0)
+		return SSH_ERR_INVALID_ARGUMENT;
+	if ((digest = calloc(1, roundup(need, mdsz))) == NULL) {
+		r = SSH_ERR_ALLOC_FAIL;
+		goto out;
+	}
 
 	/* K1 = HASH(K || H || "A" || session_id) */
-	EVP_DigestInit(&md, kex->evp_md);
-	if (!(datafellows & SSH_BUG_DERIVEKEY))
-		EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
-	EVP_DigestUpdate(&md, hash, hashlen);
-	EVP_DigestUpdate(&md, &c, 1);
-	EVP_DigestUpdate(&md, kex->session_id, kex->session_id_len);
-	EVP_DigestFinal(&md, digest, NULL);
+	if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
+	    ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
+	    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
+	    ssh_digest_update(hashctx, &c, 1) != 0 ||
+	    ssh_digest_update(hashctx, kex->session_id,
+	    kex->session_id_len) != 0 ||
+	    ssh_digest_final(hashctx, digest, mdsz) != 0) {
+		r = SSH_ERR_LIBCRYPTO_ERROR;
+		goto out;
+	}
+	ssh_digest_free(hashctx);
+	hashctx = NULL;
 
 	/*
 	 * expand key:
@@ -507,104 +713,123 @@
 	 * Key = K1 || K2 || ... || Kn
 	 */
 	for (have = mdsz; need > have; have += mdsz) {
-		EVP_DigestInit(&md, kex->evp_md);
-		if (!(datafellows & SSH_BUG_DERIVEKEY))
-			EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
-		EVP_DigestUpdate(&md, hash, hashlen);
-		EVP_DigestUpdate(&md, digest, have);
-		EVP_DigestFinal(&md, digest + have, NULL);
+		if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
+		    ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
+		    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
+		    ssh_digest_update(hashctx, digest, have) != 0 ||
+		    ssh_digest_final(hashctx, digest + have, mdsz) != 0) {
+			r = SSH_ERR_LIBCRYPTO_ERROR;
+			goto out;
+		}
+		ssh_digest_free(hashctx);
+		hashctx = NULL;
 	}
-	buffer_free(&b);
 #ifdef DEBUG_KEX
 	fprintf(stderr, "key '%c'== ", c);
 	dump_digest("key", digest, need);
 #endif
-	return digest;
+	*keyp = digest;
+	digest = NULL;
+	r = 0;
+ out:
+	if (digest)
+		free(digest);
+	ssh_digest_free(hashctx);
+	return r;
 }
 
-Newkeys *current_keys[MODE_MAX];
-
 #define NKEYS	6
-void
-kex_derive_keys(Kex *kex, u_char *hash, u_int hashlen, BIGNUM *shared_secret)
+int
+kex_derive_keys(struct ssh *ssh, u_char *hash, u_int hashlen,
+    const struct sshbuf *shared_secret)
 {
+	struct kex *kex = ssh->kex;
 	u_char *keys[NKEYS];
-	u_int i, mode, ctos;
+	u_int i, j, mode, ctos;
+	int r;
 
 	for (i = 0; i < NKEYS; i++) {
-		keys[i] = derive_key(kex, 'A'+i, kex->we_need, hash, hashlen,
-		    shared_secret);
+		if ((r = derive_key(ssh, 'A'+i, kex->we_need, hash, hashlen,
+		    shared_secret, &keys[i])) != 0) {
+			for (j = 0; j < i; j++)
+				free(keys[j]);
+			return r;
+		}
 	}
-
-	debug2("kex_derive_keys");
 	for (mode = 0; mode < MODE_MAX; mode++) {
-		current_keys[mode] = kex->newkeys[mode];
-		kex->newkeys[mode] = NULL;
 		ctos = (!kex->server && mode == MODE_OUT) ||
 		    (kex->server && mode == MODE_IN);
-		current_keys[mode]->enc.iv  = keys[ctos ? 0 : 1];
-		current_keys[mode]->enc.key = keys[ctos ? 2 : 3];
-		current_keys[mode]->mac.key = keys[ctos ? 4 : 5];
+		kex->newkeys[mode]->enc.iv  = keys[ctos ? 0 : 1];
+		kex->newkeys[mode]->enc.key = keys[ctos ? 2 : 3];
+		kex->newkeys[mode]->mac.key = keys[ctos ? 4 : 5];
 	}
+	return 0;
 }
 
-Newkeys *
-kex_get_newkeys(int mode)
+#ifdef WITH_OPENSSL
+int
+kex_derive_keys_bn(struct ssh *ssh, u_char *hash, u_int hashlen,
+    const BIGNUM *secret)
 {
-	Newkeys *ret;
+	struct sshbuf *shared_secret;
+	int r;
 
-	ret = current_keys[mode];
-	current_keys[mode] = NULL;
-	return ret;
+	if ((shared_secret = sshbuf_new()) == NULL)
+		return SSH_ERR_ALLOC_FAIL;
+	if ((r = sshbuf_put_bignum2(shared_secret, secret)) == 0)
+		r = kex_derive_keys(ssh, hash, hashlen, shared_secret);
+	sshbuf_free(shared_secret);
+	return r;
 }
+#endif
 
-void
+#ifdef WITH_SSH1
+int
 derive_ssh1_session_id(BIGNUM *host_modulus, BIGNUM *server_modulus,
     u_int8_t cookie[8], u_int8_t id[16])
 {
-	const EVP_MD *evp_md = EVP_md5();
-	EVP_MD_CTX md;
-	u_int8_t nbuf[2048], obuf[EVP_MAX_MD_SIZE];
-	int len;
+	u_int8_t hbuf[2048], sbuf[2048], obuf[SSH_DIGEST_MAX_LENGTH];
+	struct ssh_digest_ctx *hashctx = NULL;
+	size_t hlen, slen;
+	int r;
 
-	EVP_DigestInit(&md, evp_md);
-
-	len = BN_num_bytes(host_modulus);
-	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
-		fatal("%s: bad host modulus (len %d)", __func__, len);
-	BN_bn2bin(host_modulus, nbuf);
-	EVP_DigestUpdate(&md, nbuf, len);
-
-	len = BN_num_bytes(server_modulus);
-	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
-		fatal("%s: bad server modulus (len %d)", __func__, len);
-	BN_bn2bin(server_modulus, nbuf);
-	EVP_DigestUpdate(&md, nbuf, len);
-
-	EVP_DigestUpdate(&md, cookie, 8);
-
-	EVP_DigestFinal(&md, obuf, NULL);
-	memcpy(id, obuf, 16);
-
-	memset(nbuf, 0, sizeof(nbuf));
-	memset(obuf, 0, sizeof(obuf));
-	memset(&md, 0, sizeof(md));
+	hlen = BN_num_bytes(host_modulus);
+	slen = BN_num_bytes(server_modulus);
+	if (hlen < (512 / 8) || (u_int)hlen > sizeof(hbuf) ||
+	    slen < (512 / 8) || (u_int)slen > sizeof(sbuf))
+		return SSH_ERR_KEY_BITS_MISMATCH;
+	if (BN_bn2bin(host_modulus, hbuf) <= 0 ||
+	    BN_bn2bin(server_modulus, sbuf) <= 0) {
+		r = SSH_ERR_LIBCRYPTO_ERROR;
+		goto out;
+	}
+	if ((hashctx = ssh_digest_start(SSH_DIGEST_MD5)) == NULL) {
+		r = SSH_ERR_ALLOC_FAIL;
+		goto out;
+	}
+	if (ssh_digest_update(hashctx, hbuf, hlen) != 0 ||
+	    ssh_digest_update(hashctx, sbuf, slen) != 0 ||
+	    ssh_digest_update(hashctx, cookie, 8) != 0 ||
+	    ssh_digest_final(hashctx, obuf, sizeof(obuf)) != 0) {
+		r = SSH_ERR_LIBCRYPTO_ERROR;
+		goto out;
+	}
+	memcpy(id, obuf, ssh_digest_bytes(SSH_DIGEST_MD5));
+	r = 0;
+ out:
+	ssh_digest_free(hashctx);
+	explicit_bzero(hbuf, sizeof(hbuf));
+	explicit_bzero(sbuf, sizeof(sbuf));
+	explicit_bzero(obuf, sizeof(obuf));
+	return r;
 }
+#endif
 
 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
 void
 dump_digest(char *msg, u_char *digest, int len)
 {
-	int i;
-
 	fprintf(stderr, "%s\n", msg);
-	for (i = 0; i < len; i++) {
-		fprintf(stderr, "%02x", digest[i]);
-		if (i%32 == 31)
-			fprintf(stderr, "\n");
-		else if (i%8 == 7)
-			fprintf(stderr, " ");
-	}
-	fprintf(stderr, "\n");
+	sshbuf_dump_data(digest, len, stderr);
 }
 #endif