upstream commit

update packet.c & isolate, introduce struct ssh a) switch
 packet.c to buffer api and isolate per-connection info into struct ssh b)
 (de)serialization of the state is moved from monitor to packet.c c) the old
 packet.c API is implemented in opacket.[ch] d) compress.c/h is removed and
 integrated into packet.c with and ok djm@
diff --git a/Makefile.in b/Makefile.in
index ebb0c51..13256c2 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -78,8 +78,8 @@
 	authfd.o authfile.o bufaux.o bufbn.o buffer.o \
 	canohost.o channels.o cipher.o cipher-aes.o cipher-aesctr.o \
 	cipher-bf1.o cipher-ctr.o cipher-3des1.o cleanup.o \
-	compat.o compress.o crc32.o deattack.o fatal.o hostfile.o \
-	log.o match.o md-sha256.o moduli.o nchan.o packet.o \
+	compat.o crc32.o deattack.o fatal.o hostfile.o \
+	log.o match.o md-sha256.o moduli.o nchan.o packet.o opacket.o \
 	readpass.o rsa.o ttymodes.o xmalloc.o addrmatch.o \
 	atomicio.o key.o dispatch.o kex.o mac.o uidswap.o uuencode.o misc.o \
 	monitor_fdpass.o rijndael.o ssh-dss.o ssh-ecdsa.o ssh-rsa.o dh.o \
diff --git a/clientloop.c b/clientloop.c
index 2137a81..3b9700a 100644
--- a/clientloop.c
+++ b/clientloop.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: clientloop.c,v 1.262 2015/01/14 20:05:27 djm Exp $ */
+/* $OpenBSD: clientloop.c,v 1.263 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Author: Tatu Ylonen <ylo@cs.hut.fi>
  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -192,9 +192,6 @@
 static struct global_confirms global_confirms =
     TAILQ_HEAD_INITIALIZER(global_confirms);
 
-/*XXX*/
-extern Kex *xxx_kex;
-
 void ssh_process_session2_setup(int, int, int, Buffer *);
 
 /* Restores stdin to blocking mode. */
@@ -1416,7 +1413,7 @@
 client_process_buffered_input_packets(void)
 {
 	dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
-	    compat20 ? xxx_kex : NULL);
+	    compat20 ? active_state->kex : NULL);
 }
 
 /* scan buf[] for '~' before sending data to the peer */
@@ -1555,7 +1552,7 @@
 		if (compat20 && session_closed && !channel_still_open())
 			break;
 
-		rekeying = (xxx_kex != NULL && !xxx_kex->done);
+		rekeying = (active_state->kex != NULL && !active_state->kex->done);
 
 		if (rekeying) {
 			debug("rekeying in progress");
@@ -1599,8 +1596,8 @@
 			channel_after_select(readset, writeset);
 			if (need_rekeying || packet_need_rekeying()) {
 				debug("need rekeying");
-				xxx_kex->done = 0;
-				kex_send_kexinit(xxx_kex);
+				active_state->kex->done = 0;
+				kex_send_kexinit(active_state->kex);
 				need_rekeying = 0;
 			}
 		}
@@ -1729,8 +1726,7 @@
 
 	/* Report bytes transferred, and transfer rates. */
 	total_time = get_current_time() - start_time;
-	packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
-	packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
+	packet_get_bytes(&ibytes, &obytes);
 	verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
 	    (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
 	if (total_time > 0)
diff --git a/compress.c b/compress.c
deleted file mode 100644
index 24778e5..0000000
--- a/compress.c
+++ /dev/null
@@ -1,167 +0,0 @@
-/* $OpenBSD: compress.c,v 1.26 2010/09/08 04:13:31 deraadt Exp $ */
-/*
- * Author: Tatu Ylonen <ylo@cs.hut.fi>
- * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
- *                    All rights reserved
- * Interface to packet compression for ssh.
- *
- * As far as I am concerned, the code I have written for this software
- * can be used freely for any purpose.  Any derived versions of this
- * software must be clearly marked as such, and if the derived work is
- * incompatible with the protocol description in the RFC file, it must be
- * called by a name other than "ssh" or "Secure Shell".
- */
-
-#include "includes.h"
-
-#include <sys/types.h>
-
-#include <stdarg.h>
-
-#include "log.h"
-#include "buffer.h"
-#include "compress.h"
-
-#include <zlib.h>
-
-z_stream incoming_stream;
-z_stream outgoing_stream;
-static int compress_init_send_called = 0;
-static int compress_init_recv_called = 0;
-static int inflate_failed = 0;
-static int deflate_failed = 0;
-
-/*
- * Initializes compression; level is compression level from 1 to 9
- * (as in gzip).
- */
-
-void
-buffer_compress_init_send(int level)
-{
-	if (compress_init_send_called == 1)
-		deflateEnd(&outgoing_stream);
-	compress_init_send_called = 1;
-	debug("Enabling compression at level %d.", level);
-	if (level < 1 || level > 9)
-		fatal("Bad compression level %d.", level);
-	deflateInit(&outgoing_stream, level);
-}
-void
-buffer_compress_init_recv(void)
-{
-	if (compress_init_recv_called == 1)
-		inflateEnd(&incoming_stream);
-	compress_init_recv_called = 1;
-	inflateInit(&incoming_stream);
-}
-
-/* Frees any data structures allocated for compression. */
-
-void
-buffer_compress_uninit(void)
-{
-	debug("compress outgoing: raw data %llu, compressed %llu, factor %.2f",
-	    (unsigned long long)outgoing_stream.total_in,
-	    (unsigned long long)outgoing_stream.total_out,
-	    outgoing_stream.total_in == 0 ? 0.0 :
-	    (double) outgoing_stream.total_out / outgoing_stream.total_in);
-	debug("compress incoming: raw data %llu, compressed %llu, factor %.2f",
-	    (unsigned long long)incoming_stream.total_out,
-	    (unsigned long long)incoming_stream.total_in,
-	    incoming_stream.total_out == 0 ? 0.0 :
-	    (double) incoming_stream.total_in / incoming_stream.total_out);
-	if (compress_init_recv_called == 1 && inflate_failed == 0)
-		inflateEnd(&incoming_stream);
-	if (compress_init_send_called == 1 && deflate_failed == 0)
-		deflateEnd(&outgoing_stream);
-}
-
-/*
- * Compresses the contents of input_buffer into output_buffer.  All packets
- * compressed using this function will form a single compressed data stream;
- * however, data will be flushed at the end of every call so that each
- * output_buffer can be decompressed independently (but in the appropriate
- * order since they together form a single compression stream) by the
- * receiver.  This appends the compressed data to the output buffer.
- */
-
-void
-buffer_compress(Buffer * input_buffer, Buffer * output_buffer)
-{
-	u_char buf[4096];
-	int status;
-
-	/* This case is not handled below. */
-	if (buffer_len(input_buffer) == 0)
-		return;
-
-	/* Input is the contents of the input buffer. */
-	outgoing_stream.next_in = buffer_ptr(input_buffer);
-	outgoing_stream.avail_in = buffer_len(input_buffer);
-
-	/* Loop compressing until deflate() returns with avail_out != 0. */
-	do {
-		/* Set up fixed-size output buffer. */
-		outgoing_stream.next_out = buf;
-		outgoing_stream.avail_out = sizeof(buf);
-
-		/* Compress as much data into the buffer as possible. */
-		status = deflate(&outgoing_stream, Z_PARTIAL_FLUSH);
-		switch (status) {
-		case Z_OK:
-			/* Append compressed data to output_buffer. */
-			buffer_append(output_buffer, buf,
-			    sizeof(buf) - outgoing_stream.avail_out);
-			break;
-		default:
-			deflate_failed = 1;
-			fatal("buffer_compress: deflate returned %d", status);
-			/* NOTREACHED */
-		}
-	} while (outgoing_stream.avail_out == 0);
-}
-
-/*
- * Uncompresses the contents of input_buffer into output_buffer.  All packets
- * uncompressed using this function will form a single compressed data
- * stream; however, data will be flushed at the end of every call so that
- * each output_buffer.  This must be called for the same size units that the
- * buffer_compress was called, and in the same order that buffers compressed
- * with that.  This appends the uncompressed data to the output buffer.
- */
-
-void
-buffer_uncompress(Buffer * input_buffer, Buffer * output_buffer)
-{
-	u_char buf[4096];
-	int status;
-
-	incoming_stream.next_in = buffer_ptr(input_buffer);
-	incoming_stream.avail_in = buffer_len(input_buffer);
-
-	for (;;) {
-		/* Set up fixed-size output buffer. */
-		incoming_stream.next_out = buf;
-		incoming_stream.avail_out = sizeof(buf);
-
-		status = inflate(&incoming_stream, Z_PARTIAL_FLUSH);
-		switch (status) {
-		case Z_OK:
-			buffer_append(output_buffer, buf,
-			    sizeof(buf) - incoming_stream.avail_out);
-			break;
-		case Z_BUF_ERROR:
-			/*
-			 * Comments in zlib.h say that we should keep calling
-			 * inflate() until we get an error.  This appears to
-			 * be the error that we get.
-			 */
-			return;
-		default:
-			inflate_failed = 1;
-			fatal("buffer_uncompress: inflate returned %d", status);
-			/* NOTREACHED */
-		}
-	}
-}
diff --git a/compress.h b/compress.h
deleted file mode 100644
index 418d6fd..0000000
--- a/compress.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/* $OpenBSD: compress.h,v 1.12 2006/03/25 22:22:43 djm Exp $ */
-
-/*
- * Author: Tatu Ylonen <ylo@cs.hut.fi>
- * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
- *                    All rights reserved
- * Interface to packet compression for ssh.
- *
- * As far as I am concerned, the code I have written for this software
- * can be used freely for any purpose.  Any derived versions of this
- * software must be clearly marked as such, and if the derived work is
- * incompatible with the protocol description in the RFC file, it must be
- * called by a name other than "ssh" or "Secure Shell".
- */
-
-#ifndef COMPRESS_H
-#define COMPRESS_H
-
-void	 buffer_compress_init_send(int);
-void	 buffer_compress_init_recv(void);
-void     buffer_compress_uninit(void);
-void     buffer_compress(Buffer *, Buffer *);
-void     buffer_uncompress(Buffer *, Buffer *);
-
-#endif				/* COMPRESS_H */
diff --git a/deattack.c b/deattack.c
index 1b37e4d..b102401 100644
--- a/deattack.c
+++ b/deattack.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: deattack.c,v 1.30 2006/09/16 19:53:37 djm Exp $ */
+/* $OpenBSD: deattack.c,v 1.31 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Cryptographic attack detector for ssh - source code
  *
@@ -20,16 +20,14 @@
 
 #include "includes.h"
 
-#include <sys/types.h>
-
+#include <sys/param.h>
 #include <string.h>
 #include <stdio.h>
-#include <stdarg.h>
+#include <stdlib.h>
 
-#include "xmalloc.h"
 #include "deattack.h"
-#include "log.h"
 #include "crc32.h"
+#include "sshbuf.h"
 #include "misc.h"
 
 /*
@@ -66,7 +64,7 @@
 
 
 /* Hash function (Input keys are cipher results) */
-#define HASH(x)		get_u32(x)
+#define HASH(x)		PEEK_U32(x)
 
 #define CMP(a, b)	(memcmp(a, b, SSH_BLOCKSIZE))
 
@@ -79,10 +77,10 @@
 
 /* detect if a block is used in a particular pattern */
 static int
-check_crc(u_char *S, u_char *buf, u_int32_t len)
+check_crc(const u_char *S, const u_char *buf, u_int32_t len)
 {
 	u_int32_t crc;
-	u_char *c;
+	const u_char *c;
 
 	crc = 0;
 	for (c = buf; c < buf + len; c += SSH_BLOCKSIZE) {
@@ -94,36 +92,44 @@
 			crc_update(&crc, 0);
 		}
 	}
-	return (crc == 0);
+	return crc == 0;
 }
 
+void
+deattack_init(struct deattack_ctx *dctx)
+{
+	bzero(dctx, sizeof(*dctx));
+	dctx->n = HASH_MINSIZE / HASH_ENTRYSIZE;
+}
 
 /* Detect a crc32 compensation attack on a packet */
 int
-detect_attack(u_char *buf, u_int32_t len)
+detect_attack(struct deattack_ctx *dctx, const u_char *buf, u_int32_t len)
 {
-	static u_int16_t *h = (u_int16_t *) NULL;
-	static u_int32_t n = HASH_MINSIZE / HASH_ENTRYSIZE;
-	u_int32_t i, j;
-	u_int32_t l, same;
-	u_char *c;
-	u_char *d;
+	u_int32_t i, j, l, same;
+	u_int16_t *tmp;
+	const u_char *c, *d;
 
 	if (len > (SSH_MAXBLOCKS * SSH_BLOCKSIZE) ||
-	    len % SSH_BLOCKSIZE != 0) {
-		fatal("detect_attack: bad length %d", len);
-	}
-	for (l = n; l < HASH_FACTOR(len / SSH_BLOCKSIZE); l = l << 2)
+	    len % SSH_BLOCKSIZE != 0)
+		return DEATTACK_ERROR;
+	for (l = dctx->n; l < HASH_FACTOR(len / SSH_BLOCKSIZE); l = l << 2)
 		;
 
-	if (h == NULL) {
-		debug("Installing crc compensation attack detector.");
-		h = (u_int16_t *) xcalloc(l, HASH_ENTRYSIZE);
-		n = l;
+	if (dctx->h == NULL) {
+		if ((dctx->h = calloc(l, HASH_ENTRYSIZE)) == NULL)
+			return DEATTACK_ERROR;
+		dctx->n = l;
 	} else {
-		if (l > n) {
-			h = (u_int16_t *)xrealloc(h, l, HASH_ENTRYSIZE);
-			n = l;
+		if (l > dctx->n) {
+			if ((tmp = reallocarray(dctx->h, l, HASH_ENTRYSIZE))
+			    == NULL) {
+				free(dctx->h);
+				dctx->h = NULL;
+				return DEATTACK_ERROR;
+			}
+			dctx->h = tmp;
+			dctx->n = l;
 		}
 	}
 
@@ -132,29 +138,29 @@
 			for (d = buf; d < c; d += SSH_BLOCKSIZE) {
 				if (!CMP(c, d)) {
 					if ((check_crc(c, buf, len)))
-						return (DEATTACK_DETECTED);
+						return DEATTACK_DETECTED;
 					else
 						break;
 				}
 			}
 		}
-		return (DEATTACK_OK);
+		return DEATTACK_OK;
 	}
-	memset(h, HASH_UNUSEDCHAR, n * HASH_ENTRYSIZE);
+	memset(dctx->h, HASH_UNUSEDCHAR, dctx->n * HASH_ENTRYSIZE);
 
 	for (c = buf, same = j = 0; c < (buf + len); c += SSH_BLOCKSIZE, j++) {
-		for (i = HASH(c) & (n - 1); h[i] != HASH_UNUSED;
-		    i = (i + 1) & (n - 1)) {
-			if (!CMP(c, buf + h[i] * SSH_BLOCKSIZE)) {
+		for (i = HASH(c) & (dctx->n - 1); dctx->h[i] != HASH_UNUSED;
+		    i = (i + 1) & (dctx->n - 1)) {
+			if (!CMP(c, buf + dctx->h[i] * SSH_BLOCKSIZE)) {
 				if (++same > MAX_IDENTICAL)
-					return (DEATTACK_DOS_DETECTED);
+					return DEATTACK_DOS_DETECTED;
 				if (check_crc(c, buf, len))
-					return (DEATTACK_DETECTED);
+					return DEATTACK_DETECTED;
 				else
 					break;
 			}
 		}
-		h[i] = j;
+		dctx->h[i] = j;
 	}
-	return (DEATTACK_OK);
+	return DEATTACK_OK;
 }
diff --git a/deattack.h b/deattack.h
index 0316fb2..ce67a30 100644
--- a/deattack.h
+++ b/deattack.h
@@ -1,4 +1,4 @@
-/* $OpenBSD: deattack.h,v 1.10 2006/09/16 19:53:37 djm Exp $ */
+/* $OpenBSD: deattack.h,v 1.11 2015/01/19 19:52:16 markus Exp $ */
 
 /*
  * Cryptographic attack detector for ssh - Header file
@@ -26,6 +26,13 @@
 #define DEATTACK_OK		0
 #define DEATTACK_DETECTED	1
 #define DEATTACK_DOS_DETECTED	2
+#define DEATTACK_ERROR		3
 
-int	 detect_attack(u_char *, u_int32_t);
+struct deattack_ctx {
+	u_int16_t *h;
+	u_int32_t n;
+};
+
+void	 deattack_init(struct deattack_ctx *);
+int	 detect_attack(struct deattack_ctx *, const u_char *, u_int32_t);
 #endif
diff --git a/kex.c b/kex.c
index ce0bf88..7c4dd7a 100644
--- a/kex.c
+++ b/kex.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: kex.c,v 1.99 2014/04/29 18:01:49 markus Exp $ */
+/* $OpenBSD: kex.c,v 1.100 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
  *
@@ -239,8 +239,8 @@
 	debug("SSH2_MSG_NEWKEYS received");
 
 	kex->done = 1;
-	buffer_clear(&kex->peer);
-	/* buffer_clear(&kex->my); */
+	buffer_clear(kex->peer);
+	/* buffer_clear(kex->my); */
 	kex->flags &= ~KEX_INIT_SENT;
 	free(kex->name);
 	kex->name = NULL;
@@ -264,9 +264,9 @@
 	kex->done = 0;
 
 	/* generate a random cookie */
-	if (buffer_len(&kex->my) < KEX_COOKIE_LEN)
+	if (buffer_len(kex->my) < KEX_COOKIE_LEN)
 		fatal("kex_send_kexinit: kex proposal too short");
-	cookie = buffer_ptr(&kex->my);
+	cookie = buffer_ptr(kex->my);
 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
 		if (i % 4 == 0)
 			rnd = arc4random();
@@ -274,7 +274,7 @@
 		rnd >>= 8;
 	}
 	packet_start(SSH2_MSG_KEXINIT);
-	packet_put_raw(buffer_ptr(&kex->my), buffer_len(&kex->my));
+	packet_put_raw(buffer_ptr(kex->my), buffer_len(kex->my));
 	packet_send();
 	debug("SSH2_MSG_KEXINIT sent");
 	kex->flags |= KEX_INIT_SENT;
@@ -284,8 +284,9 @@
 void
 kex_input_kexinit(int type, u_int32_t seq, void *ctxt)
 {
-	char *ptr;
-	u_int i, dlen;
+	const char *ptr;
+	u_int i;
+	size_t dlen;
 	Kex *kex = (Kex *)ctxt;
 
 	debug("SSH2_MSG_KEXINIT received");
@@ -293,7 +294,7 @@
 		fatal("kex_input_kexinit: no kex, cannot rekey");
 
 	ptr = packet_get_raw(&dlen);
-	buffer_append(&kex->peer, ptr, dlen);
+	buffer_append(kex->peer, ptr, dlen);
 
 	/* discard packet */
 	for (i = 0; i < KEX_COOKIE_LEN; i++)
@@ -317,15 +318,49 @@
 	kex_kexinit_finish(kex);
 }
 
+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);
+}
+
 Kex *
 kex_setup(char *proposal[PROPOSAL_MAX])
 {
-	Kex *kex;
+	struct kex *kex;
 
-	kex = xcalloc(1, sizeof(*kex));
-	buffer_init(&kex->peer);
-	buffer_init(&kex->my);
-	kex_prop2buf(&kex->my, proposal);
+	if ((kex = calloc(1, sizeof(*kex))) == NULL)
+		fatal("%s: calloc", __func__);
+	if ((kex->peer = sshbuf_new()) == NULL ||
+	    (kex->my = sshbuf_new()) == NULL) {
+		fatal("%s: sshbuf_new", __func__);
+	}
+	kex_prop2buf(kex->my, proposal);
 	kex->done = 0;
 
 	kex_send_kexinit(kex);					/* we start */
@@ -464,8 +499,8 @@
 	u_int mode, ctos, need, dh_need, authlen;
 	int first_kex_follows, type;
 
-	my   = kex_buf2prop(&kex->my, NULL);
-	peer = kex_buf2prop(&kex->peer, &first_kex_follows);
+	my   = kex_buf2prop(kex->my, NULL);
+	peer = kex_buf2prop(kex->peer, &first_kex_follows);
 
 	if (kex->server) {
 		cprop=peer;
@@ -591,8 +626,6 @@
 	return digest;
 }
 
-Newkeys *current_keys[MODE_MAX];
-
 #define NKEYS	6
 void
 kex_derive_keys(Kex *kex, u_char *hash, u_int hashlen,
@@ -608,13 +641,11 @@
 
 	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];
 	}
 }
 
@@ -632,16 +663,6 @@
 }
 #endif
 
-Newkeys *
-kex_get_newkeys(int mode)
-{
-	Newkeys *ret;
-
-	ret = current_keys[mode];
-	current_keys[mode] = NULL;
-	return ret;
-}
-
 #ifdef WITH_SSH1
 void
 derive_ssh1_session_id(BIGNUM *host_modulus, BIGNUM *server_modulus,
diff --git a/kex.h b/kex.h
index ef4a1f0..ffceb9f 100644
--- a/kex.h
+++ b/kex.h
@@ -1,4 +1,4 @@
-/* $OpenBSD: kex.h,v 1.66 2015/01/15 09:40:00 djm Exp $ */
+/* $OpenBSD: kex.h,v 1.67 2015/01/19 19:52:16 markus Exp $ */
 
 /*
  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
@@ -82,15 +82,15 @@
 
 #define KEX_INIT_SENT	0x0001
 
-typedef struct Kex Kex;
-typedef struct Comp Comp;
+typedef struct kex Kex;
+typedef struct sshcomp Comp;
 typedef struct sshmac Mac;
-typedef struct Enc Enc;
-typedef struct Newkeys Newkeys;
+typedef struct sshenc Enc;
+typedef struct newkeys Newkeys;
 
-struct Enc {
+struct sshenc {
 	char	*name;
-	const Cipher *cipher;
+	const struct sshcipher *cipher;
 	int	enabled;
 	u_int	key_len;
 	u_int	iv_len;
@@ -98,20 +98,20 @@
 	u_char	*key;
 	u_char	*iv;
 };
-struct Comp {
-	int	type;
+struct sshcomp {
+	u_int	type;
 	int	enabled;
 	char	*name;
 };
-struct Newkeys {
-	Enc	enc;
-	Mac	mac;
-	Comp	comp;
+struct newkeys {
+	struct sshenc	enc;
+	struct sshmac	mac;
+	struct sshcomp	comp;
 };
-struct Kex {
+struct kex {
 	u_char	*session_id;
-	u_int	session_id_len;
-	Newkeys	*newkeys[MODE_MAX];
+	size_t	session_id_len;
+	struct newkeys	*newkeys[MODE_MAX];
 	u_int	we_need;
 	u_int	dh_need;
 	int	server;
@@ -119,8 +119,8 @@
 	int	hostkey_type;
 	int	kex_type;
 	int	roaming;
-	Buffer	my;
-	Buffer	peer;
+	struct sshbuf *my;
+	struct sshbuf *peer;
 	sig_atomic_t done;
 	int	flags;
 	int	hash_alg;
@@ -140,14 +140,13 @@
 
 Kex	*kex_setup(char *[PROPOSAL_MAX]);
 void	 kex_finish(Kex *);
+void     kex_free_newkeys(struct newkeys *);
 
 void	 kex_send_kexinit(Kex *);
 void	 kex_input_kexinit(int, u_int32_t, void *);
 void	 kex_derive_keys(Kex *, u_char *, u_int, const u_char *, u_int);
 void	 kex_derive_keys_bn(Kex *, u_char *, u_int, const BIGNUM *);
 
-Newkeys *kex_get_newkeys(int);
-
 void	 kexdh_client(Kex *);
 void	 kexdh_server(Kex *);
 void	 kexgex_client(Kex *);
diff --git a/kexc25519c.c b/kexc25519c.c
index a80678a..ffb537e 100644
--- a/kexc25519c.c
+++ b/kexc25519c.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: kexc25519c.c,v 1.4 2014/01/12 08:13:13 djm Exp $ */
+/* $OpenBSD: kexc25519c.c,v 1.5 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright (c) 2001 Markus Friedl.  All rights reserved.
  * Copyright (c) 2010 Damien Miller.  All rights reserved.
@@ -101,8 +101,8 @@
 	    kex->hash_alg,
 	    kex->client_version_string,
 	    kex->server_version_string,
-	    buffer_ptr(&kex->my), buffer_len(&kex->my),
-	    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
+	    buffer_ptr(kex->my), buffer_len(kex->my),
+	    buffer_ptr(kex->peer), buffer_len(kex->peer),
 	    server_host_key_blob, sbloblen,
 	    client_pubkey,
 	    server_pubkey,
diff --git a/kexc25519s.c b/kexc25519s.c
index 2b8e8ef..ba6f546 100644
--- a/kexc25519s.c
+++ b/kexc25519s.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: kexc25519s.c,v 1.4 2014/01/12 08:13:13 djm Exp $ */
+/* $OpenBSD: kexc25519s.c,v 1.5 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright (c) 2001 Markus Friedl.  All rights reserved.
  * Copyright (c) 2010 Damien Miller.  All rights reserved.
@@ -85,8 +85,8 @@
 	    kex->hash_alg,
 	    kex->client_version_string,
 	    kex->server_version_string,
-	    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
-	    buffer_ptr(&kex->my), buffer_len(&kex->my),
+	    buffer_ptr(kex->peer), buffer_len(kex->peer),
+	    buffer_ptr(kex->my), buffer_len(kex->my),
 	    server_host_key_blob, sbloblen,
 	    client_pubkey,
 	    server_pubkey,
diff --git a/kexdhc.c b/kexdhc.c
index 53c3d9b..cd12df3 100644
--- a/kexdhc.c
+++ b/kexdhc.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: kexdhc.c,v 1.15 2014/02/02 03:44:31 djm Exp $ */
+/* $OpenBSD: kexdhc.c,v 1.16 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright (c) 2001 Markus Friedl.  All rights reserved.
  *
@@ -133,8 +133,8 @@
 	kex_dh_hash(
 	    kex->client_version_string,
 	    kex->server_version_string,
-	    buffer_ptr(&kex->my), buffer_len(&kex->my),
-	    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
+	    buffer_ptr(kex->my), buffer_len(kex->my),
+	    buffer_ptr(kex->peer), buffer_len(kex->peer),
 	    server_host_key_blob, sbloblen,
 	    dh->pub_key,
 	    dh_server_pub,
diff --git a/kexdhs.c b/kexdhs.c
index 56aa5d0..34a215f 100644
--- a/kexdhs.c
+++ b/kexdhs.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: kexdhs.c,v 1.18 2014/02/02 03:44:31 djm Exp $ */
+/* $OpenBSD: kexdhs.c,v 1.19 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright (c) 2001 Markus Friedl.  All rights reserved.
  *
@@ -121,8 +121,8 @@
 	kex_dh_hash(
 	    kex->client_version_string,
 	    kex->server_version_string,
-	    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
-	    buffer_ptr(&kex->my), buffer_len(&kex->my),
+	    buffer_ptr(kex->peer), buffer_len(kex->peer),
+	    buffer_ptr(kex->my), buffer_len(kex->my),
 	    server_host_key_blob, sbloblen,
 	    dh_client_pub,
 	    dh->pub_key,
diff --git a/kexecdhc.c b/kexecdhc.c
index 2019940..df811c1 100644
--- a/kexecdhc.c
+++ b/kexecdhc.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: kexecdhc.c,v 1.7 2014/02/02 03:44:31 djm Exp $ */
+/* $OpenBSD: kexecdhc.c,v 1.8 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright (c) 2001 Markus Friedl.  All rights reserved.
  * Copyright (c) 2010 Damien Miller.  All rights reserved.
@@ -128,8 +128,8 @@
 	    group,
 	    kex->client_version_string,
 	    kex->server_version_string,
-	    buffer_ptr(&kex->my), buffer_len(&kex->my),
-	    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
+	    buffer_ptr(kex->my), buffer_len(kex->my),
+	    buffer_ptr(kex->peer), buffer_len(kex->peer),
 	    server_host_key_blob, sbloblen,
 	    EC_KEY_get0_public_key(client_key),
 	    server_public,
diff --git a/kexecdhs.c b/kexecdhs.c
index 48bc56d..6bfad04 100644
--- a/kexecdhs.c
+++ b/kexecdhs.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: kexecdhs.c,v 1.10 2014/02/02 03:44:31 djm Exp $ */
+/* $OpenBSD: kexecdhs.c,v 1.11 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright (c) 2001 Markus Friedl.  All rights reserved.
  * Copyright (c) 2010 Damien Miller.  All rights reserved.
@@ -113,8 +113,8 @@
 	    group,
 	    kex->client_version_string,
 	    kex->server_version_string,
-	    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
-	    buffer_ptr(&kex->my), buffer_len(&kex->my),
+	    buffer_ptr(kex->peer), buffer_len(kex->peer),
+	    buffer_ptr(kex->my), buffer_len(kex->my),
 	    server_host_key_blob, sbloblen,
 	    client_public,
 	    EC_KEY_get0_public_key(server_key),
diff --git a/kexgexc.c b/kexgexc.c
index a21a1d9..18d09cf 100644
--- a/kexgexc.c
+++ b/kexgexc.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: kexgexc.c,v 1.17 2014/02/02 03:44:31 djm Exp $ */
+/* $OpenBSD: kexgexc.c,v 1.18 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright (c) 2000 Niels Provos.  All rights reserved.
  * Copyright (c) 2001 Markus Friedl.  All rights reserved.
@@ -175,8 +175,8 @@
 	    kex->hash_alg,
 	    kex->client_version_string,
 	    kex->server_version_string,
-	    buffer_ptr(&kex->my), buffer_len(&kex->my),
-	    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
+	    buffer_ptr(kex->my), buffer_len(kex->my),
+	    buffer_ptr(kex->peer), buffer_len(kex->peer),
 	    server_host_key_blob, sbloblen,
 	    min, nbits, max,
 	    dh->p, dh->g,
diff --git a/kexgexs.c b/kexgexs.c
index ab90a9d..1021e0b 100644
--- a/kexgexs.c
+++ b/kexgexs.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: kexgexs.c,v 1.19 2014/02/02 03:44:31 djm Exp $ */
+/* $OpenBSD: kexgexs.c,v 1.20 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright (c) 2000 Niels Provos.  All rights reserved.
  * Copyright (c) 2001 Markus Friedl.  All rights reserved.
@@ -165,8 +165,8 @@
 	    kex->hash_alg,
 	    kex->client_version_string,
 	    kex->server_version_string,
-	    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
-	    buffer_ptr(&kex->my), buffer_len(&kex->my),
+	    buffer_ptr(kex->peer), buffer_len(kex->peer),
+	    buffer_ptr(kex->my), buffer_len(kex->my),
 	    server_host_key_blob, sbloblen,
 	    omin, onbits, omax,
 	    dh->p, dh->g,
diff --git a/monitor.c b/monitor.c
index 6858478..6ee2911 100644
--- a/monitor.c
+++ b/monitor.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: monitor.c,v 1.138 2015/01/14 20:05:27 djm Exp $ */
+/* $OpenBSD: monitor.c,v 1.139 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright 2002 Niels Provos <provos@citi.umich.edu>
  * Copyright 2002 Markus Friedl <markus@openbsd.org>
@@ -110,38 +110,13 @@
 /* Imports */
 extern ServerOptions options;
 extern u_int utmp_len;
-extern Newkeys *current_keys[];
-extern z_stream incoming_stream;
-extern z_stream outgoing_stream;
 extern u_char session_id[];
 extern Buffer auth_debug;
 extern int auth_debug_init;
 extern Buffer loginmsg;
 
 /* State exported from the child */
-
-struct {
-	z_stream incoming;
-	z_stream outgoing;
-	u_char *keyin;
-	u_int keyinlen;
-	u_char *keyout;
-	u_int keyoutlen;
-	u_char *ivin;
-	u_int ivinlen;
-	u_char *ivout;
-	u_int ivoutlen;
-	u_char *ssh1key;
-	u_int ssh1keylen;
-	int ssh1cipher;
-	int ssh1protoflags;
-	u_char *input;
-	u_int ilen;
-	u_char *output;
-	u_int olen;
-	u_int64_t sent_bytes;
-	u_int64_t recv_bytes;
-} child_state;
+static struct sshbuf *child_state;
 
 /* Functions on the monitor that answer unprivileged requests */
 
@@ -506,6 +481,27 @@
 	}
 }
 
+/* Allocation functions for zlib */
+static void *
+mm_zalloc(struct mm_master *mm, u_int ncount, u_int size)
+{
+	size_t len = (size_t) size * ncount;
+	void *address;
+
+	if (len == 0 || ncount > SIZE_T_MAX / size)
+		fatal("%s: mm_zalloc(%u, %u)", __func__, ncount, size);
+
+	address = mm_malloc(mm, len);
+
+	return (address);
+}
+
+static void
+mm_zfree(struct mm_master *mm, void *address)
+{
+	mm_free(mm, address);
+}
+
 static int
 monitor_read_log(struct monitor *pmonitor)
 {
@@ -1807,105 +1803,41 @@
 void
 monitor_apply_keystate(struct monitor *pmonitor)
 {
-	if (compat20) {
-		set_newkeys(MODE_IN);
-		set_newkeys(MODE_OUT);
-	} else {
-		packet_set_protocol_flags(child_state.ssh1protoflags);
-		packet_set_encryption_key(child_state.ssh1key,
-		    child_state.ssh1keylen, child_state.ssh1cipher);
-		free(child_state.ssh1key);
+	struct ssh *ssh = active_state;	/* XXX */
+	struct kex *kex;
+	int r;
+
+	debug3("%s: packet_set_state", __func__);
+	if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
+                fatal("%s: packet_set_state: %s", __func__, ssh_err(r));
+	sshbuf_free(child_state);
+	child_state = NULL;
+
+	if ((kex = ssh->kex) != 0) {
+		/* XXX set callbacks */
+		kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
+		kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
+		kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
+		kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
+		kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
+		kex->kex[KEX_C25519_SHA256] = kexc25519_server;
+		kex->load_host_public_key=&get_hostkey_public_by_type;
+		kex->load_host_private_key=&get_hostkey_private_by_type;
+		kex->host_key_index=&get_hostkey_index;
+		kex->sign = sshd_hostkey_sign;
 	}
 
-	/* for rc4 and other stateful ciphers */
-	packet_set_keycontext(MODE_OUT, child_state.keyout);
-	free(child_state.keyout);
-	packet_set_keycontext(MODE_IN, child_state.keyin);
-	free(child_state.keyin);
-
-	if (!compat20) {
-		packet_set_iv(MODE_OUT, child_state.ivout);
-		free(child_state.ivout);
-		packet_set_iv(MODE_IN, child_state.ivin);
-		free(child_state.ivin);
-	}
-
-	memcpy(&incoming_stream, &child_state.incoming,
-	    sizeof(incoming_stream));
-	memcpy(&outgoing_stream, &child_state.outgoing,
-	    sizeof(outgoing_stream));
-
 	/* Update with new address */
-	if (options.compression)
-		mm_init_compression(pmonitor->m_zlib);
-
-	packet_set_postauth();
+	if (options.compression) {
+		ssh_packet_set_compress_hooks(ssh, pmonitor->m_zlib,
+		    (ssh_packet_comp_alloc_func *)mm_zalloc,
+		    (ssh_packet_comp_free_func *)mm_zfree);
+	}
 
 	if (options.rekey_limit || options.rekey_interval)
-		packet_set_rekey_limits((u_int32_t)options.rekey_limit,
+		ssh_packet_set_rekey_limits(ssh,
+		    (u_int32_t)options.rekey_limit,
 		    (time_t)options.rekey_interval);
-
-	/* Network I/O buffers */
-	/* XXX inefficient for large buffers, need: buffer_init_from_string */
-	buffer_clear(packet_get_input());
-	buffer_append(packet_get_input(), child_state.input, child_state.ilen);
-	explicit_bzero(child_state.input, child_state.ilen);
-	free(child_state.input);
-
-	buffer_clear(packet_get_output());
-	buffer_append(packet_get_output(), child_state.output,
-		      child_state.olen);
-	explicit_bzero(child_state.output, child_state.olen);
-	free(child_state.output);
-
-	/* Roaming */
-	if (compat20)
-		roam_set_bytes(child_state.sent_bytes, child_state.recv_bytes);
-}
-
-static Kex *
-mm_get_kex(Buffer *m)
-{
-	Kex *kex;
-	void *blob;
-	u_int bloblen;
-
-	kex = xcalloc(1, sizeof(*kex));
-	kex->session_id = buffer_get_string(m, &kex->session_id_len);
-	if (session_id2 == NULL ||
-	    kex->session_id_len != session_id2_len ||
-	    timingsafe_bcmp(kex->session_id, session_id2, session_id2_len) != 0)
-		fatal("mm_get_get: internal error: bad session id");
-	kex->we_need = buffer_get_int(m);
-#ifdef WITH_OPENSSL
-	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
-	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
-	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
-	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
-	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
-#endif
-	kex->kex[KEX_C25519_SHA256] = kexc25519_server;
-	kex->server = 1;
-	kex->hostkey_type = buffer_get_int(m);
-	kex->kex_type = buffer_get_int(m);
-	blob = buffer_get_string(m, &bloblen);
-	buffer_init(&kex->my);
-	buffer_append(&kex->my, blob, bloblen);
-	free(blob);
-	blob = buffer_get_string(m, &bloblen);
-	buffer_init(&kex->peer);
-	buffer_append(&kex->peer, blob, bloblen);
-	free(blob);
-	kex->done = 1;
-	kex->flags = buffer_get_int(m);
-	kex->client_version_string = buffer_get_string(m, NULL);
-	kex->server_version_string = buffer_get_string(m, NULL);
-	kex->load_host_public_key=&get_hostkey_public_by_type;
-	kex->load_host_private_key=&get_hostkey_private_by_type;
-	kex->host_key_index=&get_hostkey_index;
-	kex->sign = sshd_hostkey_sign;
-
-	return (kex);
 }
 
 /* This function requries careful sanity checking */
@@ -1913,118 +1845,16 @@
 void
 mm_get_keystate(struct monitor *pmonitor)
 {
-	Buffer m;
-	u_char *blob, *p;
-	u_int bloblen, plen;
-	u_int32_t seqnr, packets;
-	u_int64_t blocks, bytes;
-
 	debug3("%s: Waiting for new keys", __func__);
 
-	buffer_init(&m);
-	mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT, &m);
-	if (!compat20) {
-		child_state.ssh1protoflags = buffer_get_int(&m);
-		child_state.ssh1cipher = buffer_get_int(&m);
-		child_state.ssh1key = buffer_get_string(&m,
-		    &child_state.ssh1keylen);
-		child_state.ivout = buffer_get_string(&m,
-		    &child_state.ivoutlen);
-		child_state.ivin = buffer_get_string(&m, &child_state.ivinlen);
-		goto skip;
-	} else {
-		/* Get the Kex for rekeying */
-		*pmonitor->m_pkex = mm_get_kex(&m);
-	}
-
-	blob = buffer_get_string(&m, &bloblen);
-	current_keys[MODE_OUT] = mm_newkeys_from_blob(blob, bloblen);
-	free(blob);
-
-	debug3("%s: Waiting for second key", __func__);
-	blob = buffer_get_string(&m, &bloblen);
-	current_keys[MODE_IN] = mm_newkeys_from_blob(blob, bloblen);
-	free(blob);
-
-	/* Now get sequence numbers for the packets */
-	seqnr = buffer_get_int(&m);
-	blocks = buffer_get_int64(&m);
-	packets = buffer_get_int(&m);
-	bytes = buffer_get_int64(&m);
-	packet_set_state(MODE_OUT, seqnr, blocks, packets, bytes);
-	seqnr = buffer_get_int(&m);
-	blocks = buffer_get_int64(&m);
-	packets = buffer_get_int(&m);
-	bytes = buffer_get_int64(&m);
-	packet_set_state(MODE_IN, seqnr, blocks, packets, bytes);
-
- skip:
-	/* Get the key context */
-	child_state.keyout = buffer_get_string(&m, &child_state.keyoutlen);
-	child_state.keyin  = buffer_get_string(&m, &child_state.keyinlen);
-
-	debug3("%s: Getting compression state", __func__);
-	/* Get compression state */
-	p = buffer_get_string(&m, &plen);
-	if (plen != sizeof(child_state.outgoing))
-		fatal("%s: bad request size", __func__);
-	memcpy(&child_state.outgoing, p, sizeof(child_state.outgoing));
-	free(p);
-
-	p = buffer_get_string(&m, &plen);
-	if (plen != sizeof(child_state.incoming))
-		fatal("%s: bad request size", __func__);
-	memcpy(&child_state.incoming, p, sizeof(child_state.incoming));
-	free(p);
-
-	/* Network I/O buffers */
-	debug3("%s: Getting Network I/O buffers", __func__);
-	child_state.input = buffer_get_string(&m, &child_state.ilen);
-	child_state.output = buffer_get_string(&m, &child_state.olen);
-
-	/* Roaming */
-	if (compat20) {
-		child_state.sent_bytes = buffer_get_int64(&m);
-		child_state.recv_bytes = buffer_get_int64(&m);
-	}
-
-	buffer_free(&m);
+	if ((child_state = sshbuf_new()) == NULL)
+		fatal("%s: sshbuf_new failed", __func__);
+	mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT,
+	    child_state);
+	debug3("%s: GOT new keys", __func__);
 }
 
 
-/* Allocation functions for zlib */
-void *
-mm_zalloc(struct mm_master *mm, u_int ncount, u_int size)
-{
-	size_t len = (size_t) size * ncount;
-	void *address;
-
-	if (len == 0 || ncount > SIZE_T_MAX / size)
-		fatal("%s: mm_zalloc(%u, %u)", __func__, ncount, size);
-
-	address = mm_malloc(mm, len);
-
-	return (address);
-}
-
-void
-mm_zfree(struct mm_master *mm, void *address)
-{
-	mm_free(mm, address);
-}
-
-void
-mm_init_compression(struct mm_master *mm)
-{
-	outgoing_stream.zalloc = (alloc_func)mm_zalloc;
-	outgoing_stream.zfree = (free_func)mm_zfree;
-	outgoing_stream.opaque = mm;
-
-	incoming_stream.zalloc = (alloc_func)mm_zalloc;
-	incoming_stream.zfree = (free_func)mm_zfree;
-	incoming_stream.opaque = mm;
-}
-
 /* XXX */
 
 #define FD_CLOSEONEXEC(x) do { \
@@ -2060,6 +1890,7 @@
 struct monitor *
 monitor_init(void)
 {
+	struct ssh *ssh = active_state;			/* XXX */
 	struct monitor *mon;
 
 	mon = xcalloc(1, sizeof(*mon));
@@ -2072,7 +1903,9 @@
 		mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE);
 
 		/* Compression needs to share state across borders */
-		mm_init_compression(mon->m_zlib);
+		ssh_packet_set_compress_hooks(ssh, mon->m_zlib,
+		    (ssh_packet_comp_alloc_func *)mm_zalloc,
+		    (ssh_packet_comp_free_func *)mm_zfree);
 	}
 
 	return mon;
diff --git a/monitor.h b/monitor.h
index 5bc41b5..93b8b66 100644
--- a/monitor.h
+++ b/monitor.h
@@ -1,4 +1,4 @@
-/* $OpenBSD: monitor.h,v 1.18 2014/01/29 06:18:35 djm Exp $ */
+/* $OpenBSD: monitor.h,v 1.19 2015/01/19 19:52:16 markus Exp $ */
 
 /*
  * Copyright 2002 Niels Provos <provos@citi.umich.edu>
@@ -75,7 +75,7 @@
 	int			 m_log_sendfd;
 	struct mm_master	*m_zback;
 	struct mm_master	*m_zlib;
-	struct Kex		**m_pkex;
+	struct kex		**m_pkex;
 	pid_t			 m_pid;
 };
 
diff --git a/monitor_wrap.c b/monitor_wrap.c
index b0dbb3f..84df481 100644
--- a/monitor_wrap.c
+++ b/monitor_wrap.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: monitor_wrap.c,v 1.81 2015/01/13 19:31:40 markus Exp $ */
+/* $OpenBSD: monitor_wrap.c,v 1.82 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright 2002 Niels Provos <provos@citi.umich.edu>
  * Copyright 2002 Markus Friedl <markus@openbsd.org>
@@ -82,6 +82,8 @@
 #include "servconf.h"
 #include "roaming.h"
 
+#include "ssherr.h"
+
 /* Imports */
 extern int compat20;
 extern z_stream incoming_stream;
@@ -470,239 +472,21 @@
 	return (verified);
 }
 
-/* Export key state after authentication */
-Newkeys *
-mm_newkeys_from_blob(u_char *blob, int blen)
-{
-	Buffer b;
-	u_int len;
-	Newkeys *newkey = NULL;
-	Enc *enc;
-	Mac *mac;
-	Comp *comp;
-
-	debug3("%s: %p(%d)", __func__, blob, blen);
-#ifdef DEBUG_PK
-	dump_base64(stderr, blob, blen);
-#endif
-	buffer_init(&b);
-	buffer_append(&b, blob, blen);
-
-	newkey = xcalloc(1, sizeof(*newkey));
-	enc = &newkey->enc;
-	mac = &newkey->mac;
-	comp = &newkey->comp;
-
-	/* Enc structure */
-	enc->name = buffer_get_string(&b, NULL);
-	buffer_get(&b, &enc->cipher, sizeof(enc->cipher));
-	enc->enabled = buffer_get_int(&b);
-	enc->block_size = buffer_get_int(&b);
-	enc->key = buffer_get_string(&b, &enc->key_len);
-	enc->iv = buffer_get_string(&b, &enc->iv_len);
-
-	if (enc->name == NULL || cipher_by_name(enc->name) != enc->cipher)
-		fatal("%s: bad cipher name %s or pointer %p", __func__,
-		    enc->name, enc->cipher);
-
-	/* Mac structure */
-	if (cipher_authlen(enc->cipher) == 0) {
-		mac->name = buffer_get_string(&b, NULL);
-		if (mac->name == NULL || mac_setup(mac, mac->name) != 0)
-			fatal("%s: can not setup mac %s", __func__, mac->name);
-		mac->enabled = buffer_get_int(&b);
-		mac->key = buffer_get_string(&b, &len);
-		if (len > mac->key_len)
-			fatal("%s: bad mac key length: %u > %d", __func__, len,
-			    mac->key_len);
-		mac->key_len = len;
-	}
-
-	/* Comp structure */
-	comp->type = buffer_get_int(&b);
-	comp->enabled = buffer_get_int(&b);
-	comp->name = buffer_get_string(&b, NULL);
-
-	len = buffer_len(&b);
-	if (len != 0)
-		error("newkeys_from_blob: remaining bytes in blob %u", len);
-	buffer_free(&b);
-	return (newkey);
-}
-
-int
-mm_newkeys_to_blob(int mode, u_char **blobp, u_int *lenp)
-{
-	Buffer b;
-	int len;
-	Enc *enc;
-	Mac *mac;
-	Comp *comp;
-	Newkeys *newkey = (Newkeys *)packet_get_newkeys(mode);
-
-	debug3("%s: converting %p", __func__, newkey);
-
-	if (newkey == NULL) {
-		error("%s: newkey == NULL", __func__);
-		return 0;
-	}
-	enc = &newkey->enc;
-	mac = &newkey->mac;
-	comp = &newkey->comp;
-
-	buffer_init(&b);
-	/* Enc structure */
-	buffer_put_cstring(&b, enc->name);
-	/* The cipher struct is constant and shared, you export pointer */
-	buffer_append(&b, &enc->cipher, sizeof(enc->cipher));
-	buffer_put_int(&b, enc->enabled);
-	buffer_put_int(&b, enc->block_size);
-	buffer_put_string(&b, enc->key, enc->key_len);
-	packet_get_keyiv(mode, enc->iv, enc->iv_len);
-	buffer_put_string(&b, enc->iv, enc->iv_len);
-
-	/* Mac structure */
-	if (cipher_authlen(enc->cipher) == 0) {
-		buffer_put_cstring(&b, mac->name);
-		buffer_put_int(&b, mac->enabled);
-		buffer_put_string(&b, mac->key, mac->key_len);
-	}
-
-	/* Comp structure */
-	buffer_put_int(&b, comp->type);
-	buffer_put_int(&b, comp->enabled);
-	buffer_put_cstring(&b, comp->name);
-
-	len = buffer_len(&b);
-	if (lenp != NULL)
-		*lenp = len;
-	if (blobp != NULL) {
-		*blobp = xmalloc(len);
-		memcpy(*blobp, buffer_ptr(&b), len);
-	}
-	explicit_bzero(buffer_ptr(&b), len);
-	buffer_free(&b);
-	return len;
-}
-
-static void
-mm_send_kex(Buffer *m, Kex *kex)
-{
-	buffer_put_string(m, kex->session_id, kex->session_id_len);
-	buffer_put_int(m, kex->we_need);
-	buffer_put_int(m, kex->hostkey_type);
-	buffer_put_int(m, kex->kex_type);
-	buffer_put_string(m, buffer_ptr(&kex->my), buffer_len(&kex->my));
-	buffer_put_string(m, buffer_ptr(&kex->peer), buffer_len(&kex->peer));
-	buffer_put_int(m, kex->flags);
-	buffer_put_cstring(m, kex->client_version_string);
-	buffer_put_cstring(m, kex->server_version_string);
-}
-
 void
 mm_send_keystate(struct monitor *monitor)
 {
-	Buffer m, *input, *output;
-	u_char *blob, *p;
-	u_int bloblen, plen;
-	u_int32_t seqnr, packets;
-	u_int64_t blocks, bytes;
+	struct ssh *ssh = active_state;		/* XXX */
+	struct sshbuf *m;
+	int r;
 
-	buffer_init(&m);
-
-	if (!compat20) {
-		u_char iv[24];
-		u_char *key;
-		u_int ivlen, keylen;
-
-		buffer_put_int(&m, packet_get_protocol_flags());
-
-		buffer_put_int(&m, packet_get_ssh1_cipher());
-
-		debug3("%s: Sending ssh1 KEY+IV", __func__);
-		keylen = packet_get_encryption_key(NULL);
-		key = xmalloc(keylen+1);	/* add 1 if keylen == 0 */
-		keylen = packet_get_encryption_key(key);
-		buffer_put_string(&m, key, keylen);
-		explicit_bzero(key, keylen);
-		free(key);
-
-		ivlen = packet_get_keyiv_len(MODE_OUT);
-		packet_get_keyiv(MODE_OUT, iv, ivlen);
-		buffer_put_string(&m, iv, ivlen);
-		ivlen = packet_get_keyiv_len(MODE_IN);
-		packet_get_keyiv(MODE_IN, iv, ivlen);
-		buffer_put_string(&m, iv, ivlen);
-		goto skip;
-	} else {
-		/* Kex for rekeying */
-		mm_send_kex(&m, *monitor->m_pkex);
-	}
-
-	debug3("%s: Sending new keys: %p %p",
-	    __func__, packet_get_newkeys(MODE_OUT),
-	    packet_get_newkeys(MODE_IN));
-
-	/* Keys from Kex */
-	if (!mm_newkeys_to_blob(MODE_OUT, &blob, &bloblen))
-		fatal("%s: conversion of newkeys failed", __func__);
-
-	buffer_put_string(&m, blob, bloblen);
-	free(blob);
-
-	if (!mm_newkeys_to_blob(MODE_IN, &blob, &bloblen))
-		fatal("%s: conversion of newkeys failed", __func__);
-
-	buffer_put_string(&m, blob, bloblen);
-	free(blob);
-
-	packet_get_state(MODE_OUT, &seqnr, &blocks, &packets, &bytes);
-	buffer_put_int(&m, seqnr);
-	buffer_put_int64(&m, blocks);
-	buffer_put_int(&m, packets);
-	buffer_put_int64(&m, bytes);
-	packet_get_state(MODE_IN, &seqnr, &blocks, &packets, &bytes);
-	buffer_put_int(&m, seqnr);
-	buffer_put_int64(&m, blocks);
-	buffer_put_int(&m, packets);
-	buffer_put_int64(&m, bytes);
-
-	debug3("%s: New keys have been sent", __func__);
- skip:
-	/* More key context */
-	plen = packet_get_keycontext(MODE_OUT, NULL);
-	p = xmalloc(plen+1);
-	packet_get_keycontext(MODE_OUT, p);
-	buffer_put_string(&m, p, plen);
-	free(p);
-
-	plen = packet_get_keycontext(MODE_IN, NULL);
-	p = xmalloc(plen+1);
-	packet_get_keycontext(MODE_IN, p);
-	buffer_put_string(&m, p, plen);
-	free(p);
-
-	/* Compression state */
-	debug3("%s: Sending compression state", __func__);
-	buffer_put_string(&m, &outgoing_stream, sizeof(outgoing_stream));
-	buffer_put_string(&m, &incoming_stream, sizeof(incoming_stream));
-
-	/* Network I/O buffers */
-	input = (Buffer *)packet_get_input();
-	output = (Buffer *)packet_get_output();
-	buffer_put_string(&m, buffer_ptr(input), buffer_len(input));
-	buffer_put_string(&m, buffer_ptr(output), buffer_len(output));
-
-	/* Roaming */
-	if (compat20) {
-		buffer_put_int64(&m, get_sent_bytes());
-		buffer_put_int64(&m, get_recv_bytes());
-	}
-
-	mm_request_send(monitor->m_recvfd, MONITOR_REQ_KEYEXPORT, &m);
+	if ((m = sshbuf_new()) == NULL)
+		fatal("%s: sshbuf_new failed", __func__);
+	if ((r = ssh_packet_get_state(ssh, m)) != 0)
+		fatal("%s: get_state failed: %s",
+		    __func__, ssh_err(r));
+	mm_request_send(monitor->m_recvfd, MONITOR_REQ_KEYEXPORT, m);
 	debug3("%s: Finished sending state", __func__);
-
-	buffer_free(&m);
+	sshbuf_free(m);
 }
 
 int
diff --git a/monitor_wrap.h b/monitor_wrap.h
index 18c2501..d97e8db 100644
--- a/monitor_wrap.h
+++ b/monitor_wrap.h
@@ -1,4 +1,4 @@
-/* $OpenBSD: monitor_wrap.h,v 1.24 2014/01/29 06:18:35 djm Exp $ */
+/* $OpenBSD: monitor_wrap.h,v 1.25 2015/01/19 19:52:16 markus Exp $ */
 
 /*
  * Copyright 2002 Niels Provos <provos@citi.umich.edu>
@@ -87,7 +87,7 @@
 int mm_ssh1_session_key(BIGNUM *);
 
 /* Key export functions */
-struct Newkeys *mm_newkeys_from_blob(u_char *, int);
+struct newkeys *mm_newkeys_from_blob(u_char *, int);
 int mm_newkeys_to_blob(int, u_char **, u_int *);
 
 void monitor_apply_keystate(struct monitor *);
@@ -103,9 +103,6 @@
 int mm_skey_respond(void *, u_int, char **);
 
 /* zlib allocation hooks */
-
-void *mm_zalloc(struct mm_master *, u_int, u_int);
-void mm_zfree(struct mm_master *, void *);
 void mm_init_compression(struct mm_master *);
 
 #endif /* _MM_WRAP_H_ */
diff --git a/opacket.c b/opacket.c
new file mode 100644
index 0000000..63b419d
--- /dev/null
+++ b/opacket.c
@@ -0,0 +1,279 @@
+/* Written by Markus Friedl. Placed in the public domain.  */
+
+#include "includes.h"
+
+#include "ssherr.h"
+#include "packet.h"
+#include "log.h"
+
+struct ssh *active_state, *backup_state;
+
+/* Map old to new API */
+
+void
+ssh_packet_start(struct ssh *ssh, u_char type)
+{
+	int r;
+
+	if ((r = sshpkt_start(ssh, type)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+
+void
+ssh_packet_put_char(struct ssh *ssh, int value)
+{
+	u_char ch = value;
+	int r;
+
+	if ((r = sshpkt_put_u8(ssh, ch)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+
+void
+ssh_packet_put_int(struct ssh *ssh, u_int value)
+{
+	int r;
+
+	if ((r = sshpkt_put_u32(ssh, value)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+
+void
+ssh_packet_put_int64(struct ssh *ssh, u_int64_t value)
+{
+	int r;
+
+	if ((r = sshpkt_put_u64(ssh, value)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+
+void
+ssh_packet_put_string(struct ssh *ssh, const void *buf, u_int len)
+{
+	int r;
+
+	if ((r = sshpkt_put_string(ssh, buf, len)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+
+void
+ssh_packet_put_cstring(struct ssh *ssh, const char *str)
+{
+	int r;
+
+	if ((r = sshpkt_put_cstring(ssh, str)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+
+void
+ssh_packet_put_raw(struct ssh *ssh, const void *buf, u_int len)
+{
+	int r;
+
+	if ((r = sshpkt_put(ssh, buf, len)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+
+#ifdef WITH_OPENSSL
+void
+ssh_packet_put_bignum(struct ssh *ssh, BIGNUM * value)
+{
+	int r;
+
+	if ((r = sshpkt_put_bignum1(ssh, value)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+
+void
+ssh_packet_put_bignum2(struct ssh *ssh, BIGNUM * value)
+{
+	int r;
+
+	if ((r = sshpkt_put_bignum2(ssh, value)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+
+void
+ssh_packet_put_ecpoint(struct ssh *ssh, const EC_GROUP *curve,
+    const EC_POINT *point)
+{
+	int r;
+
+	if ((r = sshpkt_put_ec(ssh, point, curve)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+#endif /* WITH_OPENSSL */
+
+void
+ssh_packet_send(struct ssh *ssh)
+{
+	int r;
+
+	if ((r = sshpkt_send(ssh)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+
+u_int
+ssh_packet_get_char(struct ssh *ssh)
+{
+	u_char ch;
+	int r;
+
+	if ((r = sshpkt_get_u8(ssh, &ch)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+	return ch;
+}
+
+u_int
+ssh_packet_get_int(struct ssh *ssh)
+{
+	u_int val;
+	int r;
+
+	if ((r = sshpkt_get_u32(ssh, &val)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+	return val;
+}
+
+u_int64_t
+ssh_packet_get_int64(struct ssh *ssh)
+{
+	u_int64_t val;
+	int r;
+
+	if ((r = sshpkt_get_u64(ssh, &val)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+	return val;
+}
+
+#ifdef WITH_OPENSSL
+void
+ssh_packet_get_bignum(struct ssh *ssh, BIGNUM * value)
+{
+	int r;
+
+	if ((r = sshpkt_get_bignum1(ssh, value)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+
+void
+ssh_packet_get_bignum2(struct ssh *ssh, BIGNUM * value)
+{
+	int r;
+
+	if ((r = sshpkt_get_bignum2(ssh, value)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+
+void
+ssh_packet_get_ecpoint(struct ssh *ssh, const EC_GROUP *curve, EC_POINT *point)
+{
+	int r;
+
+	if ((r = sshpkt_get_ec(ssh, point, curve)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+}
+#endif /* WITH_OPENSSL */
+
+void *
+ssh_packet_get_string(struct ssh *ssh, u_int *length_ptr)
+{
+	int r;
+	size_t len;
+	u_char *val;
+
+	if ((r = sshpkt_get_string(ssh, &val, &len)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+	if (length_ptr != NULL)
+		*length_ptr = (u_int)len;
+	return val;
+}
+
+const void *
+ssh_packet_get_string_ptr(struct ssh *ssh, u_int *length_ptr)
+{
+	int r;
+	size_t len;
+	const u_char *val;
+
+	if ((r = sshpkt_get_string_direct(ssh, &val, &len)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+	if (length_ptr != NULL)
+		*length_ptr = (u_int)len;
+	return val;
+}
+
+char *
+ssh_packet_get_cstring(struct ssh *ssh, u_int *length_ptr)
+{
+	int r;
+	size_t len;
+	char *val;
+
+	if ((r = sshpkt_get_cstring(ssh, &val, &len)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+	if (length_ptr != NULL)
+		*length_ptr = (u_int)len;
+	return val;
+}
+
+/* Old API, that had to be reimplemented */
+
+void
+packet_set_connection(int fd_in, int fd_out)
+{
+	active_state = ssh_packet_set_connection(active_state, fd_in, fd_out);
+}
+
+void
+packet_backup_state(void)
+{
+	ssh_packet_backup_state(active_state, backup_state);
+}
+
+void
+packet_restore_state(void)
+{
+	ssh_packet_restore_state(active_state, backup_state);
+}
+
+u_int
+packet_get_char(void)
+{
+	return (ssh_packet_get_char(active_state));
+}
+
+u_int
+packet_get_int(void)
+{
+	return (ssh_packet_get_int(active_state));
+}
+
+int
+packet_read_seqnr(u_int32_t *seqnr)
+{
+	u_char type;
+	int r;
+
+	if ((r = ssh_packet_read_seqnr(active_state, &type, seqnr)))
+		fatal("%s: %s", __func__, ssh_err(r));
+	return type;
+}
+
+int
+packet_read_poll_seqnr(u_int32_t *seqnr)
+{
+	u_char type;
+	int r;
+
+	if ((r = ssh_packet_read_poll_seqnr(active_state, &type, seqnr)))
+		fatal("%s: %s", __func__, ssh_err(r));
+	return type;
+}
+
+void
+packet_close(void)
+{
+	ssh_packet_close(active_state);
+	active_state = NULL;
+}
diff --git a/opacket.h b/opacket.h
new file mode 100644
index 0000000..1e15626
--- /dev/null
+++ b/opacket.h
@@ -0,0 +1,173 @@
+#ifndef _OPACKET_H
+/* Written by Markus Friedl. Placed in the public domain.  */
+
+/* Map old to new API */
+void     ssh_packet_start(struct ssh *, u_char);
+void     ssh_packet_put_char(struct ssh *, int ch);
+void     ssh_packet_put_int(struct ssh *, u_int value);
+void     ssh_packet_put_int64(struct ssh *, u_int64_t value);
+void     ssh_packet_put_bignum(struct ssh *, BIGNUM * value);
+void     ssh_packet_put_bignum2(struct ssh *, BIGNUM * value);
+void     ssh_packet_put_ecpoint(struct ssh *, const EC_GROUP *, const EC_POINT *);
+void     ssh_packet_put_string(struct ssh *, const void *buf, u_int len);
+void     ssh_packet_put_cstring(struct ssh *, const char *str);
+void     ssh_packet_put_raw(struct ssh *, const void *buf, u_int len);
+void     ssh_packet_send(struct ssh *);
+
+u_int	 ssh_packet_get_char(struct ssh *);
+u_int	 ssh_packet_get_int(struct ssh *);
+u_int64_t ssh_packet_get_int64(struct ssh *);
+void     ssh_packet_get_bignum(struct ssh *, BIGNUM * value);
+void     ssh_packet_get_bignum2(struct ssh *, BIGNUM * value);
+void	 ssh_packet_get_ecpoint(struct ssh *, const EC_GROUP *, EC_POINT *);
+void	*ssh_packet_get_string(struct ssh *, u_int *length_ptr);
+char	*ssh_packet_get_cstring(struct ssh *, u_int *length_ptr);
+
+/* don't allow remaining bytes after the end of the message */
+#define ssh_packet_check_eom(ssh) \
+do { \
+	int _len = ssh_packet_remaining(ssh); \
+	if (_len > 0) { \
+		logit("Packet integrity error (%d bytes remaining) at %s:%d", \
+		    _len ,__FILE__, __LINE__); \
+		ssh_packet_disconnect(ssh, \
+		    "Packet integrity error."); \
+	} \
+} while (0)
+
+/* old API */
+void	 packet_close(void);
+u_int	 packet_get_char(void);
+u_int	 packet_get_int(void);
+void	 packet_backup_state(void);
+void	 packet_restore_state(void);
+void     packet_set_connection(int, int);
+int	 packet_read_seqnr(u_int32_t *);
+int	 packet_read_poll_seqnr(u_int32_t *);
+#define packet_set_timeout(timeout, count) \
+	ssh_packet_set_timeout(active_state, (timeout), (count))
+#define packet_connection_is_on_socket() \
+	ssh_packet_connection_is_on_socket(active_state)
+#define packet_set_nonblocking() \
+	ssh_packet_set_nonblocking(active_state)
+#define packet_get_connection_in() \
+	ssh_packet_get_connection_in(active_state)
+#define packet_get_connection_out() \
+	ssh_packet_get_connection_out(active_state)
+#define packet_set_protocol_flags(protocol_flags) \
+	ssh_packet_set_protocol_flags(active_state, (protocol_flags))
+#define packet_get_protocol_flags() \
+	ssh_packet_get_protocol_flags(active_state)
+#define packet_start_compression(level) \
+	ssh_packet_start_compression(active_state, (level))
+#define packet_set_encryption_key(key, keylen, number) \
+	ssh_packet_set_encryption_key(active_state, (key), (keylen), (number))
+#define packet_start(type) \
+	ssh_packet_start(active_state, (type))
+#define packet_put_char(value) \
+	ssh_packet_put_char(active_state, (value))
+#define packet_put_int(value) \
+	ssh_packet_put_int(active_state, (value))
+#define packet_put_int64(value) \
+	ssh_packet_put_int64(active_state, (value))
+#define packet_put_string( buf, len) \
+	ssh_packet_put_string(active_state, (buf), (len))
+#define packet_put_cstring(str) \
+	ssh_packet_put_cstring(active_state, (str))
+#define packet_put_raw(buf, len) \
+	ssh_packet_put_raw(active_state, (buf), (len))
+#define packet_put_bignum(value) \
+	ssh_packet_put_bignum(active_state, (value))
+#define packet_put_bignum2(value) \
+	ssh_packet_put_bignum2(active_state, (value))
+#define packet_send() \
+	ssh_packet_send(active_state)
+#define packet_read() \
+	ssh_packet_read(active_state)
+#define packet_read_expect(expected_type) \
+	ssh_packet_read_expect(active_state, (expected_type))
+#define packet_process_incoming(buf, len) \
+	ssh_packet_process_incoming(active_state, (buf), (len))
+#define packet_get_int64() \
+	ssh_packet_get_int64(active_state)
+#define packet_get_bignum(value) \
+	ssh_packet_get_bignum(active_state, (value))
+#define packet_get_bignum2(value) \
+	ssh_packet_get_bignum2(active_state, (value))
+#define packet_remaining() \
+	ssh_packet_remaining(active_state)
+#define packet_get_string(length_ptr) \
+	ssh_packet_get_string(active_state, (length_ptr))
+#define packet_get_string_ptr(length_ptr) \
+	ssh_packet_get_string_ptr(active_state, (length_ptr))
+#define packet_get_cstring(length_ptr) \
+	ssh_packet_get_cstring(active_state, (length_ptr))
+#define packet_send_debug(fmt, args...) \
+	ssh_packet_send_debug(active_state, (fmt), ##args)
+#define packet_disconnect(fmt, args...) \
+	ssh_packet_disconnect(active_state, (fmt), ##args)
+#define packet_write_poll() \
+	ssh_packet_write_poll(active_state)
+#define packet_write_wait() \
+	ssh_packet_write_wait(active_state)
+#define packet_have_data_to_write() \
+	ssh_packet_have_data_to_write(active_state)
+#define packet_not_very_much_data_to_write() \
+	ssh_packet_not_very_much_data_to_write(active_state)
+#define packet_set_interactive(interactive, qos_interactive, qos_bulk) \
+	ssh_packet_set_interactive(active_state, (interactive), (qos_interactive), (qos_bulk))
+#define packet_is_interactive() \
+	ssh_packet_is_interactive(active_state)
+#define packet_set_maxsize(s) \
+	ssh_packet_set_maxsize(active_state, (s))
+#define packet_inc_alive_timeouts() \
+	ssh_packet_inc_alive_timeouts(active_state)
+#define packet_set_alive_timeouts(ka) \
+	ssh_packet_set_alive_timeouts(active_state, (ka))
+#define packet_get_maxsize() \
+	ssh_packet_get_maxsize(active_state)
+#define packet_add_padding(pad) \
+	sshpkt_add_padding(active_state, (pad))
+#define packet_send_ignore(nbytes) \
+	ssh_packet_send_ignore(active_state, (nbytes))
+#define packet_need_rekeying() \
+	ssh_packet_need_rekeying(active_state)
+#define packet_set_rekey_limit(bytes) \
+	ssh_packet_set_rekey_limit(active_state, (bytes))
+#define packet_set_server() \
+	ssh_packet_set_server(active_state)
+#define packet_set_authenticated() \
+	ssh_packet_set_authenticated(active_state)
+#define packet_get_input() \
+	ssh_packet_get_input(active_state)
+#define packet_get_output() \
+	ssh_packet_get_output(active_state)
+#define packet_set_compress_hooks(ctx, allocfunc, freefunc) \
+	ssh_packet_set_compress_hooks(active_state, ctx, \
+	    allocfunc, freefunc);
+#define packet_check_eom() \
+	ssh_packet_check_eom(active_state)
+#define set_newkeys(mode) \
+	ssh_set_newkeys(active_state, (mode))
+#define packet_get_state(m) \
+	ssh_packet_get_state(active_state, m)
+#define packet_set_state(m) \
+	ssh_packet_set_state(active_state, m)
+#if 0
+#define get_remote_ipaddr() \
+	ssh_remote_ipaddr(active_state)
+#endif
+#define packet_get_raw(lenp) \
+        sshpkt_ptr(active_state, lenp)
+#define packet_get_ecpoint(c,p) \
+	ssh_packet_get_ecpoint(active_state, c, p)
+#define packet_put_ecpoint(c,p) \
+	ssh_packet_put_ecpoint(active_state, c, p)
+#define packet_get_rekey_timeout() \
+	ssh_packet_get_rekey_timeout(active_state)
+#define packet_set_rekey_limits(x,y) \
+	ssh_packet_set_rekey_limits(active_state, x, y)
+#define packet_get_bytes(x,y) \
+	ssh_packet_get_bytes(active_state, x, y)
+
+#endif /* _OPACKET_H */
diff --git a/packet.c b/packet.c
index d6f9ff3..3306e4d 100644
--- a/packet.c
+++ b/packet.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: packet.c,v 1.200 2015/01/13 19:31:40 markus Exp $ */
+/* $OpenBSD: packet.c,v 1.201 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Author: Tatu Ylonen <ylo@cs.hut.fi>
  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -60,17 +60,19 @@
 #include <signal.h>
 #include <time.h>
 
+#include <zlib.h>
+
+#include "buffer.h"	/* typedefs XXX */
+#include "key.h"	/* typedefs XXX */
+
 #include "xmalloc.h"
-#include "buffer.h"
-#include "packet.h"
 #include "crc32.h"
-#include "compress.h"
 #include "deattack.h"
 #include "compat.h"
 #include "ssh1.h"
 #include "ssh2.h"
 #include "cipher.h"
-#include "key.h"
+#include "sshkey.h"
 #include "kex.h"
 #include "digest.h"
 #include "mac.h"
@@ -79,8 +81,10 @@
 #include "misc.h"
 #include "channels.h"
 #include "ssh.h"
-#include "ssherr.h"
+#include "packet.h"
 #include "roaming.h"
+#include "ssherr.h"
+#include "sshbuf.h"
 
 #ifdef PACKET_DEBUG
 #define DBG(x) x
@@ -100,7 +104,7 @@
 struct packet {
 	TAILQ_ENTRY(packet) next;
 	u_char type;
-	Buffer payload;
+	struct sshbuf *payload;
 };
 
 struct session_state {
@@ -117,26 +121,33 @@
 	u_int remote_protocol_flags;
 
 	/* Encryption context for receiving data.  Only used for decryption. */
-	CipherContext receive_context;
+	struct sshcipher_ctx receive_context;
 
 	/* Encryption context for sending data.  Only used for encryption. */
-	CipherContext send_context;
+	struct sshcipher_ctx send_context;
 
 	/* Buffer for raw input data from the socket. */
-	Buffer input;
+	struct sshbuf *input;
 
 	/* Buffer for raw output data going to the socket. */
-	Buffer output;
+	struct sshbuf *output;
 
 	/* Buffer for the partial outgoing packet being constructed. */
-	Buffer outgoing_packet;
+	struct sshbuf *outgoing_packet;
 
 	/* Buffer for the incoming packet currently being processed. */
-	Buffer incoming_packet;
+	struct sshbuf *incoming_packet;
 
 	/* Scratch buffer for packet compression/decompression. */
-	Buffer compression_buffer;
-	int compression_buffer_ready;
+	struct sshbuf *compression_buffer;
+
+	/* Incoming/outgoing compression dictionaries */
+	z_stream compression_in_stream;
+	z_stream compression_out_stream;
+	int compression_in_started;
+	int compression_out_started;
+	int compression_in_failures;
+	int compression_out_failures;
 
 	/*
 	 * Flag indicating whether packet compression/decompression is
@@ -165,7 +176,7 @@
 	int packet_timeout_ms;
 
 	/* Session key information for Encryption and MAC */
-	Newkeys *newkeys[MODE_MAX];
+	struct newkeys *newkeys[MODE_MAX];
 	struct packet_state p_read, p_send;
 
 	/* Volume-based rekeying */
@@ -185,7 +196,7 @@
 
 	/* XXX discard incoming data after MAC error */
 	u_int packet_discard;
-	Mac *packet_discard_mac;
+	struct sshmac *packet_discard_mac;
 
 	/* Used in packet_read_poll2() */
 	u_int packlen;
@@ -199,121 +210,164 @@
 	/* Used in packet_set_maxsize */
 	int set_maxsize_called;
 
+	/* One-off warning about weak ciphers */
+	int cipher_warning_done;
+
+	/* SSH1 CRC compensation attack detector */
+	struct deattack_ctx deattack;
+
 	TAILQ_HEAD(, packet) outgoing;
 };
 
-static struct session_state *active_state, *backup_state;
-
-static struct session_state *
-alloc_session_state(void)
+struct ssh *
+ssh_alloc_session_state(void)
 {
-	struct session_state *s = xcalloc(1, sizeof(*s));
+	struct ssh *ssh = NULL;
+	struct session_state *state = NULL;
 
-	s->connection_in = -1;
-	s->connection_out = -1;
-	s->max_packet_size = 32768;
-	s->packet_timeout_ms = -1;
-	return s;
+	if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
+	    (state = calloc(1, sizeof(*state))) == NULL ||
+	    (state->input = sshbuf_new()) == NULL ||
+	    (state->output = sshbuf_new()) == NULL ||
+	    (state->outgoing_packet = sshbuf_new()) == NULL ||
+	    (state->incoming_packet = sshbuf_new()) == NULL)
+		goto fail;
+	TAILQ_INIT(&state->outgoing);
+	state->connection_in = -1;
+	state->connection_out = -1;
+	state->max_packet_size = 32768;
+	state->packet_timeout_ms = -1;
+	state->p_send.packets = state->p_read.packets = 0;
+	state->initialized = 1;
+	/*
+	 * ssh_packet_send2() needs to queue packets until
+	 * we've done the initial key exchange.
+	 */
+	state->rekeying = 1;
+	ssh->state = state;
+	return ssh;
+ fail:
+	if (state) {
+		sshbuf_free(state->input);
+		sshbuf_free(state->output);
+		sshbuf_free(state->incoming_packet);
+		sshbuf_free(state->outgoing_packet);
+		free(state);
+	}
+	free(ssh);
+	return NULL;
 }
 
 /*
  * Sets the descriptors used for communication.  Disables encryption until
  * packet_set_encryption_key is called.
  */
-void
-packet_set_connection(int fd_in, int fd_out)
+struct ssh *
+ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
 {
-	const Cipher *none = cipher_by_name("none");
+	struct session_state *state;
+	const struct sshcipher *none = cipher_by_name("none");
 	int r;
 
 	if (none == NULL)
-		fatal("packet_set_connection: cannot load cipher 'none'");
-	if (active_state == NULL)
-		active_state = alloc_session_state();
-	active_state->connection_in = fd_in;
-	active_state->connection_out = fd_out;
-	if ((r = cipher_init(&active_state->send_context, none,
+		fatal("%s: cannot load cipher 'none'", __func__);
+	if (ssh == NULL)
+		ssh = ssh_alloc_session_state();
+	if (ssh == NULL)
+		fatal("%s: cound not allocate state", __func__);
+	state = ssh->state;
+	state->connection_in = fd_in;
+	state->connection_out = fd_out;
+	if ((r = cipher_init(&state->send_context, none,
 	    (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
-	    (r = cipher_init(&active_state->receive_context, none,
+	    (r = cipher_init(&state->receive_context, none,
 	    (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0)
-		fatal("%s: cipher_init: %s", __func__, ssh_err(r));
-	active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
-	if (!active_state->initialized) {
-		active_state->initialized = 1;
-		buffer_init(&active_state->input);
-		buffer_init(&active_state->output);
-		buffer_init(&active_state->outgoing_packet);
-		buffer_init(&active_state->incoming_packet);
-		TAILQ_INIT(&active_state->outgoing);
-		active_state->p_send.packets = active_state->p_read.packets = 0;
-	}
+		fatal("%s: cipher_init failed: %s", __func__, ssh_err(r));
+	state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
+	deattack_init(&state->deattack);
+	return ssh;
 }
 
 void
-packet_set_timeout(int timeout, int count)
+ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
 {
+	struct session_state *state = ssh->state;
+
 	if (timeout <= 0 || count <= 0) {
-		active_state->packet_timeout_ms = -1;
+		state->packet_timeout_ms = -1;
 		return;
 	}
 	if ((INT_MAX / 1000) / count < timeout)
-		active_state->packet_timeout_ms = INT_MAX;
+		state->packet_timeout_ms = INT_MAX;
 	else
-		active_state->packet_timeout_ms = timeout * count * 1000;
+		state->packet_timeout_ms = timeout * count * 1000;
 }
 
-static void
-packet_stop_discard(void)
+int
+ssh_packet_stop_discard(struct ssh *ssh)
 {
-	if (active_state->packet_discard_mac) {
+	struct session_state *state = ssh->state;
+	int r;
+
+	if (state->packet_discard_mac) {
 		char buf[1024];
-		
+
 		memset(buf, 'a', sizeof(buf));
-		while (buffer_len(&active_state->incoming_packet) <
+		while (sshbuf_len(state->incoming_packet) <
 		    PACKET_MAX_SIZE)
-			buffer_append(&active_state->incoming_packet, buf,
-			    sizeof(buf));
-		(void) mac_compute(active_state->packet_discard_mac,
-		    active_state->p_read.seqnr,
-		    buffer_ptr(&active_state->incoming_packet),
-		    PACKET_MAX_SIZE, NULL, 0);
+			if ((r = sshbuf_put(state->incoming_packet, buf,
+			    sizeof(buf))) != 0)
+				return r;
+		(void) mac_compute(state->packet_discard_mac,
+		    state->p_read.seqnr,
+		    sshbuf_ptr(state->incoming_packet), PACKET_MAX_SIZE,
+		    NULL, 0);
 	}
-	logit("Finished discarding for %.200s", get_remote_ipaddr());
-	cleanup_exit(255);
+	logit("Finished discarding for %.200s", ssh_remote_ipaddr(ssh));
+	return SSH_ERR_MAC_INVALID;
 }
 
-static void
-packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
+static int
+ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
+    struct sshmac *mac, u_int packet_length, u_int discard)
 {
-	if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm))
-		packet_disconnect("Packet corrupt");
+	struct session_state *state = ssh->state;
+	int r;
+
+	if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
+		if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
+			return r;
+		return SSH_ERR_MAC_INVALID;
+	}
 	if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
-		active_state->packet_discard_mac = mac;
-	if (buffer_len(&active_state->input) >= discard)
-		packet_stop_discard();
-	active_state->packet_discard = discard -
-	    buffer_len(&active_state->input);
+		state->packet_discard_mac = mac;
+	if (sshbuf_len(state->input) >= discard &&
+	   (r = ssh_packet_stop_discard(ssh)) != 0)
+		return r;
+	state->packet_discard = discard - sshbuf_len(state->input);
+	return 0;
 }
 
 /* Returns 1 if remote host is connected via socket, 0 if not. */
 
 int
-packet_connection_is_on_socket(void)
+ssh_packet_connection_is_on_socket(struct ssh *ssh)
 {
+	struct session_state *state = ssh->state;
 	struct sockaddr_storage from, to;
 	socklen_t fromlen, tolen;
 
 	/* filedescriptors in and out are the same, so it's a socket */
-	if (active_state->connection_in == active_state->connection_out)
+	if (state->connection_in == state->connection_out)
 		return 1;
 	fromlen = sizeof(from);
 	memset(&from, 0, sizeof(from));
-	if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
+	if (getpeername(state->connection_in, (struct sockaddr *)&from,
 	    &fromlen) < 0)
 		return 0;
 	tolen = sizeof(to);
 	memset(&to, 0, sizeof(to));
-	if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
+	if (getpeername(state->connection_out, (struct sockaddr *)&to,
 	    &tolen) < 0)
 		return 0;
 	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
@@ -323,127 +377,23 @@
 	return 1;
 }
 
-/*
- * Exports an IV from the CipherContext required to export the key
- * state back from the unprivileged child to the privileged parent
- * process.
- */
-
 void
-packet_get_keyiv(int mode, u_char *iv, u_int len)
+ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
 {
-	CipherContext *cc;
-	int r;
-
-	if (mode == MODE_OUT)
-		cc = &active_state->send_context;
-	else
-		cc = &active_state->receive_context;
-
-	if ((r = cipher_get_keyiv(cc, iv, len)) != 0)
-		fatal("%s: cipher_get_keyiv: %s", __func__, ssh_err(r));
+	if (ibytes)
+		*ibytes = ssh->state->p_read.bytes;
+	if (obytes)
+		*obytes = ssh->state->p_send.bytes;
 }
 
 int
-packet_get_keycontext(int mode, u_char *dat)
-{
-	CipherContext *cc;
-
-	if (mode == MODE_OUT)
-		cc = &active_state->send_context;
-	else
-		cc = &active_state->receive_context;
-
-	return (cipher_get_keycontext(cc, dat));
-}
-
-void
-packet_set_keycontext(int mode, u_char *dat)
-{
-	CipherContext *cc;
-
-	if (mode == MODE_OUT)
-		cc = &active_state->send_context;
-	else
-		cc = &active_state->receive_context;
-
-	cipher_set_keycontext(cc, dat);
-}
-
-int
-packet_get_keyiv_len(int mode)
-{
-	CipherContext *cc;
-
-	if (mode == MODE_OUT)
-		cc = &active_state->send_context;
-	else
-		cc = &active_state->receive_context;
-
-	return (cipher_get_keyiv_len(cc));
-}
-
-void
-packet_set_iv(int mode, u_char *dat)
-{
-	CipherContext *cc;
-	int r;
-
-	if (mode == MODE_OUT)
-		cc = &active_state->send_context;
-	else
-		cc = &active_state->receive_context;
-
-	if ((r = cipher_set_keyiv(cc, dat)) != 0)
-		fatal("%s: cipher_set_keyiv: %s", __func__, ssh_err(r));
-}
-
-int
-packet_get_ssh1_cipher(void)
-{
-	return (cipher_get_number(active_state->receive_context.cipher));
-}
-
-void
-packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks,
-    u_int32_t *packets, u_int64_t *bytes)
-{
-	struct packet_state *state;
-
-	state = (mode == MODE_IN) ?
-	    &active_state->p_read : &active_state->p_send;
-	if (seqnr)
-		*seqnr = state->seqnr;
-	if (blocks)
-		*blocks = state->blocks;
-	if (packets)
-		*packets = state->packets;
-	if (bytes)
-		*bytes = state->bytes;
-}
-
-void
-packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
-    u_int64_t bytes)
-{
-	struct packet_state *state;
-
-	state = (mode == MODE_IN) ?
-	    &active_state->p_read : &active_state->p_send;
-	state->seqnr = seqnr;
-	state->blocks = blocks;
-	state->packets = packets;
-	state->bytes = bytes;
-}
-
-static int
-packet_connection_af(void)
+ssh_packet_connection_af(struct ssh *ssh)
 {
 	struct sockaddr_storage to;
 	socklen_t tolen = sizeof(to);
 
 	memset(&to, 0, sizeof(to));
-	if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
+	if (getsockname(ssh->state->connection_out, (struct sockaddr *)&to,
 	    &tolen) < 0)
 		return 0;
 #ifdef IPV4_IN_IPV6
@@ -457,72 +407,125 @@
 /* Sets the connection into non-blocking mode. */
 
 void
-packet_set_nonblocking(void)
+ssh_packet_set_nonblocking(struct ssh *ssh)
 {
 	/* Set the socket into non-blocking mode. */
-	set_nonblock(active_state->connection_in);
+	set_nonblock(ssh->state->connection_in);
 
-	if (active_state->connection_out != active_state->connection_in)
-		set_nonblock(active_state->connection_out);
+	if (ssh->state->connection_out != ssh->state->connection_in)
+		set_nonblock(ssh->state->connection_out);
 }
 
 /* Returns the socket used for reading. */
 
 int
-packet_get_connection_in(void)
+ssh_packet_get_connection_in(struct ssh *ssh)
 {
-	return active_state->connection_in;
+	return ssh->state->connection_in;
 }
 
 /* Returns the descriptor used for writing. */
 
 int
-packet_get_connection_out(void)
+ssh_packet_get_connection_out(struct ssh *ssh)
 {
-	return active_state->connection_out;
+	return ssh->state->connection_out;
+}
+
+/*
+ * Returns the IP-address of the remote host as a string.  The returned
+ * string must not be freed.
+ */
+
+const char *
+ssh_remote_ipaddr(struct ssh *ssh)
+{
+	/* Check whether we have cached the ipaddr. */
+	if (ssh->remote_ipaddr == NULL)
+		ssh->remote_ipaddr = ssh_packet_connection_is_on_socket(ssh) ?
+		    get_peer_ipaddr(ssh->state->connection_in) :
+		    strdup("UNKNOWN");
+	if (ssh->remote_ipaddr == NULL)
+		return "UNKNOWN";
+	return ssh->remote_ipaddr;
 }
 
 /* Closes the connection and clears and frees internal data structures. */
 
 void
-packet_close(void)
+ssh_packet_close(struct ssh *ssh)
 {
-	if (!active_state->initialized)
+	struct session_state *state = ssh->state;
+	int r;
+	u_int mode;
+
+	if (!state->initialized)
 		return;
-	active_state->initialized = 0;
-	if (active_state->connection_in == active_state->connection_out) {
-		shutdown(active_state->connection_out, SHUT_RDWR);
-		close(active_state->connection_out);
+	state->initialized = 0;
+	if (state->connection_in == state->connection_out) {
+		shutdown(state->connection_out, SHUT_RDWR);
+		close(state->connection_out);
 	} else {
-		close(active_state->connection_in);
-		close(active_state->connection_out);
+		close(state->connection_in);
+		close(state->connection_out);
 	}
-	buffer_free(&active_state->input);
-	buffer_free(&active_state->output);
-	buffer_free(&active_state->outgoing_packet);
-	buffer_free(&active_state->incoming_packet);
-	if (active_state->compression_buffer_ready) {
-		buffer_free(&active_state->compression_buffer);
-		buffer_compress_uninit();
+	sshbuf_free(state->input);
+	sshbuf_free(state->output);
+	sshbuf_free(state->outgoing_packet);
+	sshbuf_free(state->incoming_packet);
+	for (mode = 0; mode < MODE_MAX; mode++)
+		kex_free_newkeys(state->newkeys[mode]);
+	if (state->compression_buffer) {
+		sshbuf_free(state->compression_buffer);
+		if (state->compression_out_started) {
+			z_streamp stream = &state->compression_out_stream;
+			debug("compress outgoing: "
+			    "raw data %llu, compressed %llu, factor %.2f",
+				(unsigned long long)stream->total_in,
+				(unsigned long long)stream->total_out,
+				stream->total_in == 0 ? 0.0 :
+				(double) stream->total_out / stream->total_in);
+			if (state->compression_out_failures == 0)
+				deflateEnd(stream);
+		}
+		if (state->compression_in_started) {
+			z_streamp stream = &state->compression_out_stream;
+			debug("compress incoming: "
+			    "raw data %llu, compressed %llu, factor %.2f",
+			    (unsigned long long)stream->total_out,
+			    (unsigned long long)stream->total_in,
+			    stream->total_out == 0 ? 0.0 :
+			    (double) stream->total_in / stream->total_out);
+			if (state->compression_in_failures == 0)
+				inflateEnd(stream);
+		}
 	}
-	cipher_cleanup(&active_state->send_context);
-	cipher_cleanup(&active_state->receive_context);
+	if ((r = cipher_cleanup(&state->send_context)) != 0)
+		error("%s: cipher_cleanup failed: %s", __func__, ssh_err(r));
+	if ((r = cipher_cleanup(&state->receive_context)) != 0)
+		error("%s: cipher_cleanup failed: %s", __func__, ssh_err(r));
+	if (ssh->remote_ipaddr) {
+		free(ssh->remote_ipaddr);
+		ssh->remote_ipaddr = NULL;
+	}
+	free(ssh->state);
+	ssh->state = NULL;
 }
 
 /* Sets remote side protocol flags. */
 
 void
-packet_set_protocol_flags(u_int protocol_flags)
+ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
 {
-	active_state->remote_protocol_flags = protocol_flags;
+	ssh->state->remote_protocol_flags = protocol_flags;
 }
 
 /* Returns the remote protocol flags set earlier by the above function. */
 
 u_int
-packet_get_protocol_flags(void)
+ssh_packet_get_protocol_flags(struct ssh *ssh)
 {
-	return active_state->remote_protocol_flags;
+	return ssh->state->remote_protocol_flags;
 }
 
 /*
@@ -530,24 +533,239 @@
  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
  */
 
-static void
-packet_init_compression(void)
+static int
+ssh_packet_init_compression(struct ssh *ssh)
 {
-	if (active_state->compression_buffer_ready == 1)
-		return;
-	active_state->compression_buffer_ready = 1;
-	buffer_init(&active_state->compression_buffer);
+	if (!ssh->state->compression_buffer &&
+	   ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
+		return SSH_ERR_ALLOC_FAIL;
+	return 0;
+}
+
+static int
+start_compression_out(struct ssh *ssh, int level)
+{
+	if (level < 1 || level > 9)
+		return SSH_ERR_INVALID_ARGUMENT;
+	debug("Enabling compression at level %d.", level);
+	if (ssh->state->compression_out_started == 1)
+		deflateEnd(&ssh->state->compression_out_stream);
+	switch (deflateInit(&ssh->state->compression_out_stream, level)) {
+	case Z_OK:
+		ssh->state->compression_out_started = 1;
+		break;
+	case Z_MEM_ERROR:
+		return SSH_ERR_ALLOC_FAIL;
+	default:
+		return SSH_ERR_INTERNAL_ERROR;
+	}
+	return 0;
+}
+
+static int
+start_compression_in(struct ssh *ssh)
+{
+	if (ssh->state->compression_in_started == 1)
+		inflateEnd(&ssh->state->compression_in_stream);
+	switch (inflateInit(&ssh->state->compression_in_stream)) {
+	case Z_OK:
+		ssh->state->compression_in_started = 1;
+		break;
+	case Z_MEM_ERROR:
+		return SSH_ERR_ALLOC_FAIL;
+	default:
+		return SSH_ERR_INTERNAL_ERROR;
+	}
+	return 0;
+}
+
+int
+ssh_packet_start_compression(struct ssh *ssh, int level)
+{
+	int r;
+
+	if (ssh->state->packet_compression && !compat20)
+		return SSH_ERR_INTERNAL_ERROR;
+	ssh->state->packet_compression = 1;
+	if ((r = ssh_packet_init_compression(ssh)) != 0 ||
+	    (r = start_compression_in(ssh)) != 0 ||
+	    (r = start_compression_out(ssh, level)) != 0)
+		return r;
+	return 0;
+}
+
+/* XXX remove need for separate compression buffer */
+static int
+compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
+{
+	u_char buf[4096];
+	int r, status;
+
+	if (ssh->state->compression_out_started != 1)
+		return SSH_ERR_INTERNAL_ERROR;
+
+	/* This case is not handled below. */
+	if (sshbuf_len(in) == 0)
+		return 0;
+
+	/* Input is the contents of the input buffer. */
+	if ((ssh->state->compression_out_stream.next_in =
+	    sshbuf_mutable_ptr(in)) == NULL)
+		return SSH_ERR_INTERNAL_ERROR;
+	ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
+
+	/* Loop compressing until deflate() returns with avail_out != 0. */
+	do {
+		/* Set up fixed-size output buffer. */
+		ssh->state->compression_out_stream.next_out = buf;
+		ssh->state->compression_out_stream.avail_out = sizeof(buf);
+
+		/* Compress as much data into the buffer as possible. */
+		status = deflate(&ssh->state->compression_out_stream,
+		    Z_PARTIAL_FLUSH);
+		switch (status) {
+		case Z_MEM_ERROR:
+			return SSH_ERR_ALLOC_FAIL;
+		case Z_OK:
+			/* Append compressed data to output_buffer. */
+			if ((r = sshbuf_put(out, buf, sizeof(buf) -
+			    ssh->state->compression_out_stream.avail_out)) != 0)
+				return r;
+			break;
+		case Z_STREAM_ERROR:
+		default:
+			ssh->state->compression_out_failures++;
+			return SSH_ERR_INVALID_FORMAT;
+		}
+	} while (ssh->state->compression_out_stream.avail_out == 0);
+	return 0;
+}
+
+static int
+uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
+{
+	u_char buf[4096];
+	int r, status;
+
+	if (ssh->state->compression_in_started != 1)
+		return SSH_ERR_INTERNAL_ERROR;
+
+	if ((ssh->state->compression_in_stream.next_in =
+	    sshbuf_mutable_ptr(in)) == NULL)
+		return SSH_ERR_INTERNAL_ERROR;
+	ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
+
+	for (;;) {
+		/* Set up fixed-size output buffer. */
+		ssh->state->compression_in_stream.next_out = buf;
+		ssh->state->compression_in_stream.avail_out = sizeof(buf);
+
+		status = inflate(&ssh->state->compression_in_stream,
+		    Z_PARTIAL_FLUSH);
+		switch (status) {
+		case Z_OK:
+			if ((r = sshbuf_put(out, buf, sizeof(buf) -
+			    ssh->state->compression_in_stream.avail_out)) != 0)
+				return r;
+			break;
+		case Z_BUF_ERROR:
+			/*
+			 * Comments in zlib.h say that we should keep calling
+			 * inflate() until we get an error.  This appears to
+			 * be the error that we get.
+			 */
+			return 0;
+		case Z_DATA_ERROR:
+			return SSH_ERR_INVALID_FORMAT;
+		case Z_MEM_ERROR:
+			return SSH_ERR_ALLOC_FAIL;
+		case Z_STREAM_ERROR:
+		default:
+			ssh->state->compression_in_failures++;
+			return SSH_ERR_INTERNAL_ERROR;
+		}
+	}
+	/* NOTREACHED */
+}
+
+/* Serialise compression state into a blob for privsep */
+static int
+ssh_packet_get_compress_state(struct sshbuf *m, struct ssh *ssh)
+{
+	struct session_state *state = ssh->state;
+	struct sshbuf *b;
+	int r;
+
+	if ((b = sshbuf_new()) == NULL)
+		return SSH_ERR_ALLOC_FAIL;
+	if (state->compression_in_started) {
+		if ((r = sshbuf_put_string(b, &state->compression_in_stream,
+		    sizeof(state->compression_in_stream))) != 0)
+			goto out;
+	} else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
+		goto out;
+	if (state->compression_out_started) {
+		if ((r = sshbuf_put_string(b, &state->compression_out_stream,
+		    sizeof(state->compression_out_stream))) != 0)
+			goto out;
+	} else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
+		goto out;
+	r = sshbuf_put_stringb(m, b);
+ out:
+	sshbuf_free(b);
+	return r;
+}
+
+/* Deserialise compression state from a blob for privsep */
+static int
+ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
+{
+	struct session_state *state = ssh->state;
+	struct sshbuf *b = NULL;
+	int r;
+	const u_char *inblob, *outblob;
+	size_t inl, outl;
+
+	if ((r = sshbuf_froms(m, &b)) != 0)
+		goto out;
+	if ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 ||
+	    (r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0)
+		goto out;
+	if (inl == 0)
+		state->compression_in_started = 0;
+	else if (inl != sizeof(state->compression_in_stream)) {
+		r = SSH_ERR_INTERNAL_ERROR;
+		goto out;
+	} else {
+		state->compression_in_started = 1;
+		memcpy(&state->compression_in_stream, inblob, inl);
+	}
+	if (outl == 0)
+		state->compression_out_started = 0;
+	else if (outl != sizeof(state->compression_out_stream)) {
+		r = SSH_ERR_INTERNAL_ERROR;
+		goto out;
+	} else {
+		state->compression_out_started = 1;
+		memcpy(&state->compression_out_stream, outblob, outl);
+	}
+	r = 0;
+ out:
+	sshbuf_free(b);
+	return r;
 }
 
 void
-packet_start_compression(int level)
+ssh_packet_set_compress_hooks(struct ssh *ssh, void *ctx,
+    void *(*allocfunc)(void *, u_int, u_int),
+    void (*freefunc)(void *, void *))
 {
-	if (active_state->packet_compression && !compat20)
-		fatal("Compression already enabled.");
-	active_state->packet_compression = 1;
-	packet_init_compression();
-	buffer_compress_init_send(level);
-	buffer_compress_init_recv();
+	ssh->state->compression_out_stream.zalloc = (alloc_func)allocfunc;
+	ssh->state->compression_out_stream.zfree = (free_func)freefunc;
+	ssh->state->compression_out_stream.opaque = ctx;
+	ssh->state->compression_in_stream.zalloc = (alloc_func)allocfunc;
+	ssh->state->compression_in_stream.zfree = (free_func)freefunc;
+	ssh->state->compression_in_stream.opaque = ctx;
 }
 
 /*
@@ -556,109 +774,34 @@
  * encrypted independently of each other.
  */
 
-void
-packet_set_encryption_key(const u_char *key, u_int keylen, int number)
-{
-	const Cipher *cipher = cipher_by_number(number);
-	int r;
-
-	if (cipher == NULL)
-		fatal("packet_set_encryption_key: unknown cipher number %d", number);
-	if (keylen < 20)
-		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
-	if (keylen > SSH_SESSION_KEY_LENGTH)
-		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
-	memcpy(active_state->ssh1_key, key, keylen);
-	active_state->ssh1_keylen = keylen;
-	if ((r = cipher_init(&active_state->send_context, cipher,
-	    key, keylen, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
-	    (r = cipher_init(&active_state->receive_context, cipher,
-	    key, keylen, NULL, 0, CIPHER_DECRYPT)) != 0)
-		fatal("%s: cipher_init: %s", __func__, ssh_err(r));
-}
-
-u_int
-packet_get_encryption_key(u_char *key)
-{
-	if (key == NULL)
-		return (active_state->ssh1_keylen);
-	memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
-	return (active_state->ssh1_keylen);
-}
-
-/* Start constructing a packet to send. */
-void
-packet_start(u_char type)
-{
-	u_char buf[9];
-	int len;
-
-	DBG(debug("packet_start[%d]", type));
-	len = compat20 ? 6 : 9;
-	memset(buf, 0, len - 1);
-	buf[len - 1] = type;
-	buffer_clear(&active_state->outgoing_packet);
-	buffer_append(&active_state->outgoing_packet, buf, len);
-}
-
-/* Append payload. */
-void
-packet_put_char(int value)
-{
-	char ch = value;
-
-	buffer_append(&active_state->outgoing_packet, &ch, 1);
-}
-
-void
-packet_put_int(u_int value)
-{
-	buffer_put_int(&active_state->outgoing_packet, value);
-}
-
-void
-packet_put_int64(u_int64_t value)
-{
-	buffer_put_int64(&active_state->outgoing_packet, value);
-}
-
-void
-packet_put_string(const void *buf, u_int len)
-{
-	buffer_put_string(&active_state->outgoing_packet, buf, len);
-}
-
-void
-packet_put_cstring(const char *str)
-{
-	buffer_put_cstring(&active_state->outgoing_packet, str);
-}
-
-void
-packet_put_raw(const void *buf, u_int len)
-{
-	buffer_append(&active_state->outgoing_packet, buf, len);
-}
-
 #ifdef WITH_OPENSSL
 void
-packet_put_bignum(BIGNUM * value)
+ssh_packet_set_encryption_key(struct ssh *ssh, const u_char *key, u_int keylen, int number)
 {
-	buffer_put_bignum(&active_state->outgoing_packet, value);
-}
+	struct session_state *state = ssh->state;
+	const struct sshcipher *cipher = cipher_by_number(number);
+	int r;
+	const char *wmsg;
 
-void
-packet_put_bignum2(BIGNUM * value)
-{
-	buffer_put_bignum2(&active_state->outgoing_packet, value);
-}
-#endif
-
-#ifdef OPENSSL_HAS_ECC
-void
-packet_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
-{
-	buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
+	if (cipher == NULL)
+		fatal("%s: unknown cipher number %d", __func__, number);
+	if (keylen < 20)
+		fatal("%s: keylen too small: %d", __func__, keylen);
+	if (keylen > SSH_SESSION_KEY_LENGTH)
+		fatal("%s: keylen too big: %d", __func__, keylen);
+	memcpy(state->ssh1_key, key, keylen);
+	state->ssh1_keylen = keylen;
+	if ((r = cipher_init(&state->send_context, cipher, key, keylen,
+	    NULL, 0, CIPHER_ENCRYPT)) != 0 ||
+	    (r = cipher_init(&state->receive_context, cipher, key, keylen,
+	    NULL, 0, CIPHER_DECRYPT) != 0))
+		fatal("%s: cipher_init failed: %s", __func__, ssh_err(r));
+	if (!state->cipher_warning_done &&
+	    ((wmsg = cipher_warning_message(&state->send_context)) != NULL ||
+	    (wmsg = cipher_warning_message(&state->send_context)) != NULL)) {
+		error("Warning: %s", wmsg);
+		state->cipher_warning_done = 1;
+	}
 }
 #endif
 
@@ -667,114 +810,126 @@
  * encrypts the packet before sending.
  */
 
-static void
-packet_send1(void)
+int
+ssh_packet_send1(struct ssh *ssh)
 {
+	struct session_state *state = ssh->state;
 	u_char buf[8], *cp;
-	int i, padding, len;
+	int r, padding, len;
 	u_int checksum;
-	u_int32_t rnd = 0;
 
 	/*
 	 * If using packet compression, compress the payload of the outgoing
 	 * packet.
 	 */
-	if (active_state->packet_compression) {
-		buffer_clear(&active_state->compression_buffer);
+	if (state->packet_compression) {
+		sshbuf_reset(state->compression_buffer);
 		/* Skip padding. */
-		buffer_consume(&active_state->outgoing_packet, 8);
+		if ((r = sshbuf_consume(state->outgoing_packet, 8)) != 0)
+			goto out;
 		/* padding */
-		buffer_append(&active_state->compression_buffer,
-		    "\0\0\0\0\0\0\0\0", 8);
-		buffer_compress(&active_state->outgoing_packet,
-		    &active_state->compression_buffer);
-		buffer_clear(&active_state->outgoing_packet);
-		buffer_append(&active_state->outgoing_packet,
-		    buffer_ptr(&active_state->compression_buffer),
-		    buffer_len(&active_state->compression_buffer));
+		if ((r = sshbuf_put(state->compression_buffer,
+		    "\0\0\0\0\0\0\0\0", 8)) != 0)
+			goto out;
+		if ((r = compress_buffer(ssh, state->outgoing_packet,
+		    state->compression_buffer)) != 0)
+			goto out;
+		sshbuf_reset(state->outgoing_packet);
+                if ((r = sshbuf_putb(state->outgoing_packet,
+                    state->compression_buffer)) != 0)
+			goto out;
 	}
 	/* Compute packet length without padding (add checksum, remove padding). */
-	len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
+	len = sshbuf_len(state->outgoing_packet) + 4 - 8;
 
 	/* Insert padding. Initialized to zero in packet_start1() */
 	padding = 8 - len % 8;
-	if (!active_state->send_context.plaintext) {
-		cp = buffer_ptr(&active_state->outgoing_packet);
-		for (i = 0; i < padding; i++) {
-			if (i % 4 == 0)
-				rnd = arc4random();
-			cp[7 - i] = rnd & 0xff;
-			rnd >>= 8;
+	if (!state->send_context.plaintext) {
+		cp = sshbuf_mutable_ptr(state->outgoing_packet);
+		if (cp == NULL) {
+			r = SSH_ERR_INTERNAL_ERROR;
+			goto out;
 		}
+		arc4random_buf(cp + 8 - padding, padding);
 	}
-	buffer_consume(&active_state->outgoing_packet, 8 - padding);
+	if ((r = sshbuf_consume(state->outgoing_packet, 8 - padding)) != 0)
+		goto out;
 
 	/* Add check bytes. */
-	checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
-	    buffer_len(&active_state->outgoing_packet));
-	put_u32(buf, checksum);
-	buffer_append(&active_state->outgoing_packet, buf, 4);
+	checksum = ssh_crc32(sshbuf_ptr(state->outgoing_packet),
+	    sshbuf_len(state->outgoing_packet));
+	POKE_U32(buf, checksum);
+	if ((r = sshbuf_put(state->outgoing_packet, buf, 4)) != 0)
+		goto out;
 
 #ifdef PACKET_DEBUG
 	fprintf(stderr, "packet_send plain: ");
-	buffer_dump(&active_state->outgoing_packet);
+	sshbuf_dump(state->outgoing_packet, stderr);
 #endif
 
 	/* Append to output. */
-	put_u32(buf, len);
-	buffer_append(&active_state->output, buf, 4);
-	cp = buffer_append_space(&active_state->output,
-	    buffer_len(&active_state->outgoing_packet));
-	if (cipher_crypt(&active_state->send_context, 0, cp,
-	    buffer_ptr(&active_state->outgoing_packet),
-	    buffer_len(&active_state->outgoing_packet), 0, 0) != 0)
-		fatal("%s: cipher_crypt failed", __func__);
+	POKE_U32(buf, len);
+	if ((r = sshbuf_put(state->output, buf, 4)) != 0)
+		goto out;
+	if ((r = sshbuf_reserve(state->output,
+	    sshbuf_len(state->outgoing_packet), &cp)) != 0)
+		goto out;
+	if ((r = cipher_crypt(&state->send_context, 0, cp,
+	    sshbuf_ptr(state->outgoing_packet),
+	    sshbuf_len(state->outgoing_packet), 0, 0)) != 0)
+		goto out;
 
 #ifdef PACKET_DEBUG
 	fprintf(stderr, "encrypted: ");
-	buffer_dump(&active_state->output);
+	sshbuf_dump(state->output, stderr);
 #endif
-	active_state->p_send.packets++;
-	active_state->p_send.bytes += len +
-	    buffer_len(&active_state->outgoing_packet);
-	buffer_clear(&active_state->outgoing_packet);
+	state->p_send.packets++;
+	state->p_send.bytes += len +
+	    sshbuf_len(state->outgoing_packet);
+	sshbuf_reset(state->outgoing_packet);
 
 	/*
 	 * Note that the packet is now only buffered in output.  It won't be
 	 * actually sent until packet_write_wait or packet_write_poll is
 	 * called.
 	 */
+	r = 0;
+ out:
+	return r;
 }
 
-void
-set_newkeys(int mode)
+int
+ssh_set_newkeys(struct ssh *ssh, int mode)
 {
-	Enc *enc;
-	Mac *mac;
-	Comp *comp;
-	CipherContext *cc;
+	struct session_state *state = ssh->state;
+	struct sshenc *enc;
+	struct sshmac *mac;
+	struct sshcomp *comp;
+	struct sshcipher_ctx *cc;
 	u_int64_t *max_blocks;
+	const char *wmsg;
 	int r, crypt_type;
 
 	debug2("set_newkeys: mode %d", mode);
 
 	if (mode == MODE_OUT) {
-		cc = &active_state->send_context;
+		cc = &state->send_context;
 		crypt_type = CIPHER_ENCRYPT;
-		active_state->p_send.packets = active_state->p_send.blocks = 0;
-		max_blocks = &active_state->max_blocks_out;
+		state->p_send.packets = state->p_send.blocks = 0;
+		max_blocks = &state->max_blocks_out;
 	} else {
-		cc = &active_state->receive_context;
+		cc = &state->receive_context;
 		crypt_type = CIPHER_DECRYPT;
-		active_state->p_read.packets = active_state->p_read.blocks = 0;
-		max_blocks = &active_state->max_blocks_in;
+		state->p_read.packets = state->p_read.blocks = 0;
+		max_blocks = &state->max_blocks_in;
 	}
-	if (active_state->newkeys[mode] != NULL) {
+	if (state->newkeys[mode] != NULL) {
 		debug("set_newkeys: rekeying");
-		cipher_cleanup(cc);
-		enc  = &active_state->newkeys[mode]->enc;
-		mac  = &active_state->newkeys[mode]->mac;
-		comp = &active_state->newkeys[mode]->comp;
+		if ((r = cipher_cleanup(cc)) != 0)
+			return r;
+		enc  = &state->newkeys[mode]->enc;
+		mac  = &state->newkeys[mode]->mac;
+		comp = &state->newkeys[mode]->comp;
 		mac_clear(mac);
 		explicit_bzero(enc->iv,  enc->iv_len);
 		explicit_bzero(enc->key, enc->key_len);
@@ -785,32 +940,45 @@
 		free(mac->name);
 		free(mac->key);
 		free(comp->name);
-		free(active_state->newkeys[mode]);
+		free(state->newkeys[mode]);
 	}
-	active_state->newkeys[mode] = kex_get_newkeys(mode);
-	if (active_state->newkeys[mode] == NULL)
-		fatal("newkeys: no keys for mode %d", mode);
-	enc  = &active_state->newkeys[mode]->enc;
-	mac  = &active_state->newkeys[mode]->mac;
-	comp = &active_state->newkeys[mode]->comp;
-	if (cipher_authlen(enc->cipher) == 0 && mac_init(mac) == 0)
-		mac->enabled = 1;
+	/* move newkeys from kex to state */
+	if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
+		return SSH_ERR_INTERNAL_ERROR;
+	ssh->kex->newkeys[mode] = NULL;
+	enc  = &state->newkeys[mode]->enc;
+	mac  = &state->newkeys[mode]->mac;
+	comp = &state->newkeys[mode]->comp;
+	if (cipher_authlen(enc->cipher) == 0) {
+		if ((r = mac_init(mac)) != 0)
+			return r;
+	}
+	mac->enabled = 1;
 	DBG(debug("cipher_init_context: %d", mode));
 	if ((r = cipher_init(cc, enc->cipher, enc->key, enc->key_len,
 	    enc->iv, enc->iv_len, crypt_type)) != 0)
-		fatal("%s: cipher_init: %s", __func__, ssh_err(r));
+		return r;
+	if (!state->cipher_warning_done &&
+	    (wmsg = cipher_warning_message(cc)) != NULL) {
+		error("Warning: %s", wmsg);
+		state->cipher_warning_done = 1;
+	}
 	/* Deleting the keys does not gain extra security */
 	/* explicit_bzero(enc->iv,  enc->block_size);
 	   explicit_bzero(enc->key, enc->key_len);
 	   explicit_bzero(mac->key, mac->key_len); */
 	if ((comp->type == COMP_ZLIB ||
 	    (comp->type == COMP_DELAYED &&
-	     active_state->after_authentication)) && comp->enabled == 0) {
-		packet_init_compression();
-		if (mode == MODE_OUT)
-			buffer_compress_init_send(6);
-		else
-			buffer_compress_init_recv();
+	     state->after_authentication)) && comp->enabled == 0) {
+		if ((r = ssh_packet_init_compression(ssh)) < 0)
+			return r;
+		if (mode == MODE_OUT) {
+			if ((r = start_compression_out(ssh, 6)) != 0)
+				return r;
+		} else {
+			if ((r = start_compression_in(ssh)) != 0)
+				return r;
+		}
 		comp->enabled = 1;
 	}
 	/*
@@ -821,9 +989,10 @@
 		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
 	else
 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
-	if (active_state->rekey_limit)
+	if (state->rekey_limit)
 		*max_blocks = MIN(*max_blocks,
-		    active_state->rekey_limit / enc->block_size);
+		    state->rekey_limit / enc->block_size);
+	return 0;
 }
 
 /*
@@ -831,53 +1000,59 @@
  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
  */
-static void
-packet_enable_delayed_compress(void)
+static int
+ssh_packet_enable_delayed_compress(struct ssh *ssh)
 {
-	Comp *comp = NULL;
-	int mode;
+	struct session_state *state = ssh->state;
+	struct sshcomp *comp = NULL;
+	int r, mode;
 
 	/*
 	 * Remember that we are past the authentication step, so rekeying
 	 * with COMP_DELAYED will turn on compression immediately.
 	 */
-	active_state->after_authentication = 1;
+	state->after_authentication = 1;
 	for (mode = 0; mode < MODE_MAX; mode++) {
 		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
-		if (active_state->newkeys[mode] == NULL)
+		if (state->newkeys[mode] == NULL)
 			continue;
-		comp = &active_state->newkeys[mode]->comp;
+		comp = &state->newkeys[mode]->comp;
 		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
-			packet_init_compression();
-			if (mode == MODE_OUT)
-				buffer_compress_init_send(6);
-			else
-				buffer_compress_init_recv();
+			if ((r = ssh_packet_init_compression(ssh)) != 0)
+				return r;
+			if (mode == MODE_OUT) {
+				if ((r = start_compression_out(ssh, 6)) != 0)
+					return r;
+			} else {
+				if ((r = start_compression_in(ssh)) != 0)
+					return r;
+			}
 			comp->enabled = 1;
 		}
 	}
+	return 0;
 }
 
 /*
  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
  */
-static void
-packet_send2_wrapped(void)
+int
+ssh_packet_send2_wrapped(struct ssh *ssh)
 {
+	struct session_state *state = ssh->state;
 	u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
 	u_char padlen, pad = 0;
-	u_int i, len, authlen = 0, aadlen = 0;
-	u_int32_t rnd = 0;
-	Enc *enc   = NULL;
-	Mac *mac   = NULL;
-	Comp *comp = NULL;
-	int block_size;
-	int r;
+	u_int authlen = 0, aadlen = 0;
+	u_int len;
+	struct sshenc *enc   = NULL;
+	struct sshmac *mac   = NULL;
+	struct sshcomp *comp = NULL;
+	int r, block_size;
 
-	if (active_state->newkeys[MODE_OUT] != NULL) {
-		enc  = &active_state->newkeys[MODE_OUT]->enc;
-		mac  = &active_state->newkeys[MODE_OUT]->mac;
-		comp = &active_state->newkeys[MODE_OUT]->comp;
+	if (state->newkeys[MODE_OUT] != NULL) {
+		enc  = &state->newkeys[MODE_OUT]->enc;
+		mac  = &state->newkeys[MODE_OUT]->mac;
+		comp = &state->newkeys[MODE_OUT]->comp;
 		/* disable mac for authenticated encryption */
 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
 			mac = NULL;
@@ -885,32 +1060,34 @@
 	block_size = enc ? enc->block_size : 8;
 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
 
-	cp = buffer_ptr(&active_state->outgoing_packet);
-	type = cp[5];
+	type = (sshbuf_ptr(state->outgoing_packet))[5];
 
 #ifdef PACKET_DEBUG
 	fprintf(stderr, "plain:     ");
-	buffer_dump(&active_state->outgoing_packet);
+	sshbuf_dump(state->outgoing_packet, stderr);
 #endif
 
 	if (comp && comp->enabled) {
-		len = buffer_len(&active_state->outgoing_packet);
+		len = sshbuf_len(state->outgoing_packet);
 		/* skip header, compress only payload */
-		buffer_consume(&active_state->outgoing_packet, 5);
-		buffer_clear(&active_state->compression_buffer);
-		buffer_compress(&active_state->outgoing_packet,
-		    &active_state->compression_buffer);
-		buffer_clear(&active_state->outgoing_packet);
-		buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
-		buffer_append(&active_state->outgoing_packet,
-		    buffer_ptr(&active_state->compression_buffer),
-		    buffer_len(&active_state->compression_buffer));
-		DBG(debug("compression: raw %d compressed %d", len,
-		    buffer_len(&active_state->outgoing_packet)));
+		if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
+			goto out;
+		sshbuf_reset(state->compression_buffer);
+		if ((r = compress_buffer(ssh, state->outgoing_packet,
+		    state->compression_buffer)) != 0)
+			goto out;
+		sshbuf_reset(state->outgoing_packet);
+		if ((r = sshbuf_put(state->outgoing_packet,
+		    "\0\0\0\0\0", 5)) != 0 ||
+		    (r = sshbuf_putb(state->outgoing_packet,
+		    state->compression_buffer)) != 0)
+			goto out;
+		DBG(debug("compression: raw %d compressed %zd", len,
+		    sshbuf_len(state->outgoing_packet)));
 	}
 
 	/* sizeof (packet_len + pad_len + payload) */
-	len = buffer_len(&active_state->outgoing_packet);
+	len = sshbuf_len(state->outgoing_packet);
 
 	/*
 	 * calc size of padding, alloc space, get random data,
@@ -920,143 +1097,145 @@
 	padlen = block_size - (len % block_size);
 	if (padlen < 4)
 		padlen += block_size;
-	if (active_state->extra_pad) {
+	if (state->extra_pad) {
 		/* will wrap if extra_pad+padlen > 255 */
-		active_state->extra_pad =
-		    roundup(active_state->extra_pad, block_size);
-		pad = active_state->extra_pad -
-		    ((len + padlen) % active_state->extra_pad);
+		state->extra_pad =
+		    roundup(state->extra_pad, block_size);
+		pad = state->extra_pad -
+		    ((len + padlen) % state->extra_pad);
 		DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
-		    __func__, pad, len, padlen, active_state->extra_pad));
+		    __func__, pad, len, padlen, state->extra_pad));
 		padlen += pad;
-		active_state->extra_pad = 0;
+		state->extra_pad = 0;
 	}
-	cp = buffer_append_space(&active_state->outgoing_packet, padlen);
-	if (enc && !active_state->send_context.plaintext) {
+	if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
+		goto out;
+	if (enc && !state->send_context.plaintext) {
 		/* random padding */
-		for (i = 0; i < padlen; i++) {
-			if (i % 4 == 0)
-				rnd = arc4random();
-			cp[i] = rnd & 0xff;
-			rnd >>= 8;
-		}
+		arc4random_buf(cp, padlen);
 	} else {
 		/* clear padding */
 		explicit_bzero(cp, padlen);
 	}
 	/* sizeof (packet_len + pad_len + payload + padding) */
-	len = buffer_len(&active_state->outgoing_packet);
-	cp = buffer_ptr(&active_state->outgoing_packet);
+	len = sshbuf_len(state->outgoing_packet);
+	cp = sshbuf_mutable_ptr(state->outgoing_packet);
+	if (cp == NULL) {
+		r = SSH_ERR_INTERNAL_ERROR;
+		goto out;
+	}
 	/* packet_length includes payload, padding and padding length field */
-	put_u32(cp, len - 4);
+	POKE_U32(cp, len - 4);
 	cp[4] = padlen;
 	DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
 	    len, padlen, aadlen));
 
 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
 	if (mac && mac->enabled && !mac->etm) {
-		if ((r = mac_compute(mac, active_state->p_send.seqnr,
-		    buffer_ptr(&active_state->outgoing_packet), len,
+		if ((r = mac_compute(mac, state->p_send.seqnr,
+		    sshbuf_ptr(state->outgoing_packet), len,
 		    macbuf, sizeof(macbuf))) != 0)
-			fatal("%s: mac_compute: %s", __func__, ssh_err(r));
-		DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
+			goto out;
+		DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
 	}
 	/* encrypt packet and append to output buffer. */
-	cp = buffer_append_space(&active_state->output, len + authlen);
-	if (cipher_crypt(&active_state->send_context, active_state->p_send.seqnr,
-	    cp, buffer_ptr(&active_state->outgoing_packet),
-	    len - aadlen, aadlen, authlen) != 0)
-		fatal("%s: cipher_crypt failed", __func__);
+	if ((r = sshbuf_reserve(state->output,
+	    sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
+		goto out;
+	if ((r = cipher_crypt(&state->send_context, state->p_send.seqnr, cp,
+	    sshbuf_ptr(state->outgoing_packet),
+	    len - aadlen, aadlen, authlen)) != 0)
+		goto out;
 	/* append unencrypted MAC */
 	if (mac && mac->enabled) {
 		if (mac->etm) {
 			/* EtM: compute mac over aadlen + cipher text */
-			if ((r = mac_compute(mac,
-			    active_state->p_send.seqnr, cp, len,
-			    macbuf, sizeof(macbuf))) != 0)
-				fatal("%s: mac_compute: %s", __func__, ssh_err(r));
+			if ((r = mac_compute(mac, state->p_send.seqnr,
+			    cp, len, macbuf, sizeof(macbuf))) != 0)
+				goto out;
 			DBG(debug("done calc MAC(EtM) out #%d",
-			    active_state->p_send.seqnr));
+			    state->p_send.seqnr));
 		}
-		buffer_append(&active_state->output, macbuf, mac->mac_len);
+		if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
+			goto out;
 	}
 #ifdef PACKET_DEBUG
 	fprintf(stderr, "encrypted: ");
-	buffer_dump(&active_state->output);
+	sshbuf_dump(state->output, stderr);
 #endif
 	/* increment sequence number for outgoing packets */
-	if (++active_state->p_send.seqnr == 0)
+	if (++state->p_send.seqnr == 0)
 		logit("outgoing seqnr wraps around");
-	if (++active_state->p_send.packets == 0)
-		if (!(datafellows & SSH_BUG_NOREKEY))
-			fatal("XXX too many packets with same key");
-	active_state->p_send.blocks += len / block_size;
-	active_state->p_send.bytes += len;
-	buffer_clear(&active_state->outgoing_packet);
+	if (++state->p_send.packets == 0)
+		if (!(ssh->compat & SSH_BUG_NOREKEY))
+			return SSH_ERR_NEED_REKEY;
+	state->p_send.blocks += len / block_size;
+	state->p_send.bytes += len;
+	sshbuf_reset(state->outgoing_packet);
 
 	if (type == SSH2_MSG_NEWKEYS)
-		set_newkeys(MODE_OUT);
-	else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
-		packet_enable_delayed_compress();
+		r = ssh_set_newkeys(ssh, MODE_OUT);
+	else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
+		r = ssh_packet_enable_delayed_compress(ssh);
+	else
+		r = 0;
+ out:
+	return r;
 }
 
-static void
-packet_send2(void)
+int
+ssh_packet_send2(struct ssh *ssh)
 {
+	struct session_state *state = ssh->state;
 	struct packet *p;
-	u_char type, *cp;
+	u_char type;
+	int r;
 
-	cp = buffer_ptr(&active_state->outgoing_packet);
-	type = cp[5];
+	type = sshbuf_ptr(state->outgoing_packet)[5];
 
 	/* during rekeying we can only send key exchange messages */
-	if (active_state->rekeying) {
+	if (state->rekeying) {
 		if ((type < SSH2_MSG_TRANSPORT_MIN) ||
 		    (type > SSH2_MSG_TRANSPORT_MAX) ||
 		    (type == SSH2_MSG_SERVICE_REQUEST) ||
 		    (type == SSH2_MSG_SERVICE_ACCEPT)) {
 			debug("enqueue packet: %u", type);
-			p = xcalloc(1, sizeof(*p));
+			p = calloc(1, sizeof(*p));
+			if (p == NULL)
+				return SSH_ERR_ALLOC_FAIL;
 			p->type = type;
-			memcpy(&p->payload, &active_state->outgoing_packet,
-			    sizeof(Buffer));
-			buffer_init(&active_state->outgoing_packet);
-			TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
-			return;
+			p->payload = state->outgoing_packet;
+			TAILQ_INSERT_TAIL(&state->outgoing, p, next);
+			state->outgoing_packet = sshbuf_new();
+			if (state->outgoing_packet == NULL)
+				return SSH_ERR_ALLOC_FAIL;
+			return 0;
 		}
 	}
 
 	/* rekeying starts with sending KEXINIT */
 	if (type == SSH2_MSG_KEXINIT)
-		active_state->rekeying = 1;
+		state->rekeying = 1;
 
-	packet_send2_wrapped();
+	if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
+		return r;
 
 	/* after a NEWKEYS message we can send the complete queue */
 	if (type == SSH2_MSG_NEWKEYS) {
-		active_state->rekeying = 0;
-		active_state->rekey_time = monotime();
-		while ((p = TAILQ_FIRST(&active_state->outgoing))) {
+		state->rekeying = 0;
+		state->rekey_time = monotime();
+		while ((p = TAILQ_FIRST(&state->outgoing))) {
 			type = p->type;
 			debug("dequeue packet: %u", type);
-			buffer_free(&active_state->outgoing_packet);
-			memcpy(&active_state->outgoing_packet, &p->payload,
-			    sizeof(Buffer));
-			TAILQ_REMOVE(&active_state->outgoing, p, next);
+			sshbuf_free(state->outgoing_packet);
+			state->outgoing_packet = p->payload;
+			TAILQ_REMOVE(&state->outgoing, p, next);
 			free(p);
-			packet_send2_wrapped();
+			if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
+				return r;
 		}
 	}
-}
-
-void
-packet_send(void)
-{
-	if (compat20)
-		packet_send2();
-	else
-		packet_send1();
-	DBG(debug("packet_send done"));
+	return 0;
 }
 
 /*
@@ -1066,95 +1245,106 @@
  */
 
 int
-packet_read_seqnr(u_int32_t *seqnr_p)
+ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
 {
-	int type, len, ret, cont, ms_remain = 0;
+	struct session_state *state = ssh->state;
+	int len, r, ms_remain, cont;
 	fd_set *setp;
 	char buf[8192];
 	struct timeval timeout, start, *timeoutp = NULL;
 
 	DBG(debug("packet_read()"));
 
-	setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
+	setp = (fd_set *)calloc(howmany(state->connection_in + 1,
 	    NFDBITS), sizeof(fd_mask));
+	if (setp == NULL)
+		return SSH_ERR_ALLOC_FAIL;
 
 	/* Since we are blocking, ensure that all written packets have been sent. */
-	packet_write_wait();
+	ssh_packet_write_wait(ssh);
 
 	/* Stay in the loop until we have received a complete packet. */
 	for (;;) {
 		/* Try to read a packet from the buffer. */
-		type = packet_read_poll_seqnr(seqnr_p);
+		r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
+		if (r != 0)
+			break;
 		if (!compat20 && (
-		    type == SSH_SMSG_SUCCESS
-		    || type == SSH_SMSG_FAILURE
-		    || type == SSH_CMSG_EOF
-		    || type == SSH_CMSG_EXIT_CONFIRMATION))
-			packet_check_eom();
+		    *typep == SSH_SMSG_SUCCESS
+		    || *typep == SSH_SMSG_FAILURE
+		    || *typep == SSH_CMSG_EOF
+		    || *typep == SSH_CMSG_EXIT_CONFIRMATION))
+			if ((r = sshpkt_get_end(ssh)) != 0)
+				break;
 		/* If we got a packet, return it. */
-		if (type != SSH_MSG_NONE) {
-			free(setp);
-			return type;
-		}
+		if (*typep != SSH_MSG_NONE)
+			break;
 		/*
 		 * Otherwise, wait for some data to arrive, add it to the
 		 * buffer, and try again.
 		 */
-		memset(setp, 0, howmany(active_state->connection_in + 1,
+		memset(setp, 0, howmany(state->connection_in + 1,
 		    NFDBITS) * sizeof(fd_mask));
-		FD_SET(active_state->connection_in, setp);
+		FD_SET(state->connection_in, setp);
 
-		if (active_state->packet_timeout_ms > 0) {
-			ms_remain = active_state->packet_timeout_ms;
+		if (state->packet_timeout_ms > 0) {
+			ms_remain = state->packet_timeout_ms;
 			timeoutp = &timeout;
 		}
 		/* Wait for some data to arrive. */
 		for (;;) {
-			if (active_state->packet_timeout_ms != -1) {
+			if (state->packet_timeout_ms != -1) {
 				ms_to_timeval(&timeout, ms_remain);
 				gettimeofday(&start, NULL);
 			}
-			if ((ret = select(active_state->connection_in + 1, setp,
+			if ((r = select(state->connection_in + 1, setp,
 			    NULL, NULL, timeoutp)) >= 0)
 				break;
 			if (errno != EAGAIN && errno != EINTR &&
 			    errno != EWOULDBLOCK)
 				break;
-			if (active_state->packet_timeout_ms == -1)
+			if (state->packet_timeout_ms == -1)
 				continue;
 			ms_subtract_diff(&start, &ms_remain);
 			if (ms_remain <= 0) {
-				ret = 0;
+				r = 0;
 				break;
 			}
 		}
-		if (ret == 0) {
+		if (r == 0) {
 			logit("Connection to %.200s timed out while "
-			    "waiting to read", get_remote_ipaddr());
+			    "waiting to read", ssh_remote_ipaddr(ssh));
 			cleanup_exit(255);
 		}
 		/* Read data from the socket. */
 		do {
 			cont = 0;
-			len = roaming_read(active_state->connection_in, buf,
+			len = roaming_read(state->connection_in, buf,
 			    sizeof(buf), &cont);
 		} while (len == 0 && cont);
 		if (len == 0) {
-			logit("Connection closed by %.200s", get_remote_ipaddr());
+			logit("Connection closed by %.200s",
+			    ssh_remote_ipaddr(ssh));
 			cleanup_exit(255);
 		}
 		if (len < 0)
 			fatal("Read from socket failed: %.100s", strerror(errno));
 		/* Append it to the buffer. */
-		packet_process_incoming(buf, len);
+		ssh_packet_process_incoming(ssh, buf, len);
 	}
-	/* NOTREACHED */
+	free(setp);
+	return r;
 }
 
 int
-packet_read(void)
+ssh_packet_read(struct ssh *ssh)
 {
-	return packet_read_seqnr(NULL);
+	u_char type;
+	int r;
+
+	if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
+	return type;
 }
 
 /*
@@ -1163,13 +1353,14 @@
  */
 
 void
-packet_read_expect(int expected_type)
+ssh_packet_read_expect(struct ssh *ssh, int expected_type)
 {
 	int type;
 
-	type = packet_read();
+	type = ssh_packet_read(ssh);
 	if (type != expected_type)
-		packet_disconnect("Protocol error: expected packet type %d, got %d",
+		ssh_packet_disconnect(ssh,
+		    "Protocol error: expected packet type %d, got %d",
 		    expected_type, type);
 }
 
@@ -1182,116 +1373,141 @@
  * to higher levels.
  */
 
-static int
-packet_read_poll1(void)
+int
+ssh_packet_read_poll1(struct ssh *ssh, u_char *typep)
 {
+	struct session_state *state = ssh->state;
 	u_int len, padded_len;
-	u_char *cp, type;
+	const u_char *cp;
+	u_char *p;
 	u_int checksum, stored_checksum;
+	int r;
+
+	*typep = SSH_MSG_NONE;
 
 	/* Check if input size is less than minimum packet size. */
-	if (buffer_len(&active_state->input) < 4 + 8)
-		return SSH_MSG_NONE;
+	if (sshbuf_len(state->input) < 4 + 8)
+		return 0;
 	/* Get length of incoming packet. */
-	cp = buffer_ptr(&active_state->input);
-	len = get_u32(cp);
+	len = PEEK_U32(sshbuf_ptr(state->input));
 	if (len < 1 + 2 + 2 || len > 256 * 1024)
-		packet_disconnect("Bad packet length %u.", len);
+		ssh_packet_disconnect(ssh, "Bad packet length %u.",
+		    len);
 	padded_len = (len + 8) & ~7;
 
 	/* Check if the packet has been entirely received. */
-	if (buffer_len(&active_state->input) < 4 + padded_len)
-		return SSH_MSG_NONE;
+	if (sshbuf_len(state->input) < 4 + padded_len)
+		return 0;
 
 	/* The entire packet is in buffer. */
 
 	/* Consume packet length. */
-	buffer_consume(&active_state->input, 4);
+	if ((r = sshbuf_consume(state->input, 4)) != 0)
+		goto out;
 
 	/*
 	 * Cryptographic attack detector for ssh
 	 * (C)1998 CORE-SDI, Buenos Aires Argentina
 	 * Ariel Futoransky(futo@core-sdi.com)
 	 */
-	if (!active_state->receive_context.plaintext) {
-		switch (detect_attack(buffer_ptr(&active_state->input),
-		    padded_len)) {
+	if (!state->receive_context.plaintext) {
+		switch (detect_attack(&state->deattack,
+		    sshbuf_ptr(state->input), padded_len)) {
+		case DEATTACK_OK:
+			break;
 		case DEATTACK_DETECTED:
-			packet_disconnect("crc32 compensation attack: "
-			    "network attack detected");
+			ssh_packet_disconnect(ssh,
+			    "crc32 compensation attack: network attack detected"
+			);
 		case DEATTACK_DOS_DETECTED:
-			packet_disconnect("deattack denial of "
-			    "service detected");
+			ssh_packet_disconnect(ssh,
+			    "deattack denial of service detected");
+		default:
+			ssh_packet_disconnect(ssh, "deattack error");
 		}
 	}
 
 	/* Decrypt data to incoming_packet. */
-	buffer_clear(&active_state->incoming_packet);
-	cp = buffer_append_space(&active_state->incoming_packet, padded_len);
-	if (cipher_crypt(&active_state->receive_context, 0, cp,
-	    buffer_ptr(&active_state->input), padded_len, 0, 0) != 0)
-		fatal("%s: cipher_crypt failed", __func__);
+	sshbuf_reset(state->incoming_packet);
+	if ((r = sshbuf_reserve(state->incoming_packet, padded_len, &p)) != 0)
+		goto out;
+	if ((r = cipher_crypt(&state->receive_context, 0, p,
+	    sshbuf_ptr(state->input), padded_len, 0, 0)) != 0)
+		goto out;
 
-	buffer_consume(&active_state->input, padded_len);
+	if ((r = sshbuf_consume(state->input, padded_len)) != 0)
+		goto out;
 
 #ifdef PACKET_DEBUG
 	fprintf(stderr, "read_poll plain: ");
-	buffer_dump(&active_state->incoming_packet);
+	sshbuf_dump(state->incoming_packet, stderr);
 #endif
 
 	/* Compute packet checksum. */
-	checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
-	    buffer_len(&active_state->incoming_packet) - 4);
+	checksum = ssh_crc32(sshbuf_ptr(state->incoming_packet),
+	    sshbuf_len(state->incoming_packet) - 4);
 
 	/* Skip padding. */
-	buffer_consume(&active_state->incoming_packet, 8 - len % 8);
+	if ((r = sshbuf_consume(state->incoming_packet, 8 - len % 8)) != 0)
+		goto out;
 
 	/* Test check bytes. */
-	if (len != buffer_len(&active_state->incoming_packet))
-		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
-		    len, buffer_len(&active_state->incoming_packet));
+	if (len != sshbuf_len(state->incoming_packet))
+		ssh_packet_disconnect(ssh,
+		    "packet_read_poll1: len %d != sshbuf_len %zd.",
+		    len, sshbuf_len(state->incoming_packet));
 
-	cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
-	stored_checksum = get_u32(cp);
+	cp = sshbuf_ptr(state->incoming_packet) + len - 4;
+	stored_checksum = PEEK_U32(cp);
 	if (checksum != stored_checksum)
-		packet_disconnect("Corrupted check bytes on input.");
-	buffer_consume_end(&active_state->incoming_packet, 4);
+		ssh_packet_disconnect(ssh,
+		    "Corrupted check bytes on input.");
+	if ((r = sshbuf_consume_end(state->incoming_packet, 4)) < 0)
+		goto out;
 
-	if (active_state->packet_compression) {
-		buffer_clear(&active_state->compression_buffer);
-		buffer_uncompress(&active_state->incoming_packet,
-		    &active_state->compression_buffer);
-		buffer_clear(&active_state->incoming_packet);
-		buffer_append(&active_state->incoming_packet,
-		    buffer_ptr(&active_state->compression_buffer),
-		    buffer_len(&active_state->compression_buffer));
+	if (state->packet_compression) {
+		sshbuf_reset(state->compression_buffer);
+		if ((r = uncompress_buffer(ssh, state->incoming_packet,
+		    state->compression_buffer)) != 0)
+			goto out;
+		sshbuf_reset(state->incoming_packet);
+		if ((r = sshbuf_putb(state->incoming_packet,
+		    state->compression_buffer)) != 0)
+			goto out;
 	}
-	active_state->p_read.packets++;
-	active_state->p_read.bytes += padded_len + 4;
-	type = buffer_get_char(&active_state->incoming_packet);
-	if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
-		packet_disconnect("Invalid ssh1 packet type: %d", type);
-	return type;
+	state->p_read.packets++;
+	state->p_read.bytes += padded_len + 4;
+	if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
+		goto out;
+	if (*typep < SSH_MSG_MIN || *typep > SSH_MSG_MAX)
+		ssh_packet_disconnect(ssh,
+		    "Invalid ssh1 packet type: %d", *typep);
+	r = 0;
+ out:
+	return r;
 }
 
-static int
-packet_read_poll2(u_int32_t *seqnr_p)
+int
+ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
 {
+	struct session_state *state = ssh->state;
 	u_int padlen, need;
-	u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
-	u_int maclen, authlen = 0, aadlen = 0, block_size;
+	u_char *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
+	u_int maclen, aadlen = 0, authlen = 0, block_size;
+	struct sshenc *enc   = NULL;
+	struct sshmac *mac   = NULL;
+	struct sshcomp *comp = NULL;
 	int r;
-	Enc *enc   = NULL;
-	Mac *mac   = NULL;
-	Comp *comp = NULL;
 
-	if (active_state->packet_discard)
-		return SSH_MSG_NONE;
+	*typep = SSH_MSG_NONE;
 
-	if (active_state->newkeys[MODE_IN] != NULL) {
-		enc  = &active_state->newkeys[MODE_IN]->enc;
-		mac  = &active_state->newkeys[MODE_IN]->mac;
-		comp = &active_state->newkeys[MODE_IN]->comp;
+	if (state->packet_discard)
+		return 0;
+
+	if (state->newkeys[MODE_IN] != NULL) {
+		enc  = &state->newkeys[MODE_IN]->enc;
+		mac  = &state->newkeys[MODE_IN]->mac;
+		comp = &state->newkeys[MODE_IN]->comp;
 		/* disable mac for authenticated encryption */
 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
 			mac = NULL;
@@ -1300,69 +1516,71 @@
 	block_size = enc ? enc->block_size : 8;
 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
 
-	if (aadlen && active_state->packlen == 0) {
-		if (cipher_get_length(&active_state->receive_context,
-		    &active_state->packlen,
-		    active_state->p_read.seqnr,
-		    buffer_ptr(&active_state->input),
-		    buffer_len(&active_state->input)) != 0)
-			return SSH_MSG_NONE;
-		if (active_state->packlen < 1 + 4 ||
-		    active_state->packlen > PACKET_MAX_SIZE) {
+	if (aadlen && state->packlen == 0) {
+		if (cipher_get_length(&state->receive_context,
+		    &state->packlen, state->p_read.seqnr,
+		    sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
+			return 0;
+		if (state->packlen < 1 + 4 ||
+		    state->packlen > PACKET_MAX_SIZE) {
 #ifdef PACKET_DEBUG
-			buffer_dump(&active_state->input);
+			sshbuf_dump(state->input, stderr);
 #endif
-			logit("Bad packet length %u.", active_state->packlen);
-			packet_disconnect("Packet corrupt");
+			logit("Bad packet length %u.", state->packlen);
+			if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
+				return r;
 		}
-		buffer_clear(&active_state->incoming_packet);
-	} else if (active_state->packlen == 0) {
+		sshbuf_reset(state->incoming_packet);
+	} else if (state->packlen == 0) {
 		/*
 		 * check if input size is less than the cipher block size,
 		 * decrypt first block and extract length of incoming packet
 		 */
-		if (buffer_len(&active_state->input) < block_size)
-			return SSH_MSG_NONE;
-		buffer_clear(&active_state->incoming_packet);
-		cp = buffer_append_space(&active_state->incoming_packet,
-		    block_size);
-		if (cipher_crypt(&active_state->receive_context,
-		    active_state->p_read.seqnr, cp,
-		    buffer_ptr(&active_state->input), block_size, 0, 0) != 0)
-			fatal("Decryption integrity check failed");
-		cp = buffer_ptr(&active_state->incoming_packet);
-		active_state->packlen = get_u32(cp);
-		if (active_state->packlen < 1 + 4 ||
-		    active_state->packlen > PACKET_MAX_SIZE) {
+		if (sshbuf_len(state->input) < block_size)
+			return 0;
+		sshbuf_reset(state->incoming_packet);
+		if ((r = sshbuf_reserve(state->incoming_packet, block_size,
+		    &cp)) != 0)
+			goto out;
+		if ((r = cipher_crypt(&state->receive_context,
+		    state->p_send.seqnr, cp, sshbuf_ptr(state->input),
+		    block_size, 0, 0)) != 0)
+			goto out;
+		state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
+		if (state->packlen < 1 + 4 ||
+		    state->packlen > PACKET_MAX_SIZE) {
 #ifdef PACKET_DEBUG
-			buffer_dump(&active_state->incoming_packet);
+			fprintf(stderr, "input: \n");
+			sshbuf_dump(state->input, stderr);
+			fprintf(stderr, "incoming_packet: \n");
+			sshbuf_dump(state->incoming_packet, stderr);
 #endif
-			logit("Bad packet length %u.", active_state->packlen);
-			packet_start_discard(enc, mac, active_state->packlen,
-			    PACKET_MAX_SIZE);
-			return SSH_MSG_NONE;
+			logit("Bad packet length %u.", state->packlen);
+			return ssh_packet_start_discard(ssh, enc, mac,
+			    state->packlen, PACKET_MAX_SIZE);
 		}
-		buffer_consume(&active_state->input, block_size);
+		if ((r = sshbuf_consume(state->input, block_size)) != 0)
+			goto out;
 	}
-	DBG(debug("input: packet len %u", active_state->packlen+4));
+	DBG(debug("input: packet len %u", state->packlen+4));
+
 	if (aadlen) {
 		/* only the payload is encrypted */
-		need = active_state->packlen;
+		need = state->packlen;
 	} else {
 		/*
 		 * the payload size and the payload are encrypted, but we
 		 * have a partial packet of block_size bytes
 		 */
-		need = 4 + active_state->packlen - block_size;
+		need = 4 + state->packlen - block_size;
 	}
 	DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
 	    " aadlen %d", block_size, need, maclen, authlen, aadlen));
 	if (need % block_size != 0) {
 		logit("padding error: need %d block %d mod %d",
 		    need, block_size, need % block_size);
-		packet_start_discard(enc, mac, active_state->packlen,
-		    PACKET_MAX_SIZE - block_size);
-		return SSH_MSG_NONE;
+		return ssh_packet_start_discard(ssh, enc, mac,
+		    state->packlen, PACKET_MAX_SIZE - block_size);
 	}
 	/*
 	 * check if the entire packet has been received and
@@ -1372,171 +1590,190 @@
 	 * 'authlen' bytes of authentication tag or
 	 * 'maclen' bytes of message authentication code.
 	 */
-	if (buffer_len(&active_state->input) < aadlen + need + authlen + maclen)
-		return SSH_MSG_NONE;
+	if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
+		return 0;
 #ifdef PACKET_DEBUG
 	fprintf(stderr, "read_poll enc/full: ");
-	buffer_dump(&active_state->input);
+	sshbuf_dump(state->input, stderr);
 #endif
 	/* EtM: compute mac over encrypted input */
-	if (mac && mac->enabled && mac->etm)
-		if ((r = mac_compute(mac, active_state->p_read.seqnr,
-		    buffer_ptr(&active_state->input), aadlen + need,
+	if (mac && mac->enabled && mac->etm) {
+		if ((r = mac_compute(mac, state->p_read.seqnr,
+		    sshbuf_ptr(state->input), aadlen + need,
 		    macbuf, sizeof(macbuf))) != 0)
-			fatal("%s: mac_compute: %s", __func__, ssh_err(r));
-	cp = buffer_append_space(&active_state->incoming_packet, aadlen + need);
-	if (cipher_crypt(&active_state->receive_context,
-	    active_state->p_read.seqnr, cp,
-	    buffer_ptr(&active_state->input), need, aadlen, authlen) != 0)
-		fatal("Decryption integrity check failed");
-	buffer_consume(&active_state->input, aadlen + need + authlen);
+			goto out;
+	}
+	if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
+	    &cp)) != 0)
+		goto out;
+	if ((r = cipher_crypt(&state->receive_context, state->p_read.seqnr, cp,
+	    sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
+		goto out;
+	if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
+		goto out;
 	/*
 	 * compute MAC over seqnr and packet,
 	 * increment sequence number for incoming packet
 	 */
 	if (mac && mac->enabled) {
 		if (!mac->etm)
-			if ((r = mac_compute(mac, active_state->p_read.seqnr,
-			    buffer_ptr(&active_state->incoming_packet),
-			    buffer_len(&active_state->incoming_packet),
+			if ((r = mac_compute(mac, state->p_read.seqnr,
+			    sshbuf_ptr(state->incoming_packet),
+			    sshbuf_len(state->incoming_packet),
 			    macbuf, sizeof(macbuf))) != 0)
-				fatal("%s: mac_compute: %s", __func__, ssh_err(r));
-		if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
+				goto out;
+		if (timingsafe_bcmp(macbuf, sshbuf_ptr(state->input),
 		    mac->mac_len) != 0) {
 			logit("Corrupted MAC on input.");
 			if (need > PACKET_MAX_SIZE)
-				fatal("internal error need %d", need);
-			packet_start_discard(enc, mac, active_state->packlen,
-			    PACKET_MAX_SIZE - need);
-			return SSH_MSG_NONE;
+				return SSH_ERR_INTERNAL_ERROR;
+			return ssh_packet_start_discard(ssh, enc, mac,
+			    state->packlen, PACKET_MAX_SIZE - need);
 		}
-				
-		DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
-		buffer_consume(&active_state->input, mac->mac_len);
+
+		DBG(debug("MAC #%d ok", state->p_read.seqnr));
+		if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
+			goto out;
 	}
 	/* XXX now it's safe to use fatal/packet_disconnect */
 	if (seqnr_p != NULL)
-		*seqnr_p = active_state->p_read.seqnr;
-	if (++active_state->p_read.seqnr == 0)
+		*seqnr_p = state->p_read.seqnr;
+	if (++state->p_read.seqnr == 0)
 		logit("incoming seqnr wraps around");
-	if (++active_state->p_read.packets == 0)
-		if (!(datafellows & SSH_BUG_NOREKEY))
-			fatal("XXX too many packets with same key");
-	active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
-	active_state->p_read.bytes += active_state->packlen + 4;
+	if (++state->p_read.packets == 0)
+		if (!(ssh->compat & SSH_BUG_NOREKEY))
+			return SSH_ERR_NEED_REKEY;
+	state->p_read.blocks += (state->packlen + 4) / block_size;
+	state->p_read.bytes += state->packlen + 4;
 
 	/* get padlen */
-	cp = buffer_ptr(&active_state->incoming_packet);
-	padlen = cp[4];
+	padlen = sshbuf_ptr(state->incoming_packet)[4];
 	DBG(debug("input: padlen %d", padlen));
 	if (padlen < 4)
-		packet_disconnect("Corrupted padlen %d on input.", padlen);
+		ssh_packet_disconnect(ssh,
+		    "Corrupted padlen %d on input.", padlen);
 
 	/* skip packet size + padlen, discard padding */
-	buffer_consume(&active_state->incoming_packet, 4 + 1);
-	buffer_consume_end(&active_state->incoming_packet, padlen);
+	if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
+	    ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
+		goto out;
 
-	DBG(debug("input: len before de-compress %d",
-	    buffer_len(&active_state->incoming_packet)));
+	DBG(debug("input: len before de-compress %zd",
+	    sshbuf_len(state->incoming_packet)));
 	if (comp && comp->enabled) {
-		buffer_clear(&active_state->compression_buffer);
-		buffer_uncompress(&active_state->incoming_packet,
-		    &active_state->compression_buffer);
-		buffer_clear(&active_state->incoming_packet);
-		buffer_append(&active_state->incoming_packet,
-		    buffer_ptr(&active_state->compression_buffer),
-		    buffer_len(&active_state->compression_buffer));
-		DBG(debug("input: len after de-compress %d",
-		    buffer_len(&active_state->incoming_packet)));
+		sshbuf_reset(state->compression_buffer);
+		if ((r = uncompress_buffer(ssh, state->incoming_packet,
+		    state->compression_buffer)) != 0)
+			goto out;
+		sshbuf_reset(state->incoming_packet);
+		if ((r = sshbuf_putb(state->incoming_packet,
+		    state->compression_buffer)) != 0)
+			goto out;
+		DBG(debug("input: len after de-compress %zd",
+		    sshbuf_len(state->incoming_packet)));
 	}
 	/*
 	 * get packet type, implies consume.
 	 * return length of payload (without type field)
 	 */
-	type = buffer_get_char(&active_state->incoming_packet);
-	if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
-		packet_disconnect("Invalid ssh2 packet type: %d", type);
-	if (type == SSH2_MSG_NEWKEYS)
-		set_newkeys(MODE_IN);
-	else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
-	    !active_state->server_side)
-		packet_enable_delayed_compress();
+	if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
+		goto out;
+	if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN)
+		ssh_packet_disconnect(ssh,
+		    "Invalid ssh2 packet type: %d", *typep);
+	if (*typep == SSH2_MSG_NEWKEYS)
+		r = ssh_set_newkeys(ssh, MODE_IN);
+	else if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
+		r = ssh_packet_enable_delayed_compress(ssh);
+	else
+		r = 0;
 #ifdef PACKET_DEBUG
-	fprintf(stderr, "read/plain[%d]:\r\n", type);
-	buffer_dump(&active_state->incoming_packet);
+	fprintf(stderr, "read/plain[%d]:\r\n", *typep);
+	sshbuf_dump(state->incoming_packet, stderr);
 #endif
 	/* reset for next packet */
-	active_state->packlen = 0;
-	return type;
+	state->packlen = 0;
+ out:
+	return r;
 }
 
 int
-packet_read_poll_seqnr(u_int32_t *seqnr_p)
+ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
 {
+	struct session_state *state = ssh->state;
 	u_int reason, seqnr;
-	u_char type;
-	char *msg;
+	int r;
+	u_char *msg;
 
 	for (;;) {
+		msg = NULL;
 		if (compat20) {
-			type = packet_read_poll2(seqnr_p);
-			if (type) {
-				active_state->keep_alive_timeouts = 0;
-				DBG(debug("received packet type %d", type));
+			r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
+			if (r != 0)
+				return r;
+			if (*typep) {
+				state->keep_alive_timeouts = 0;
+				DBG(debug("received packet type %d", *typep));
 			}
-			switch (type) {
+			switch (*typep) {
 			case SSH2_MSG_IGNORE:
 				debug3("Received SSH2_MSG_IGNORE");
 				break;
 			case SSH2_MSG_DEBUG:
-				packet_get_char();
-				msg = packet_get_string(NULL);
+				if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
+				    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
+				    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
+					if (msg)
+						free(msg);
+					return r;
+				}
 				debug("Remote: %.900s", msg);
 				free(msg);
-				msg = packet_get_string(NULL);
-				free(msg);
 				break;
 			case SSH2_MSG_DISCONNECT:
-				reason = packet_get_int();
-				msg = packet_get_string(NULL);
+				if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
+				    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
+					return r;
 				/* Ignore normal client exit notifications */
-				do_log2(active_state->server_side &&
+				do_log2(ssh->state->server_side &&
 				    reason == SSH2_DISCONNECT_BY_APPLICATION ?
 				    SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
 				    "Received disconnect from %s: %u: %.400s",
-				    get_remote_ipaddr(), reason, msg);
+				    ssh_remote_ipaddr(ssh), reason, msg);
 				free(msg);
-				cleanup_exit(255);
-				break;
+				return SSH_ERR_DISCONNECTED;
 			case SSH2_MSG_UNIMPLEMENTED:
-				seqnr = packet_get_int();
+				if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
+					return r;
 				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
 				    seqnr);
 				break;
 			default:
-				return type;
+				return 0;
 			}
 		} else {
-			type = packet_read_poll1();
-			switch (type) {
+			r = ssh_packet_read_poll1(ssh, typep);
+			switch (*typep) {
 			case SSH_MSG_NONE:
 				return SSH_MSG_NONE;
 			case SSH_MSG_IGNORE:
 				break;
 			case SSH_MSG_DEBUG:
-				msg = packet_get_string(NULL);
+				if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
+					return r;
 				debug("Remote: %.900s", msg);
 				free(msg);
 				break;
 			case SSH_MSG_DISCONNECT:
-				msg = packet_get_string(NULL);
+				if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
+					return r;
 				error("Received disconnect from %s: %.400s",
-				    get_remote_ipaddr(), msg);
-				cleanup_exit(255);
-				break;
+				    ssh_remote_ipaddr(ssh), msg);
+				free(msg);
+				return SSH_ERR_DISCONNECTED;
 			default:
-				DBG(debug("received packet type %d", type));
-				return type;
+				DBG(debug("received packet type %d", *typep));
+				return 0;
 			}
 		}
 	}
@@ -1548,112 +1785,29 @@
  */
 
 void
-packet_process_incoming(const char *buf, u_int len)
+ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
 {
-	if (active_state->packet_discard) {
-		active_state->keep_alive_timeouts = 0; /* ?? */
-		if (len >= active_state->packet_discard)
-			packet_stop_discard();
-		active_state->packet_discard -= len;
+	struct session_state *state = ssh->state;
+	int r;
+
+	if (state->packet_discard) {
+		state->keep_alive_timeouts = 0; /* ?? */
+		if (len >= state->packet_discard) {
+			if ((r = ssh_packet_stop_discard(ssh)) != 0)
+				fatal("%s: %s", __func__, ssh_err(r));
+			cleanup_exit(255);
+		}
+		state->packet_discard -= len;
 		return;
 	}
-	buffer_append(&active_state->input, buf, len);
-}
-
-/* Returns a character from the packet. */
-
-u_int
-packet_get_char(void)
-{
-	char ch;
-
-	buffer_get(&active_state->incoming_packet, &ch, 1);
-	return (u_char) ch;
-}
-
-/* Returns an integer from the packet data. */
-
-u_int
-packet_get_int(void)
-{
-	return buffer_get_int(&active_state->incoming_packet);
-}
-
-/* Returns an 64 bit integer from the packet data. */
-
-u_int64_t
-packet_get_int64(void)
-{
-	return buffer_get_int64(&active_state->incoming_packet);
-}
-
-/*
- * Returns an arbitrary precision integer from the packet data.  The integer
- * must have been initialized before this call.
- */
-
-#ifdef WITH_OPENSSL
-void
-packet_get_bignum(BIGNUM * value)
-{
-	buffer_get_bignum(&active_state->incoming_packet, value);
-}
-
-void
-packet_get_bignum2(BIGNUM * value)
-{
-	buffer_get_bignum2(&active_state->incoming_packet, value);
-}
-
-#ifdef OPENSSL_HAS_ECC
-void
-packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
-{
-	buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
-}
-#endif
-#endif
-
-void *
-packet_get_raw(u_int *length_ptr)
-{
-	u_int bytes = buffer_len(&active_state->incoming_packet);
-
-	if (length_ptr != NULL)
-		*length_ptr = bytes;
-	return buffer_ptr(&active_state->incoming_packet);
+	if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
 }
 
 int
-packet_remaining(void)
+ssh_packet_remaining(struct ssh *ssh)
 {
-	return buffer_len(&active_state->incoming_packet);
-}
-
-/*
- * Returns a string from the packet data.  The string is allocated using
- * xmalloc; it is the responsibility of the calling program to free it when
- * no longer needed.  The length_ptr argument may be NULL, or point to an
- * integer into which the length of the string is stored.
- */
-
-void *
-packet_get_string(u_int *length_ptr)
-{
-	return buffer_get_string(&active_state->incoming_packet, length_ptr);
-}
-
-const void *
-packet_get_string_ptr(u_int *length_ptr)
-{
-	return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
-}
-
-/* Ensures the returned string has no embedded \0 characters in it. */
-char *
-packet_get_cstring(u_int *length_ptr)
-{
-	return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
+	return sshbuf_len(ssh->state->incoming_packet);
 }
 
 /*
@@ -1666,12 +1820,13 @@
  */
 
 void
-packet_send_debug(const char *fmt,...)
+ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
 {
 	char buf[1024];
 	va_list args;
+	int r;
 
-	if (compat20 && (datafellows & SSH_BUG_DEBUG))
+	if (compat20 && (ssh->compat & SSH_BUG_DEBUG))
 		return;
 
 	va_start(args, fmt);
@@ -1679,16 +1834,19 @@
 	va_end(args);
 
 	if (compat20) {
-		packet_start(SSH2_MSG_DEBUG);
-		packet_put_char(0);	/* bool: always display */
-		packet_put_cstring(buf);
-		packet_put_cstring("");
+		if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
+		    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
+		    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
+		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
+		    (r = sshpkt_send(ssh)) != 0)
+			fatal("%s: %s", __func__, ssh_err(r));
 	} else {
-		packet_start(SSH_MSG_DEBUG);
-		packet_put_cstring(buf);
+		if ((r = sshpkt_start(ssh, SSH_MSG_DEBUG)) != 0 ||
+		    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
+		    (r = sshpkt_send(ssh)) != 0)
+			fatal("%s: %s", __func__, ssh_err(r));
 	}
-	packet_send();
-	packet_write_wait();
+	ssh_packet_write_wait(ssh);
 }
 
 /*
@@ -1699,11 +1857,12 @@
  */
 
 void
-packet_disconnect(const char *fmt,...)
+ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
 {
 	char buf[1024];
 	va_list args;
 	static int disconnecting = 0;
+	int r;
 
 	if (disconnecting)	/* Guard against recursive invocations. */
 		fatal("packet_disconnect called recursively.");
@@ -1722,37 +1881,38 @@
 
 	/* Send the disconnect message to the other side, and wait for it to get sent. */
 	if (compat20) {
-		packet_start(SSH2_MSG_DISCONNECT);
-		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
-		packet_put_cstring(buf);
-		packet_put_cstring("");
+		if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
+		    (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
+		    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
+		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
+		    (r = sshpkt_send(ssh)) != 0)
+			fatal("%s: %s", __func__, ssh_err(r));
 	} else {
-		packet_start(SSH_MSG_DISCONNECT);
-		packet_put_cstring(buf);
+		if ((r = sshpkt_start(ssh, SSH_MSG_DISCONNECT)) != 0 ||
+		    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
+		    (r = sshpkt_send(ssh)) != 0)
+			fatal("%s: %s", __func__, ssh_err(r));
 	}
-	packet_send();
-	packet_write_wait();
-
-	/* Stop listening for connections. */
-	channel_close_all();
+	ssh_packet_write_wait(ssh);
 
 	/* Close the connection. */
-	packet_close();
+	ssh_packet_close(ssh);
 	cleanup_exit(255);
 }
 
 /* Checks if there is any buffered output, and tries to write some of the output. */
 
 void
-packet_write_poll(void)
+ssh_packet_write_poll(struct ssh *ssh)
 {
-	int len = buffer_len(&active_state->output);
-	int cont;
+	struct session_state *state = ssh->state;
+	int len = sshbuf_len(state->output);
+	int cont, r;
 
 	if (len > 0) {
 		cont = 0;
-		len = roaming_write(active_state->connection_out,
-		    buffer_ptr(&active_state->output), len, &cont);
+		len = roaming_write(state->connection_out,
+		    sshbuf_ptr(state->output), len, &cont);
 		if (len == -1) {
 			if (errno == EINTR || errno == EAGAIN ||
 			    errno == EWOULDBLOCK)
@@ -1761,7 +1921,8 @@
 		}
 		if (len == 0 && !cont)
 			fatal("Write connection closed");
-		buffer_consume(&active_state->output, len);
+		if ((r = sshbuf_consume(state->output, len)) != 0)
+			fatal("%s: %s", __func__, ssh_err(r));
 	}
 }
 
@@ -1771,36 +1932,39 @@
  */
 
 void
-packet_write_wait(void)
+ssh_packet_write_wait(struct ssh *ssh)
 {
 	fd_set *setp;
 	int ret, ms_remain = 0;
 	struct timeval start, timeout, *timeoutp = NULL;
+	struct session_state *state = ssh->state;
 
-	setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
+	setp = (fd_set *)calloc(howmany(state->connection_out + 1,
 	    NFDBITS), sizeof(fd_mask));
-	packet_write_poll();
-	while (packet_have_data_to_write()) {
-		memset(setp, 0, howmany(active_state->connection_out + 1,
+	if (setp == NULL)
+		fatal("%s: calloc failed", __func__);
+	ssh_packet_write_poll(ssh);
+	while (ssh_packet_have_data_to_write(ssh)) {
+		memset(setp, 0, howmany(state->connection_out + 1,
 		    NFDBITS) * sizeof(fd_mask));
-		FD_SET(active_state->connection_out, setp);
+		FD_SET(state->connection_out, setp);
 
-		if (active_state->packet_timeout_ms > 0) {
-			ms_remain = active_state->packet_timeout_ms;
+		if (state->packet_timeout_ms > 0) {
+			ms_remain = state->packet_timeout_ms;
 			timeoutp = &timeout;
 		}
 		for (;;) {
-			if (active_state->packet_timeout_ms != -1) {
+			if (state->packet_timeout_ms != -1) {
 				ms_to_timeval(&timeout, ms_remain);
 				gettimeofday(&start, NULL);
 			}
-			if ((ret = select(active_state->connection_out + 1,
+			if ((ret = select(state->connection_out + 1,
 			    NULL, setp, NULL, timeoutp)) >= 0)
 				break;
 			if (errno != EAGAIN && errno != EINTR &&
 			    errno != EWOULDBLOCK)
 				break;
-			if (active_state->packet_timeout_ms == -1)
+			if (state->packet_timeout_ms == -1)
 				continue;
 			ms_subtract_diff(&start, &ms_remain);
 			if (ms_remain <= 0) {
@@ -1810,10 +1974,10 @@
 		}
 		if (ret == 0) {
 			logit("Connection to %.200s timed out while "
-			    "waiting to write", get_remote_ipaddr());
+			    "waiting to write", ssh_remote_ipaddr(ssh));
 			cleanup_exit(255);
 		}
-		packet_write_poll();
+		ssh_packet_write_poll(ssh);
 	}
 	free(setp);
 }
@@ -1821,33 +1985,33 @@
 /* Returns true if there is buffered data to write to the connection. */
 
 int
-packet_have_data_to_write(void)
+ssh_packet_have_data_to_write(struct ssh *ssh)
 {
-	return buffer_len(&active_state->output) != 0;
+	return sshbuf_len(ssh->state->output) != 0;
 }
 
 /* Returns true if there is not too much data to write to the connection. */
 
 int
-packet_not_very_much_data_to_write(void)
+ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
 {
-	if (active_state->interactive_mode)
-		return buffer_len(&active_state->output) < 16384;
+	if (ssh->state->interactive_mode)
+		return sshbuf_len(ssh->state->output) < 16384;
 	else
-		return buffer_len(&active_state->output) < 128 * 1024;
+		return sshbuf_len(ssh->state->output) < 128 * 1024;
 }
 
-static void
-packet_set_tos(int tos)
+void
+ssh_packet_set_tos(struct ssh *ssh, int tos)
 {
 #ifndef IP_TOS_IS_BROKEN
-	if (!packet_connection_is_on_socket())
+	if (!ssh_packet_connection_is_on_socket(ssh))
 		return;
-	switch (packet_connection_af()) {
+	switch (ssh_packet_connection_af(ssh)) {
 # ifdef IP_TOS
 	case AF_INET:
 		debug3("%s: set IP_TOS 0x%02x", __func__, tos);
-		if (setsockopt(active_state->connection_in,
+		if (setsockopt(ssh->state->connection_in,
 		    IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
 			error("setsockopt IP_TOS %d: %.100s:",
 			    tos, strerror(errno));
@@ -1856,7 +2020,7 @@
 # ifdef IPV6_TCLASS
 	case AF_INET6:
 		debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
-		if (setsockopt(active_state->connection_in,
+		if (setsockopt(ssh->state->connection_in,
 		    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
 			error("setsockopt IPV6_TCLASS %d: %.100s:",
 			    tos, strerror(errno));
@@ -1869,71 +2033,69 @@
 /* Informs that the current session is interactive.  Sets IP flags for that. */
 
 void
-packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
+ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
 {
-	if (active_state->set_interactive_called)
+	struct session_state *state = ssh->state;
+
+	if (state->set_interactive_called)
 		return;
-	active_state->set_interactive_called = 1;
+	state->set_interactive_called = 1;
 
 	/* Record that we are in interactive mode. */
-	active_state->interactive_mode = interactive;
+	state->interactive_mode = interactive;
 
 	/* Only set socket options if using a socket.  */
-	if (!packet_connection_is_on_socket())
+	if (!ssh_packet_connection_is_on_socket(ssh))
 		return;
-	set_nodelay(active_state->connection_in);
-	packet_set_tos(interactive ? qos_interactive : qos_bulk);
+	set_nodelay(state->connection_in);
+	ssh_packet_set_tos(ssh, interactive ? qos_interactive :
+	    qos_bulk);
 }
 
 /* Returns true if the current connection is interactive. */
 
 int
-packet_is_interactive(void)
+ssh_packet_is_interactive(struct ssh *ssh)
 {
-	return active_state->interactive_mode;
+	return ssh->state->interactive_mode;
 }
 
 int
-packet_set_maxsize(u_int s)
+ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
 {
-	if (active_state->set_maxsize_called) {
+	struct session_state *state = ssh->state;
+
+	if (state->set_maxsize_called) {
 		logit("packet_set_maxsize: called twice: old %d new %d",
-		    active_state->max_packet_size, s);
+		    state->max_packet_size, s);
 		return -1;
 	}
 	if (s < 4 * 1024 || s > 1024 * 1024) {
 		logit("packet_set_maxsize: bad size %d", s);
 		return -1;
 	}
-	active_state->set_maxsize_called = 1;
+	state->set_maxsize_called = 1;
 	debug("packet_set_maxsize: setting to %d", s);
-	active_state->max_packet_size = s;
+	state->max_packet_size = s;
 	return s;
 }
 
 int
-packet_inc_alive_timeouts(void)
+ssh_packet_inc_alive_timeouts(struct ssh *ssh)
 {
-	return ++active_state->keep_alive_timeouts;
+	return ++ssh->state->keep_alive_timeouts;
 }
 
 void
-packet_set_alive_timeouts(int ka)
+ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
 {
-	active_state->keep_alive_timeouts = ka;
+	ssh->state->keep_alive_timeouts = ka;
 }
 
 u_int
-packet_get_maxsize(void)
+ssh_packet_get_maxsize(struct ssh *ssh)
 {
-	return active_state->max_packet_size;
-}
-
-/* roundup current message to pad bytes */
-void
-packet_add_padding(u_char pad)
-{
-	active_state->extra_pad = pad;
+	return ssh->state->max_packet_size;
 }
 
 /*
@@ -1948,155 +2110,702 @@
  * protection measure against advanced traffic analysis techniques.
  */
 void
-packet_send_ignore(int nbytes)
+ssh_packet_send_ignore(struct ssh *ssh, int nbytes)
 {
 	u_int32_t rnd = 0;
-	int i;
+	int r, i;
 
-	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
-	packet_put_int(nbytes);
+	if ((r = sshpkt_start(ssh, compat20 ?
+	    SSH2_MSG_IGNORE : SSH_MSG_IGNORE)) != 0 ||
+	    (r = sshpkt_put_u32(ssh, nbytes)) != 0)
+		fatal("%s: %s", __func__, ssh_err(r));
 	for (i = 0; i < nbytes; i++) {
 		if (i % 4 == 0)
 			rnd = arc4random();
-		packet_put_char((u_char)rnd & 0xff);
+		if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
+			fatal("%s: %s", __func__, ssh_err(r));
 		rnd >>= 8;
 	}
 }
 
 #define MAX_PACKETS	(1U<<31)
 int
-packet_need_rekeying(void)
+ssh_packet_need_rekeying(struct ssh *ssh)
 {
-	if (datafellows & SSH_BUG_NOREKEY)
+	struct session_state *state = ssh->state;
+
+	if (ssh->compat & SSH_BUG_NOREKEY)
 		return 0;
 	return
-	    (active_state->p_send.packets > MAX_PACKETS) ||
-	    (active_state->p_read.packets > MAX_PACKETS) ||
-	    (active_state->max_blocks_out &&
-	        (active_state->p_send.blocks > active_state->max_blocks_out)) ||
-	    (active_state->max_blocks_in &&
-	        (active_state->p_read.blocks > active_state->max_blocks_in)) ||
-	    (active_state->rekey_interval != 0 && active_state->rekey_time +
-		 active_state->rekey_interval <= monotime());
+	    (state->p_send.packets > MAX_PACKETS) ||
+	    (state->p_read.packets > MAX_PACKETS) ||
+	    (state->max_blocks_out &&
+	        (state->p_send.blocks > state->max_blocks_out)) ||
+	    (state->max_blocks_in &&
+	        (state->p_read.blocks > state->max_blocks_in)) ||
+	    (state->rekey_interval != 0 && state->rekey_time +
+		 state->rekey_interval <= monotime());
 }
 
 void
-packet_set_rekey_limits(u_int32_t bytes, time_t seconds)
+ssh_packet_set_rekey_limits(struct ssh *ssh, u_int32_t bytes, time_t seconds)
 {
 	debug3("rekey after %lld bytes, %d seconds", (long long)bytes,
 	    (int)seconds);
-	active_state->rekey_limit = bytes;
-	active_state->rekey_interval = seconds;
+	ssh->state->rekey_limit = bytes;
+	ssh->state->rekey_interval = seconds;
 	/*
 	 * We set the time here so that in post-auth privsep slave we count
 	 * from the completion of the authentication.
 	 */
-	active_state->rekey_time = monotime();
+	ssh->state->rekey_time = monotime();
 }
 
 time_t
-packet_get_rekey_timeout(void)
+ssh_packet_get_rekey_timeout(struct ssh *ssh)
 {
 	time_t seconds;
 
-	seconds = active_state->rekey_time + active_state->rekey_interval -
+	seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
 	    monotime();
 	return (seconds <= 0 ? 1 : seconds);
 }
 
 void
-packet_set_server(void)
+ssh_packet_set_server(struct ssh *ssh)
 {
-	active_state->server_side = 1;
+	ssh->state->server_side = 1;
 }
 
 void
-packet_set_authenticated(void)
+ssh_packet_set_authenticated(struct ssh *ssh)
 {
-	active_state->after_authentication = 1;
+	ssh->state->after_authentication = 1;
 }
 
 void *
-packet_get_input(void)
+ssh_packet_get_input(struct ssh *ssh)
 {
-	return (void *)&active_state->input;
+	return (void *)ssh->state->input;
 }
 
 void *
-packet_get_output(void)
+ssh_packet_get_output(struct ssh *ssh)
 {
-	return (void *)&active_state->output;
+	return (void *)ssh->state->output;
 }
 
-void *
-packet_get_newkeys(int mode)
-{
-	return (void *)active_state->newkeys[mode];
-}
-
+/* XXX TODO update roaming to new API (does not work anyway) */
 /*
  * Save the state for the real connection, and use a separate state when
  * resuming a suspended connection.
  */
 void
-packet_backup_state(void)
+ssh_packet_backup_state(struct ssh *ssh,
+    struct ssh *backup_state)
 {
-	struct session_state *tmp;
+	struct ssh *tmp;
 
-	close(active_state->connection_in);
-	active_state->connection_in = -1;
-	close(active_state->connection_out);
-	active_state->connection_out = -1;
+	close(ssh->state->connection_in);
+	ssh->state->connection_in = -1;
+	close(ssh->state->connection_out);
+	ssh->state->connection_out = -1;
 	if (backup_state)
 		tmp = backup_state;
 	else
-		tmp = alloc_session_state();
-	backup_state = active_state;
-	active_state = tmp;
+		tmp = ssh_alloc_session_state();
+	backup_state = ssh;
+	ssh = tmp;
 }
 
+/* XXX FIXME FIXME FIXME */
 /*
  * Swap in the old state when resuming a connecion.
  */
 void
-packet_restore_state(void)
+ssh_packet_restore_state(struct ssh *ssh,
+    struct ssh *backup_state)
 {
-	struct session_state *tmp;
-	void *buf;
+	struct ssh *tmp;
 	u_int len;
+	int r;
 
 	tmp = backup_state;
-	backup_state = active_state;
-	active_state = tmp;
-	active_state->connection_in = backup_state->connection_in;
-	backup_state->connection_in = -1;
-	active_state->connection_out = backup_state->connection_out;
-	backup_state->connection_out = -1;
-	len = buffer_len(&backup_state->input);
+	backup_state = ssh;
+	ssh = tmp;
+	ssh->state->connection_in = backup_state->state->connection_in;
+	backup_state->state->connection_in = -1;
+	ssh->state->connection_out = backup_state->state->connection_out;
+	backup_state->state->connection_out = -1;
+	len = sshbuf_len(backup_state->state->input);
 	if (len > 0) {
-		buf = buffer_ptr(&backup_state->input);
-		buffer_append(&active_state->input, buf, len);
-		buffer_clear(&backup_state->input);
+		if ((r = sshbuf_putb(ssh->state->input,
+		    backup_state->state->input)) != 0)
+			fatal("%s: %s", __func__, ssh_err(r));
+		sshbuf_reset(backup_state->state->input);
 		add_recv_bytes(len);
 	}
 }
 
 /* Reset after_authentication and reset compression in post-auth privsep */
-void
-packet_set_postauth(void)
+static int
+ssh_packet_set_postauth(struct ssh *ssh)
 {
-	Comp *comp;
-	int mode;
+	struct sshcomp *comp;
+	int r, mode;
 
 	debug("%s: called", __func__);
 	/* This was set in net child, but is not visible in user child */
-	active_state->after_authentication = 1;
-	active_state->rekeying = 0;
+	ssh->state->after_authentication = 1;
+	ssh->state->rekeying = 0;
 	for (mode = 0; mode < MODE_MAX; mode++) {
-		if (active_state->newkeys[mode] == NULL)
+		if (ssh->state->newkeys[mode] == NULL)
 			continue;
-		comp = &active_state->newkeys[mode]->comp;
-		if (comp && comp->enabled)
-			packet_init_compression();
+		comp = &ssh->state->newkeys[mode]->comp;
+		if (comp && comp->enabled &&
+		    (r = ssh_packet_init_compression(ssh)) != 0)
+			return r;
 	}
+	return 0;
+}
+
+/* Packet state (de-)serialization for privsep */
+
+/* turn kex into a blob for packet state serialization */
+static int
+kex_to_blob(struct sshbuf *m, struct kex *kex)
+{
+	int r;
+
+	if ((r = sshbuf_put_string(m, kex->session_id,
+	    kex->session_id_len)) != 0 ||
+	    (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
+	    (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
+	    (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
+	    (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
+	    (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
+	    (r = sshbuf_put_u32(m, kex->flags)) != 0 ||
+	    (r = sshbuf_put_cstring(m, kex->client_version_string)) != 0 ||
+	    (r = sshbuf_put_cstring(m, kex->server_version_string)) != 0)
+		return r;
+	return 0;
+}
+
+/* turn key exchange results into a blob for packet state serialization */
+static int
+newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
+{
+	struct sshbuf *b;
+	struct sshcipher_ctx *cc;
+	struct sshcomp *comp;
+	struct sshenc *enc;
+	struct sshmac *mac;
+	struct newkeys *newkey;
+	int r;
+
+	if ((newkey = ssh->state->newkeys[mode]) == NULL)
+		return SSH_ERR_INTERNAL_ERROR;
+	enc = &newkey->enc;
+	mac = &newkey->mac;
+	comp = &newkey->comp;
+	cc = (mode == MODE_OUT) ? &ssh->state->send_context :
+	    &ssh->state->receive_context;
+	if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
+		return r;
+	if ((b = sshbuf_new()) == NULL)
+		return SSH_ERR_ALLOC_FAIL;
+	/* The cipher struct is constant and shared, you export pointer */
+	if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
+	    (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
+	    (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
+	    (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
+	    (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
+	    (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
+		goto out;
+	if (cipher_authlen(enc->cipher) == 0) {
+		if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
+		    (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
+		    (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
+			goto out;
+	}
+	if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
+	    (r = sshbuf_put_u32(b, comp->enabled)) != 0 ||
+	    (r = sshbuf_put_cstring(b, comp->name)) != 0)
+		goto out;
+	r = sshbuf_put_stringb(m, b);
+ out:
+	if (b != NULL)
+		sshbuf_free(b);
+	return r;
+}
+
+/* serialize packet state into a blob */
+int
+ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
+{
+	struct session_state *state = ssh->state;
+	u_char *p;
+	size_t slen, rlen;
+	int r, ssh1cipher;
+
+	if (!compat20) {
+		ssh1cipher = cipher_get_number(state->receive_context.cipher);
+		slen = cipher_get_keyiv_len(&state->send_context);
+		rlen = cipher_get_keyiv_len(&state->receive_context);
+		if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
+		    (r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
+		    (r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
+		    (r = sshbuf_put_u32(m, slen)) != 0 ||
+		    (r = sshbuf_reserve(m, slen, &p)) != 0 ||
+		    (r = cipher_get_keyiv(&state->send_context, p, slen)) != 0 ||
+		    (r = sshbuf_put_u32(m, rlen)) != 0 ||
+		    (r = sshbuf_reserve(m, rlen, &p)) != 0 ||
+		    (r = cipher_get_keyiv(&state->receive_context, p, rlen)) != 0)
+			return r;
+	} else {
+		if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
+		    (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
+		    (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
+		    (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
+		    (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
+		    (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
+		    (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
+		    (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
+		    (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
+		    (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
+		    (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
+			return r;
+	}
+
+	slen = cipher_get_keycontext(&state->send_context, NULL);
+	rlen = cipher_get_keycontext(&state->receive_context, NULL);
+	if ((r = sshbuf_put_u32(m, slen)) != 0 ||
+	    (r = sshbuf_reserve(m, slen, &p)) != 0)
+		return r;
+	if (cipher_get_keycontext(&state->send_context, p) != (int)slen)
+		return SSH_ERR_INTERNAL_ERROR;
+	if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
+	    (r = sshbuf_reserve(m, rlen, &p)) != 0)
+		return r;
+	if (cipher_get_keycontext(&state->receive_context, p) != (int)rlen)
+		return SSH_ERR_INTERNAL_ERROR;
+
+	if ((r = ssh_packet_get_compress_state(m, ssh)) != 0 ||
+	    (r = sshbuf_put_stringb(m, state->input)) != 0 ||
+	    (r = sshbuf_put_stringb(m, state->output)) != 0)
+		return r;
+
+	if (compat20) {
+		if ((r = sshbuf_put_u64(m, get_sent_bytes())) != 0 ||
+		    (r = sshbuf_put_u64(m, get_recv_bytes())) != 0)
+			return r;
+	}
+	return 0;
+}
+
+/* restore key exchange results from blob for packet state de-serialization */
+static int
+newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
+{
+	struct sshbuf *b = NULL;
+	struct sshcomp *comp;
+	struct sshenc *enc;
+	struct sshmac *mac;
+	struct newkeys *newkey = NULL;
+	size_t keylen, ivlen, maclen;
+	int r;
+
+	if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
+		r = SSH_ERR_ALLOC_FAIL;
+		goto out;
+	}
+	if ((r = sshbuf_froms(m, &b)) != 0)
+		goto out;
+#ifdef DEBUG_PK
+	sshbuf_dump(b, stderr);
+#endif
+	enc = &newkey->enc;
+	mac = &newkey->mac;
+	comp = &newkey->comp;
+
+	if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
+	    (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
+	    (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
+	    (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
+	    (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
+	    (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
+		goto out;
+	if (cipher_authlen(enc->cipher) == 0) {
+		if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
+			goto out;
+		if ((r = mac_setup(mac, mac->name)) != 0)
+			goto out;
+		if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
+		    (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
+			goto out;
+		if (maclen > mac->key_len) {
+			r = SSH_ERR_INVALID_FORMAT;
+			goto out;
+		}
+		mac->key_len = maclen;
+	}
+	if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
+	    (r = sshbuf_get_u32(b, (u_int *)&comp->enabled)) != 0 ||
+	    (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
+		goto out;
+	if (enc->name == NULL ||
+	    cipher_by_name(enc->name) != enc->cipher) {
+		r = SSH_ERR_INVALID_FORMAT;
+		goto out;
+	}
+	if (sshbuf_len(b) != 0) {
+		r = SSH_ERR_INVALID_FORMAT;
+		goto out;
+	}
+	enc->key_len = keylen;
+	enc->iv_len = ivlen;
+	ssh->kex->newkeys[mode] = newkey;
+	newkey = NULL;
+	r = 0;
+ out:
+	if (newkey != NULL)
+		free(newkey);
+	if (b != NULL)
+		sshbuf_free(b);
+	return r;
+}
+
+/* restore kex from blob for packet state de-serialization */
+static int
+kex_from_blob(struct sshbuf *m, struct kex **kexp)
+{
+	struct kex *kex;
+	int r;
+
+	if ((kex = calloc(1, sizeof(struct kex))) == NULL ||
+	    (kex->my = sshbuf_new()) == NULL ||
+	    (kex->peer = sshbuf_new()) == NULL) {
+		r = SSH_ERR_ALLOC_FAIL;
+		goto out;
+	}
+	if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
+	    (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
+	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
+	    (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
+	    (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
+	    (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
+	    (r = sshbuf_get_u32(m, &kex->flags)) != 0 ||
+	    (r = sshbuf_get_cstring(m, &kex->client_version_string, NULL)) != 0 ||
+	    (r = sshbuf_get_cstring(m, &kex->server_version_string, NULL)) != 0)
+		goto out;
+	kex->server = 1;
+	kex->done = 1;
+	r = 0;
+ out:
+	if (r != 0 || kexp == NULL) {
+		if (kex != NULL) {
+			if (kex->my != NULL)
+				sshbuf_free(kex->my);
+			if (kex->peer != NULL)
+				sshbuf_free(kex->peer);
+			free(kex);
+		}
+		if (kexp != NULL)
+			*kexp = NULL;
+	} else {
+		*kexp = kex;
+	}
+	return r;
+}
+
+/*
+ * Restore packet state from content of blob 'm' (de-serialization).
+ * Note that 'm' will be partially consumed on parsing or any other errors.
+ */
+int
+ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
+{
+	struct session_state *state = ssh->state;
+	const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output;
+	size_t ssh1keylen, rlen, slen, ilen, olen;
+	int r;
+	u_int ssh1cipher = 0;
+	u_int64_t sent_bytes = 0, recv_bytes = 0;
+
+	if (!compat20) {
+		if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 ||
+		    (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 ||
+		    (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 ||
+		    (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 ||
+		    (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0)
+			return r;
+		if (ssh1cipher > INT_MAX)
+			return SSH_ERR_KEY_UNKNOWN_CIPHER;
+		ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen,
+		    (int)ssh1cipher);
+		if (cipher_get_keyiv_len(&state->send_context) != (int)slen ||
+		    cipher_get_keyiv_len(&state->receive_context) != (int)rlen)
+			return SSH_ERR_INVALID_FORMAT;
+		if ((r = cipher_set_keyiv(&state->send_context, ivout)) != 0 ||
+		    (r = cipher_set_keyiv(&state->receive_context, ivin)) != 0)
+			return r;
+	} else {
+		if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
+		    (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
+		    (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
+		    (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
+		    (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
+		    (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
+		    (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
+		    (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
+		    (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
+		    (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
+		    (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
+			return r;
+		/* XXX ssh_set_newkeys overrides p_read.packets? XXX */
+		if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
+		    (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
+			return r;
+	}
+	if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 ||
+	    (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0)
+		return r;
+	if (cipher_get_keycontext(&state->send_context, NULL) != (int)slen ||
+	    cipher_get_keycontext(&state->receive_context, NULL) != (int)rlen)
+		return SSH_ERR_INVALID_FORMAT;
+	cipher_set_keycontext(&state->send_context, keyout);
+	cipher_set_keycontext(&state->receive_context, keyin);
+
+	if ((r = ssh_packet_set_compress_state(ssh, m)) != 0 ||
+	    (r = ssh_packet_set_postauth(ssh)) != 0)
+		return r;
+
+	sshbuf_reset(state->input);
+	sshbuf_reset(state->output);
+	if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
+	    (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
+	    (r = sshbuf_put(state->input, input, ilen)) != 0 ||
+	    (r = sshbuf_put(state->output, output, olen)) != 0)
+		return r;
+
+	if (compat20) {
+		if ((r = sshbuf_get_u64(m, &sent_bytes)) != 0 ||
+		    (r = sshbuf_get_u64(m, &recv_bytes)) != 0)
+			return r;
+		roam_set_bytes(sent_bytes, recv_bytes);
+	}
+	if (sshbuf_len(m))
+		return SSH_ERR_INVALID_FORMAT;
+	debug3("%s: done", __func__);
+	return 0;
+}
+
+/* NEW API */
+
+/* put data to the outgoing packet */
+
+int
+sshpkt_put(struct ssh *ssh, const void *v, size_t len)
+{
+	return sshbuf_put(ssh->state->outgoing_packet, v, len);
+}
+
+int
+sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
+{
+	return sshbuf_putb(ssh->state->outgoing_packet, b);
+}
+
+int
+sshpkt_put_u8(struct ssh *ssh, u_char val)
+{
+	return sshbuf_put_u8(ssh->state->outgoing_packet, val);
+}
+
+int
+sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
+{
+	return sshbuf_put_u32(ssh->state->outgoing_packet, val);
+}
+
+int
+sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
+{
+	return sshbuf_put_u64(ssh->state->outgoing_packet, val);
+}
+
+int
+sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
+{
+	return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
+}
+
+int
+sshpkt_put_cstring(struct ssh *ssh, const void *v)
+{
+	return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
+}
+
+int
+sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
+{
+	return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
+}
+
+int
+sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
+{
+	return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
+}
+
+int
+sshpkt_put_bignum1(struct ssh *ssh, const BIGNUM *v)
+{
+	return sshbuf_put_bignum1(ssh->state->outgoing_packet, v);
+}
+
+int
+sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
+{
+	return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
+}
+
+/* fetch data from the incoming packet */
+
+int
+sshpkt_get(struct ssh *ssh, void *valp, size_t len)
+{
+	return sshbuf_get(ssh->state->incoming_packet, valp, len);
+}
+
+int
+sshpkt_get_u8(struct ssh *ssh, u_char *valp)
+{
+	return sshbuf_get_u8(ssh->state->incoming_packet, valp);
+}
+
+int
+sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
+{
+	return sshbuf_get_u32(ssh->state->incoming_packet, valp);
+}
+
+int
+sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
+{
+	return sshbuf_get_u64(ssh->state->incoming_packet, valp);
+}
+
+int
+sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
+{
+	return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
+}
+
+int
+sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
+{
+	return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
+}
+
+int
+sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
+{
+	return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
+}
+
+int
+sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
+{
+	return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
+}
+
+int
+sshpkt_get_bignum1(struct ssh *ssh, BIGNUM *v)
+{
+	return sshbuf_get_bignum1(ssh->state->incoming_packet, v);
+}
+
+int
+sshpkt_get_bignum2(struct ssh *ssh, BIGNUM *v)
+{
+	return sshbuf_get_bignum2(ssh->state->incoming_packet, v);
+}
+
+int
+sshpkt_get_end(struct ssh *ssh)
+{
+	if (sshbuf_len(ssh->state->incoming_packet) > 0)
+		return SSH_ERR_UNEXPECTED_TRAILING_DATA;
+	return 0;
+}
+
+const u_char *
+sshpkt_ptr(struct ssh *ssh, size_t *lenp)
+{
+	if (lenp != NULL)
+		*lenp = sshbuf_len(ssh->state->incoming_packet);
+	return sshbuf_ptr(ssh->state->incoming_packet);
+}
+
+/* start a new packet */
+
+int
+sshpkt_start(struct ssh *ssh, u_char type)
+{
+	u_char buf[9];
+	int len;
+
+	DBG(debug("packet_start[%d]", type));
+	len = compat20 ? 6 : 9;
+	memset(buf, 0, len - 1);
+	buf[len - 1] = type;
+	sshbuf_reset(ssh->state->outgoing_packet);
+	return sshbuf_put(ssh->state->outgoing_packet, buf, len);
+}
+
+/* send it */
+
+int
+sshpkt_send(struct ssh *ssh)
+{
+	if (compat20)
+		return ssh_packet_send2(ssh);
+	else
+		return ssh_packet_send1(ssh);
+}
+
+int
+sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
+{
+	char buf[1024];
+	va_list args;
+	int r;
+
+	va_start(args, fmt);
+	vsnprintf(buf, sizeof(buf), fmt, args);
+	va_end(args);
+
+	if (compat20) {
+		if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
+		    (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
+		    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
+		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
+		    (r = sshpkt_send(ssh)) != 0)
+			return r;
+	} else {
+		if ((r = sshpkt_start(ssh, SSH_MSG_DISCONNECT)) != 0 ||
+		    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
+		    (r = sshpkt_send(ssh)) != 0)
+			return r;
+	}
+	return 0;
+}
+
+/* roundup current message to pad bytes */
+int
+sshpkt_add_padding(struct ssh *ssh, u_char pad)
+{
+	ssh->state->extra_pad = pad;
+	return 0;
 }
diff --git a/packet.h b/packet.h
index e7b5fcb..0d69197 100644
--- a/packet.h
+++ b/packet.h
@@ -1,4 +1,4 @@
-/* $OpenBSD: packet.h,v 1.61 2014/05/03 17:20:34 markus Exp $ */
+/* $OpenBSD: packet.h,v 1.62 2015/01/19 19:52:16 markus Exp $ */
 
 /*
  * Author: Tatu Ylonen <ylo@cs.hut.fi>
@@ -18,111 +18,147 @@
 
 #include <termios.h>
 
-#include <openssl/bn.h>
-#ifdef OPENSSL_HAS_ECC
-#include <openssl/ec.h>
+#ifdef WITH_OPENSSL
+# include <openssl/bn.h>
+# ifdef OPENSSL_HAS_ECC
+#  include <openssl/ec.h>
+# endif
 #endif
+#include <sys/signal.h>
+#include <sys/queue.h>
 
-void     packet_set_connection(int, int);
-void     packet_set_timeout(int, int);
-void     packet_set_nonblocking(void);
-int      packet_get_connection_in(void);
-int      packet_get_connection_out(void);
-void     packet_close(void);
-void	 packet_set_encryption_key(const u_char *, u_int, int);
-u_int	 packet_get_encryption_key(u_char *);
-void     packet_set_protocol_flags(u_int);
-u_int	 packet_get_protocol_flags(void);
-void     packet_start_compression(int);
-void     packet_set_interactive(int, int, int);
-int      packet_is_interactive(void);
-void     packet_set_server(void);
-void     packet_set_authenticated(void);
+struct kex;
+struct sshkey;
+struct sshbuf;
+struct session_state;	/* private session data */
 
-void     packet_start(u_char);
-void     packet_put_char(int ch);
-void     packet_put_int(u_int value);
-void     packet_put_int64(u_int64_t value);
-void     packet_put_bignum(BIGNUM * value);
-void     packet_put_bignum2(BIGNUM * value);
-#ifdef OPENSSL_HAS_ECC
-void     packet_put_ecpoint(const EC_GROUP *, const EC_POINT *);
-#endif
-void     packet_put_string(const void *buf, u_int len);
-void     packet_put_cstring(const char *str);
-void     packet_put_raw(const void *buf, u_int len);
-void     packet_send(void);
+struct ssh {
+	/* Session state */
+	struct session_state *state;
 
-int      packet_read(void);
-void     packet_read_expect(int type);
-void     packet_process_incoming(const char *buf, u_int len);
-int      packet_read_seqnr(u_int32_t *seqnr_p);
-int      packet_read_poll_seqnr(u_int32_t *seqnr_p);
+	/* Key exchange */
+	struct kex *kex;
 
-u_int	 packet_get_char(void);
-u_int	 packet_get_int(void);
-u_int64_t packet_get_int64(void);
-void     packet_get_bignum(BIGNUM * value);
-void     packet_get_bignum2(BIGNUM * value);
-#ifdef OPENSSL_HAS_ECC
-void	 packet_get_ecpoint(const EC_GROUP *, EC_POINT *);
-#endif
-void	*packet_get_raw(u_int *length_ptr);
-void	*packet_get_string(u_int *length_ptr);
-char	*packet_get_cstring(u_int *length_ptr);
-const void	*packet_get_string_ptr(u_int *length_ptr);
-void     packet_disconnect(const char *fmt,...) __attribute__((noreturn)) __attribute__((format(printf, 1, 2)));
-void     packet_send_debug(const char *fmt,...) __attribute__((format(printf, 1, 2)));
+	/* cached remote ip address and port*/
+	char *remote_ipaddr;
+	int remote_port;
 
-void	 set_newkeys(int mode);
-int	 packet_get_keyiv_len(int);
-void	 packet_get_keyiv(int, u_char *, u_int);
-int	 packet_get_keycontext(int, u_char *);
-void	 packet_set_keycontext(int, u_char *);
-void	 packet_get_state(int, u_int32_t *, u_int64_t *, u_int32_t *, u_int64_t *);
-void	 packet_set_state(int, u_int32_t, u_int64_t, u_int32_t, u_int64_t);
-int	 packet_get_ssh1_cipher(void);
-void	 packet_set_iv(int, u_char *);
-void	*packet_get_newkeys(int);
+	/* datafellows */
+	int compat;
+};
 
-void     packet_write_poll(void);
-void     packet_write_wait(void);
-int      packet_have_data_to_write(void);
-int      packet_not_very_much_data_to_write(void);
+struct ssh *ssh_alloc_session_state(void);
+struct ssh *ssh_packet_set_connection(struct ssh *, int, int);
+void     ssh_packet_set_timeout(struct ssh *, int, int);
+int	 ssh_packet_stop_discard(struct ssh *);
+int	 ssh_packet_connection_af(struct ssh *);
+void     ssh_packet_set_nonblocking(struct ssh *);
+int      ssh_packet_get_connection_in(struct ssh *);
+int      ssh_packet_get_connection_out(struct ssh *);
+void     ssh_packet_close(struct ssh *);
+void	 ssh_packet_set_encryption_key(struct ssh *, const u_char *, u_int, int);
+void     ssh_packet_set_protocol_flags(struct ssh *, u_int);
+u_int	 ssh_packet_get_protocol_flags(struct ssh *);
+int      ssh_packet_start_compression(struct ssh *, int);
+void	 ssh_packet_set_tos(struct ssh *, int);
+void     ssh_packet_set_interactive(struct ssh *, int, int, int);
+int      ssh_packet_is_interactive(struct ssh *);
+void     ssh_packet_set_server(struct ssh *);
+void     ssh_packet_set_authenticated(struct ssh *);
 
-int	 packet_connection_is_on_socket(void);
-int	 packet_remaining(void);
-void	 packet_send_ignore(int);
-void	 packet_add_padding(u_char);
+int	 ssh_packet_send1(struct ssh *);
+int	 ssh_packet_send2_wrapped(struct ssh *);
+int	 ssh_packet_send2(struct ssh *);
+
+int      ssh_packet_read(struct ssh *);
+void     ssh_packet_read_expect(struct ssh *, int type);
+int      ssh_packet_read_poll(struct ssh *);
+int ssh_packet_read_poll1(struct ssh *, u_char *);
+int ssh_packet_read_poll2(struct ssh *, u_char *, u_int32_t *seqnr_p);
+void     ssh_packet_process_incoming(struct ssh *, const char *buf, u_int len);
+int      ssh_packet_read_seqnr(struct ssh *, u_char *, u_int32_t *seqnr_p);
+int      ssh_packet_read_poll_seqnr(struct ssh *, u_char *, u_int32_t *seqnr_p);
+
+const void *ssh_packet_get_string_ptr(struct ssh *, u_int *length_ptr);
+void     ssh_packet_disconnect(struct ssh *, const char *fmt, ...)
+	__attribute__((format(printf, 2, 3)))
+	__attribute__((noreturn));
+void     ssh_packet_send_debug(struct ssh *, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
+
+int	 ssh_set_newkeys(struct ssh *, int mode);
+void	 ssh_packet_get_bytes(struct ssh *, u_int64_t *, u_int64_t *);
+
+typedef void *(ssh_packet_comp_alloc_func)(void *, u_int, u_int);
+typedef void (ssh_packet_comp_free_func)(void *, void *);
+void	 ssh_packet_set_compress_hooks(struct ssh *, void *,
+    ssh_packet_comp_alloc_func *, ssh_packet_comp_free_func *);
+
+void     ssh_packet_write_poll(struct ssh *);
+void     ssh_packet_write_wait(struct ssh *);
+int      ssh_packet_have_data_to_write(struct ssh *);
+int      ssh_packet_not_very_much_data_to_write(struct ssh *);
+
+int	 ssh_packet_connection_is_on_socket(struct ssh *);
+int	 ssh_packet_remaining(struct ssh *);
+void	 ssh_packet_send_ignore(struct ssh *, int);
 
 void	 tty_make_modes(int, struct termios *);
 void	 tty_parse_modes(int, int *);
 
-void	 packet_set_alive_timeouts(int);
-int	 packet_inc_alive_timeouts(void);
-int	 packet_set_maxsize(u_int);
-u_int	 packet_get_maxsize(void);
+void	 ssh_packet_set_alive_timeouts(struct ssh *, int);
+int	 ssh_packet_inc_alive_timeouts(struct ssh *);
+int	 ssh_packet_set_maxsize(struct ssh *, u_int);
+u_int	 ssh_packet_get_maxsize(struct ssh *);
 
-/* don't allow remaining bytes after the end of the message */
-#define packet_check_eom() \
-do { \
-	int _len = packet_remaining(); \
-	if (_len > 0) { \
-		logit("Packet integrity error (%d bytes remaining) at %s:%d", \
-		    _len ,__FILE__, __LINE__); \
-		packet_disconnect("Packet integrity error."); \
-	} \
-} while (0)
+int	 ssh_packet_get_state(struct ssh *, struct sshbuf *);
+int	 ssh_packet_set_state(struct ssh *, struct sshbuf *);
 
-int	 packet_need_rekeying(void);
-void	 packet_set_rekey_limits(u_int32_t, time_t);
-time_t	 packet_get_rekey_timeout(void);
+const char *ssh_remote_ipaddr(struct ssh *);
 
-void	 packet_backup_state(void);
-void	 packet_restore_state(void);
-void	 packet_set_postauth(void);
+int	 ssh_packet_need_rekeying(struct ssh *);
+void	 ssh_packet_set_rekey_limits(struct ssh *, u_int32_t, time_t);
+time_t	 ssh_packet_get_rekey_timeout(struct ssh *);
 
-void	*packet_get_input(void);
-void	*packet_get_output(void);
+/* XXX FIXME */
+void	 ssh_packet_backup_state(struct ssh *, struct ssh *);
+void	 ssh_packet_restore_state(struct ssh *, struct ssh *);
+
+void	*ssh_packet_get_input(struct ssh *);
+void	*ssh_packet_get_output(struct ssh *);
+
+/* new API */
+int	sshpkt_start(struct ssh *ssh, u_char type);
+int	sshpkt_send(struct ssh *ssh);
+int     sshpkt_disconnect(struct ssh *, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
+int	sshpkt_add_padding(struct ssh *, u_char);
+
+int	sshpkt_put(struct ssh *ssh, const void *v, size_t len);
+int	sshpkt_putb(struct ssh *ssh, const struct sshbuf *b);
+int	sshpkt_put_u8(struct ssh *ssh, u_char val);
+int	sshpkt_put_u32(struct ssh *ssh, u_int32_t val);
+int	sshpkt_put_u64(struct ssh *ssh, u_int64_t val);
+int	sshpkt_put_string(struct ssh *ssh, const void *v, size_t len);
+int	sshpkt_put_cstring(struct ssh *ssh, const void *v);
+int	sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v);
+int	sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g);
+int	sshpkt_put_bignum1(struct ssh *ssh, const BIGNUM *v);
+int	sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v);
+
+int	sshpkt_get(struct ssh *ssh, void *valp, size_t len);
+int	sshpkt_get_u8(struct ssh *ssh, u_char *valp);
+int	sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp);
+int	sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp);
+int	sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp);
+int	sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp);
+int	sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp);
+int	sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g);
+int	sshpkt_get_bignum1(struct ssh *ssh, BIGNUM *v);
+int	sshpkt_get_bignum2(struct ssh *ssh, BIGNUM *v);
+int	sshpkt_get_end(struct ssh *ssh);
+const u_char	*sshpkt_ptr(struct ssh *, size_t *lenp);
+
+/* OLD API */
+extern struct ssh *active_state;
+#include "opacket.h"
 
 #endif				/* PACKET_H */
diff --git a/roaming_dummy.c b/roaming_dummy.c
index 45c4008..837de69 100644
--- a/roaming_dummy.c
+++ b/roaming_dummy.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: roaming_dummy.c,v 1.3 2009/06/21 09:04:03 dtucker Exp $ */
+/* $OpenBSD: roaming_dummy.c,v 1.4 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright (c) 2004-2009 AppGate Network Security AB
  *
@@ -35,6 +35,17 @@
 	return 0;
 }
 
+u_int64_t
+get_sent_bytes(void)
+{
+	return 0;
+}
+
+void
+roam_set_bytes(u_int64_t sent, u_int64_t recvd)
+{
+}
+
 ssize_t
 roaming_write(int fd, const void *buf, size_t count, int *cont)
 {
diff --git a/serverloop.c b/serverloop.c
index e92f9e2..f1fbb05 100644
--- a/serverloop.c
+++ b/serverloop.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: serverloop.c,v 1.172 2014/07/15 15:54:14 millert Exp $ */
+/* $OpenBSD: serverloop.c,v 1.173 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Author: Tatu Ylonen <ylo@cs.hut.fi>
  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -83,7 +83,6 @@
 extern ServerOptions options;
 
 /* XXX */
-extern Kex *xxx_kex;
 extern Authctxt *the_authctxt;
 extern int use_privsep;
 
@@ -545,7 +544,7 @@
 static void
 process_buffered_input_packets(void)
 {
-	dispatch_run(DISPATCH_NONBLOCK, NULL, compat20 ? xxx_kex : NULL);
+	dispatch_run(DISPATCH_NONBLOCK, NULL, compat20 ? active_state->kex : NULL);
 }
 
 /*
@@ -851,7 +850,7 @@
 	for (;;) {
 		process_buffered_input_packets();
 
-		rekeying = (xxx_kex != NULL && !xxx_kex->done);
+		rekeying = (active_state->kex != NULL && !active_state->kex->done);
 
 		if (!rekeying && packet_not_very_much_data_to_write())
 			channel_output_poll();
@@ -874,8 +873,8 @@
 			channel_after_select(readset, writeset);
 			if (packet_need_rekeying()) {
 				debug("need rekeying");
-				xxx_kex->done = 0;
-				kex_send_kexinit(xxx_kex);
+				active_state->kex->done = 0;
+				kex_send_kexinit(active_state->kex);
 			}
 		}
 		process_input(readset);
diff --git a/sshconnect2.c b/sshconnect2.c
index aee49a4..ba34762 100644
--- a/sshconnect2.c
+++ b/sshconnect2.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: sshconnect2.c,v 1.216 2015/01/18 13:33:34 djm Exp $ */
+/* $OpenBSD: sshconnect2.c,v 1.217 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
  * Copyright (c) 2008 Damien Miller.  All rights reserved.
@@ -91,8 +91,6 @@
 char *xxx_host;
 struct sockaddr *xxx_hostaddr;
 
-Kex *xxx_kex = NULL;
-
 static int
 verify_host_key_callback(Key *hostkey)
 {
@@ -207,6 +205,7 @@
 
 	/* start key exchange */
 	kex = kex_setup(myproposal);
+	active_state->kex = kex;
 #ifdef WITH_OPENSSL
 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
 	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
@@ -219,8 +218,6 @@
 	kex->server_version_string=server_version_string;
 	kex->verify_host_key=&verify_host_key_callback;
 
-	xxx_kex = kex;
-
 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
 
 	if (options.use_roaming && !kex->roaming) {
diff --git a/sshd.c b/sshd.c
index a4611e4..e453039 100644
--- a/sshd.c
+++ b/sshd.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: sshd.c,v 1.433 2015/01/17 18:53:34 djm Exp $ */
+/* $OpenBSD: sshd.c,v 1.434 2015/01/19 19:52:16 markus Exp $ */
 /*
  * Author: Tatu Ylonen <ylo@cs.hut.fi>
  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -188,9 +188,6 @@
 char *client_version_string = NULL;
 char *server_version_string = NULL;
 
-/* for rekeying XXX fixme */
-Kex *xxx_kex;
-
 /* Daemon's agent connection */
 int auth_sock = -1;
 int have_agent = 0;
@@ -663,7 +660,7 @@
 	/* Set up unprivileged child process to deal with network data */
 	pmonitor = monitor_init();
 	/* Store a pointer to the kex for later rekeying */
-	pmonitor->m_pkex = &xxx_kex;
+	pmonitor->m_pkex = &active_state->kex;
 
 	if (use_privsep == PRIVSEP_ON)
 		box = ssh_sandbox_init(pmonitor);
@@ -2192,8 +2189,7 @@
 	do_authenticated(authctxt);
 
 	/* The connection has been terminated. */
-	packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
-	packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
+	packet_get_bytes(&ibytes, &obytes);
 	verbose("Transferred: sent %llu, received %llu bytes",
 	    (unsigned long long)obytes, (unsigned long long)ibytes);
 
@@ -2505,6 +2501,7 @@
 
 	/* start key exchange */
 	kex = kex_setup(myproposal);
+	active_state->kex = kex;
 #ifdef WITH_OPENSSL
 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
 	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
@@ -2521,8 +2518,6 @@
 	kex->host_key_index=&get_hostkey_index;
 	kex->sign = sshd_hostkey_sign;
 
-	xxx_kex = kex;
-
 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
 
 	session_id2 = kex->session_id;