xref: /openssh-portable/packet.c (revision e3599508)
1 /* $OpenBSD: packet.c,v 1.292 2020/06/24 15:10:38 markus Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This file contains code implementing the packet protocol and communication
7  * with the other side.  This same code is used both on client and server side.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  *
16  * SSH2 packet format added by Markus Friedl.
17  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 #include "includes.h"
41 
42 #include <sys/types.h>
43 #include "openbsd-compat/sys-queue.h"
44 #include <sys/socket.h>
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
47 #endif
48 
49 #include <netinet/in.h>
50 #include <netinet/ip.h>
51 #include <arpa/inet.h>
52 
53 #include <errno.h>
54 #include <netdb.h>
55 #include <stdarg.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 #include <limits.h>
61 #ifdef HAVE_POLL_H
62 #include <poll.h>
63 #endif
64 #include <signal.h>
65 #include <time.h>
66 
67 /*
68  * Explicitly include OpenSSL before zlib as some versions of OpenSSL have
69  * "free_func" in their headers, which zlib typedefs.
70  */
71 #ifdef WITH_OPENSSL
72 # include <openssl/bn.h>
73 # include <openssl/evp.h>
74 # ifdef OPENSSL_HAS_ECC
75 #  include <openssl/ec.h>
76 # endif
77 #endif
78 
79 #ifdef WITH_ZLIB
80 #include <zlib.h>
81 #endif
82 
83 #include "xmalloc.h"
84 #include "compat.h"
85 #include "ssh2.h"
86 #include "cipher.h"
87 #include "sshkey.h"
88 #include "kex.h"
89 #include "digest.h"
90 #include "mac.h"
91 #include "log.h"
92 #include "canohost.h"
93 #include "misc.h"
94 #include "channels.h"
95 #include "ssh.h"
96 #include "packet.h"
97 #include "ssherr.h"
98 #include "sshbuf.h"
99 
100 #ifdef PACKET_DEBUG
101 #define DBG(x) x
102 #else
103 #define DBG(x)
104 #endif
105 
106 #define PACKET_MAX_SIZE (256 * 1024)
107 
108 struct packet_state {
109 	u_int32_t seqnr;
110 	u_int32_t packets;
111 	u_int64_t blocks;
112 	u_int64_t bytes;
113 };
114 
115 struct packet {
116 	TAILQ_ENTRY(packet) next;
117 	u_char type;
118 	struct sshbuf *payload;
119 };
120 
121 struct session_state {
122 	/*
123 	 * This variable contains the file descriptors used for
124 	 * communicating with the other side.  connection_in is used for
125 	 * reading; connection_out for writing.  These can be the same
126 	 * descriptor, in which case it is assumed to be a socket.
127 	 */
128 	int connection_in;
129 	int connection_out;
130 
131 	/* Protocol flags for the remote side. */
132 	u_int remote_protocol_flags;
133 
134 	/* Encryption context for receiving data.  Only used for decryption. */
135 	struct sshcipher_ctx *receive_context;
136 
137 	/* Encryption context for sending data.  Only used for encryption. */
138 	struct sshcipher_ctx *send_context;
139 
140 	/* Buffer for raw input data from the socket. */
141 	struct sshbuf *input;
142 
143 	/* Buffer for raw output data going to the socket. */
144 	struct sshbuf *output;
145 
146 	/* Buffer for the partial outgoing packet being constructed. */
147 	struct sshbuf *outgoing_packet;
148 
149 	/* Buffer for the incoming packet currently being processed. */
150 	struct sshbuf *incoming_packet;
151 
152 	/* Scratch buffer for packet compression/decompression. */
153 	struct sshbuf *compression_buffer;
154 
155 #ifdef WITH_ZLIB
156 	/* Incoming/outgoing compression dictionaries */
157 	z_stream compression_in_stream;
158 	z_stream compression_out_stream;
159 #endif
160 	int compression_in_started;
161 	int compression_out_started;
162 	int compression_in_failures;
163 	int compression_out_failures;
164 
165 	/* default maximum packet size */
166 	u_int max_packet_size;
167 
168 	/* Flag indicating whether this module has been initialized. */
169 	int initialized;
170 
171 	/* Set to true if the connection is interactive. */
172 	int interactive_mode;
173 
174 	/* Set to true if we are the server side. */
175 	int server_side;
176 
177 	/* Set to true if we are authenticated. */
178 	int after_authentication;
179 
180 	int keep_alive_timeouts;
181 
182 	/* The maximum time that we will wait to send or receive a packet */
183 	int packet_timeout_ms;
184 
185 	/* Session key information for Encryption and MAC */
186 	struct newkeys *newkeys[MODE_MAX];
187 	struct packet_state p_read, p_send;
188 
189 	/* Volume-based rekeying */
190 	u_int64_t max_blocks_in, max_blocks_out, rekey_limit;
191 
192 	/* Time-based rekeying */
193 	u_int32_t rekey_interval;	/* how often in seconds */
194 	time_t rekey_time;	/* time of last rekeying */
195 
196 	/* roundup current message to extra_pad bytes */
197 	u_char extra_pad;
198 
199 	/* XXX discard incoming data after MAC error */
200 	u_int packet_discard;
201 	size_t packet_discard_mac_already;
202 	struct sshmac *packet_discard_mac;
203 
204 	/* Used in packet_read_poll2() */
205 	u_int packlen;
206 
207 	/* Used in packet_send2 */
208 	int rekeying;
209 
210 	/* Used in ssh_packet_send_mux() */
211 	int mux;
212 
213 	/* Used in packet_set_interactive */
214 	int set_interactive_called;
215 
216 	/* Used in packet_set_maxsize */
217 	int set_maxsize_called;
218 
219 	/* One-off warning about weak ciphers */
220 	int cipher_warning_done;
221 
222 	/* Hook for fuzzing inbound packets */
223 	ssh_packet_hook_fn *hook_in;
224 	void *hook_in_ctx;
225 
226 	TAILQ_HEAD(, packet) outgoing;
227 };
228 
229 struct ssh *
230 ssh_alloc_session_state(void)
231 {
232 	struct ssh *ssh = NULL;
233 	struct session_state *state = NULL;
234 
235 	if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
236 	    (state = calloc(1, sizeof(*state))) == NULL ||
237 	    (ssh->kex = kex_new()) == NULL ||
238 	    (state->input = sshbuf_new()) == NULL ||
239 	    (state->output = sshbuf_new()) == NULL ||
240 	    (state->outgoing_packet = sshbuf_new()) == NULL ||
241 	    (state->incoming_packet = sshbuf_new()) == NULL)
242 		goto fail;
243 	TAILQ_INIT(&state->outgoing);
244 	TAILQ_INIT(&ssh->private_keys);
245 	TAILQ_INIT(&ssh->public_keys);
246 	state->connection_in = -1;
247 	state->connection_out = -1;
248 	state->max_packet_size = 32768;
249 	state->packet_timeout_ms = -1;
250 	state->p_send.packets = state->p_read.packets = 0;
251 	state->initialized = 1;
252 	/*
253 	 * ssh_packet_send2() needs to queue packets until
254 	 * we've done the initial key exchange.
255 	 */
256 	state->rekeying = 1;
257 	ssh->state = state;
258 	return ssh;
259  fail:
260 	if (ssh) {
261 		kex_free(ssh->kex);
262 		free(ssh);
263 	}
264 	if (state) {
265 		sshbuf_free(state->input);
266 		sshbuf_free(state->output);
267 		sshbuf_free(state->incoming_packet);
268 		sshbuf_free(state->outgoing_packet);
269 		free(state);
270 	}
271 	return NULL;
272 }
273 
274 void
275 ssh_packet_set_input_hook(struct ssh *ssh, ssh_packet_hook_fn *hook, void *ctx)
276 {
277 	ssh->state->hook_in = hook;
278 	ssh->state->hook_in_ctx = ctx;
279 }
280 
281 /* Returns nonzero if rekeying is in progress */
282 int
283 ssh_packet_is_rekeying(struct ssh *ssh)
284 {
285 	return ssh->state->rekeying ||
286 	    (ssh->kex != NULL && ssh->kex->done == 0);
287 }
288 
289 /*
290  * Sets the descriptors used for communication.
291  */
292 struct ssh *
293 ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
294 {
295 	struct session_state *state;
296 	const struct sshcipher *none = cipher_by_name("none");
297 	int r;
298 
299 	if (none == NULL) {
300 		error("%s: cannot load cipher 'none'", __func__);
301 		return NULL;
302 	}
303 	if (ssh == NULL)
304 		ssh = ssh_alloc_session_state();
305 	if (ssh == NULL) {
306 		error("%s: could not allocate state", __func__);
307 		return NULL;
308 	}
309 	state = ssh->state;
310 	state->connection_in = fd_in;
311 	state->connection_out = fd_out;
312 	if ((r = cipher_init(&state->send_context, none,
313 	    (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
314 	    (r = cipher_init(&state->receive_context, none,
315 	    (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
316 		error("%s: cipher_init failed: %s", __func__, ssh_err(r));
317 		free(ssh); /* XXX need ssh_free_session_state? */
318 		return NULL;
319 	}
320 	state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
321 	/*
322 	 * Cache the IP address of the remote connection for use in error
323 	 * messages that might be generated after the connection has closed.
324 	 */
325 	(void)ssh_remote_ipaddr(ssh);
326 	return ssh;
327 }
328 
329 void
330 ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
331 {
332 	struct session_state *state = ssh->state;
333 
334 	if (timeout <= 0 || count <= 0) {
335 		state->packet_timeout_ms = -1;
336 		return;
337 	}
338 	if ((INT_MAX / 1000) / count < timeout)
339 		state->packet_timeout_ms = INT_MAX;
340 	else
341 		state->packet_timeout_ms = timeout * count * 1000;
342 }
343 
344 void
345 ssh_packet_set_mux(struct ssh *ssh)
346 {
347 	ssh->state->mux = 1;
348 	ssh->state->rekeying = 0;
349 	kex_free(ssh->kex);
350 	ssh->kex = NULL;
351 }
352 
353 int
354 ssh_packet_get_mux(struct ssh *ssh)
355 {
356 	return ssh->state->mux;
357 }
358 
359 int
360 ssh_packet_set_log_preamble(struct ssh *ssh, const char *fmt, ...)
361 {
362 	va_list args;
363 	int r;
364 
365 	free(ssh->log_preamble);
366 	if (fmt == NULL)
367 		ssh->log_preamble = NULL;
368 	else {
369 		va_start(args, fmt);
370 		r = vasprintf(&ssh->log_preamble, fmt, args);
371 		va_end(args);
372 		if (r < 0 || ssh->log_preamble == NULL)
373 			return SSH_ERR_ALLOC_FAIL;
374 	}
375 	return 0;
376 }
377 
378 int
379 ssh_packet_stop_discard(struct ssh *ssh)
380 {
381 	struct session_state *state = ssh->state;
382 	int r;
383 
384 	if (state->packet_discard_mac) {
385 		char buf[1024];
386 		size_t dlen = PACKET_MAX_SIZE;
387 
388 		if (dlen > state->packet_discard_mac_already)
389 			dlen -= state->packet_discard_mac_already;
390 		memset(buf, 'a', sizeof(buf));
391 		while (sshbuf_len(state->incoming_packet) < dlen)
392 			if ((r = sshbuf_put(state->incoming_packet, buf,
393 			    sizeof(buf))) != 0)
394 				return r;
395 		(void) mac_compute(state->packet_discard_mac,
396 		    state->p_read.seqnr,
397 		    sshbuf_ptr(state->incoming_packet), dlen,
398 		    NULL, 0);
399 	}
400 	logit("Finished discarding for %.200s port %d",
401 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
402 	return SSH_ERR_MAC_INVALID;
403 }
404 
405 static int
406 ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
407     struct sshmac *mac, size_t mac_already, u_int discard)
408 {
409 	struct session_state *state = ssh->state;
410 	int r;
411 
412 	if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
413 		if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
414 			return r;
415 		return SSH_ERR_MAC_INVALID;
416 	}
417 	/*
418 	 * Record number of bytes over which the mac has already
419 	 * been computed in order to minimize timing attacks.
420 	 */
421 	if (mac && mac->enabled) {
422 		state->packet_discard_mac = mac;
423 		state->packet_discard_mac_already = mac_already;
424 	}
425 	if (sshbuf_len(state->input) >= discard)
426 		return ssh_packet_stop_discard(ssh);
427 	state->packet_discard = discard - sshbuf_len(state->input);
428 	return 0;
429 }
430 
431 /* Returns 1 if remote host is connected via socket, 0 if not. */
432 
433 int
434 ssh_packet_connection_is_on_socket(struct ssh *ssh)
435 {
436 	struct session_state *state;
437 	struct sockaddr_storage from, to;
438 	socklen_t fromlen, tolen;
439 
440 	if (ssh == NULL || ssh->state == NULL)
441 		return 0;
442 
443 	state = ssh->state;
444 	if (state->connection_in == -1 || state->connection_out == -1)
445 		return 0;
446 	/* filedescriptors in and out are the same, so it's a socket */
447 	if (state->connection_in == state->connection_out)
448 		return 1;
449 	fromlen = sizeof(from);
450 	memset(&from, 0, sizeof(from));
451 	if (getpeername(state->connection_in, (struct sockaddr *)&from,
452 	    &fromlen) == -1)
453 		return 0;
454 	tolen = sizeof(to);
455 	memset(&to, 0, sizeof(to));
456 	if (getpeername(state->connection_out, (struct sockaddr *)&to,
457 	    &tolen) == -1)
458 		return 0;
459 	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
460 		return 0;
461 	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
462 		return 0;
463 	return 1;
464 }
465 
466 void
467 ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
468 {
469 	if (ibytes)
470 		*ibytes = ssh->state->p_read.bytes;
471 	if (obytes)
472 		*obytes = ssh->state->p_send.bytes;
473 }
474 
475 int
476 ssh_packet_connection_af(struct ssh *ssh)
477 {
478 	struct sockaddr_storage to;
479 	socklen_t tolen = sizeof(to);
480 
481 	memset(&to, 0, sizeof(to));
482 	if (getsockname(ssh->state->connection_out, (struct sockaddr *)&to,
483 	    &tolen) == -1)
484 		return 0;
485 #ifdef IPV4_IN_IPV6
486 	if (to.ss_family == AF_INET6 &&
487 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
488 		return AF_INET;
489 #endif
490 	return to.ss_family;
491 }
492 
493 /* Sets the connection into non-blocking mode. */
494 
495 void
496 ssh_packet_set_nonblocking(struct ssh *ssh)
497 {
498 	/* Set the socket into non-blocking mode. */
499 	set_nonblock(ssh->state->connection_in);
500 
501 	if (ssh->state->connection_out != ssh->state->connection_in)
502 		set_nonblock(ssh->state->connection_out);
503 }
504 
505 /* Returns the socket used for reading. */
506 
507 int
508 ssh_packet_get_connection_in(struct ssh *ssh)
509 {
510 	return ssh->state->connection_in;
511 }
512 
513 /* Returns the descriptor used for writing. */
514 
515 int
516 ssh_packet_get_connection_out(struct ssh *ssh)
517 {
518 	return ssh->state->connection_out;
519 }
520 
521 /*
522  * Returns the IP-address of the remote host as a string.  The returned
523  * string must not be freed.
524  */
525 
526 const char *
527 ssh_remote_ipaddr(struct ssh *ssh)
528 {
529 	int sock;
530 
531 	/* Check whether we have cached the ipaddr. */
532 	if (ssh->remote_ipaddr == NULL) {
533 		if (ssh_packet_connection_is_on_socket(ssh)) {
534 			sock = ssh->state->connection_in;
535 			ssh->remote_ipaddr = get_peer_ipaddr(sock);
536 			ssh->remote_port = get_peer_port(sock);
537 			ssh->local_ipaddr = get_local_ipaddr(sock);
538 			ssh->local_port = get_local_port(sock);
539 		} else {
540 			ssh->remote_ipaddr = xstrdup("UNKNOWN");
541 			ssh->remote_port = 65535;
542 			ssh->local_ipaddr = xstrdup("UNKNOWN");
543 			ssh->local_port = 65535;
544 		}
545 	}
546 	return ssh->remote_ipaddr;
547 }
548 
549 /* Returns the port number of the remote host. */
550 
551 int
552 ssh_remote_port(struct ssh *ssh)
553 {
554 	(void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
555 	return ssh->remote_port;
556 }
557 
558 /*
559  * Returns the IP-address of the local host as a string.  The returned
560  * string must not be freed.
561  */
562 
563 const char *
564 ssh_local_ipaddr(struct ssh *ssh)
565 {
566 	(void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
567 	return ssh->local_ipaddr;
568 }
569 
570 /* Returns the port number of the local host. */
571 
572 int
573 ssh_local_port(struct ssh *ssh)
574 {
575 	(void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
576 	return ssh->local_port;
577 }
578 
579 /* Returns the routing domain of the input socket, or NULL if unavailable */
580 const char *
581 ssh_packet_rdomain_in(struct ssh *ssh)
582 {
583 	if (ssh->rdomain_in != NULL)
584 		return ssh->rdomain_in;
585 	if (!ssh_packet_connection_is_on_socket(ssh))
586 		return NULL;
587 	ssh->rdomain_in = get_rdomain(ssh->state->connection_in);
588 	return ssh->rdomain_in;
589 }
590 
591 /* Closes the connection and clears and frees internal data structures. */
592 
593 static void
594 ssh_packet_close_internal(struct ssh *ssh, int do_close)
595 {
596 	struct session_state *state = ssh->state;
597 	u_int mode;
598 
599 	if (!state->initialized)
600 		return;
601 	state->initialized = 0;
602 	if (do_close) {
603 		if (state->connection_in == state->connection_out) {
604 			close(state->connection_out);
605 		} else {
606 			close(state->connection_in);
607 			close(state->connection_out);
608 		}
609 	}
610 	sshbuf_free(state->input);
611 	sshbuf_free(state->output);
612 	sshbuf_free(state->outgoing_packet);
613 	sshbuf_free(state->incoming_packet);
614 	for (mode = 0; mode < MODE_MAX; mode++) {
615 		kex_free_newkeys(state->newkeys[mode]);	/* current keys */
616 		state->newkeys[mode] = NULL;
617 		ssh_clear_newkeys(ssh, mode);		/* next keys */
618 	}
619 #ifdef WITH_ZLIB
620 	/* compression state is in shared mem, so we can only release it once */
621 	if (do_close && state->compression_buffer) {
622 		sshbuf_free(state->compression_buffer);
623 		if (state->compression_out_started) {
624 			z_streamp stream = &state->compression_out_stream;
625 			debug("compress outgoing: "
626 			    "raw data %llu, compressed %llu, factor %.2f",
627 				(unsigned long long)stream->total_in,
628 				(unsigned long long)stream->total_out,
629 				stream->total_in == 0 ? 0.0 :
630 				(double) stream->total_out / stream->total_in);
631 			if (state->compression_out_failures == 0)
632 				deflateEnd(stream);
633 		}
634 		if (state->compression_in_started) {
635 			z_streamp stream = &state->compression_in_stream;
636 			debug("compress incoming: "
637 			    "raw data %llu, compressed %llu, factor %.2f",
638 			    (unsigned long long)stream->total_out,
639 			    (unsigned long long)stream->total_in,
640 			    stream->total_out == 0 ? 0.0 :
641 			    (double) stream->total_in / stream->total_out);
642 			if (state->compression_in_failures == 0)
643 				inflateEnd(stream);
644 		}
645 	}
646 #endif	/* WITH_ZLIB */
647 	cipher_free(state->send_context);
648 	cipher_free(state->receive_context);
649 	state->send_context = state->receive_context = NULL;
650 	if (do_close) {
651 		free(ssh->local_ipaddr);
652 		ssh->local_ipaddr = NULL;
653 		free(ssh->remote_ipaddr);
654 		ssh->remote_ipaddr = NULL;
655 		free(ssh->state);
656 		ssh->state = NULL;
657 	}
658 }
659 
660 void
661 ssh_packet_close(struct ssh *ssh)
662 {
663 	ssh_packet_close_internal(ssh, 1);
664 }
665 
666 void
667 ssh_packet_clear_keys(struct ssh *ssh)
668 {
669 	ssh_packet_close_internal(ssh, 0);
670 }
671 
672 /* Sets remote side protocol flags. */
673 
674 void
675 ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
676 {
677 	ssh->state->remote_protocol_flags = protocol_flags;
678 }
679 
680 /* Returns the remote protocol flags set earlier by the above function. */
681 
682 u_int
683 ssh_packet_get_protocol_flags(struct ssh *ssh)
684 {
685 	return ssh->state->remote_protocol_flags;
686 }
687 
688 /*
689  * Starts packet compression from the next packet on in both directions.
690  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
691  */
692 
693 static int
694 ssh_packet_init_compression(struct ssh *ssh)
695 {
696 	if (!ssh->state->compression_buffer &&
697 	   ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
698 		return SSH_ERR_ALLOC_FAIL;
699 	return 0;
700 }
701 
702 #ifdef WITH_ZLIB
703 static int
704 start_compression_out(struct ssh *ssh, int level)
705 {
706 	if (level < 1 || level > 9)
707 		return SSH_ERR_INVALID_ARGUMENT;
708 	debug("Enabling compression at level %d.", level);
709 	if (ssh->state->compression_out_started == 1)
710 		deflateEnd(&ssh->state->compression_out_stream);
711 	switch (deflateInit(&ssh->state->compression_out_stream, level)) {
712 	case Z_OK:
713 		ssh->state->compression_out_started = 1;
714 		break;
715 	case Z_MEM_ERROR:
716 		return SSH_ERR_ALLOC_FAIL;
717 	default:
718 		return SSH_ERR_INTERNAL_ERROR;
719 	}
720 	return 0;
721 }
722 
723 static int
724 start_compression_in(struct ssh *ssh)
725 {
726 	if (ssh->state->compression_in_started == 1)
727 		inflateEnd(&ssh->state->compression_in_stream);
728 	switch (inflateInit(&ssh->state->compression_in_stream)) {
729 	case Z_OK:
730 		ssh->state->compression_in_started = 1;
731 		break;
732 	case Z_MEM_ERROR:
733 		return SSH_ERR_ALLOC_FAIL;
734 	default:
735 		return SSH_ERR_INTERNAL_ERROR;
736 	}
737 	return 0;
738 }
739 
740 /* XXX remove need for separate compression buffer */
741 static int
742 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
743 {
744 	u_char buf[4096];
745 	int r, status;
746 
747 	if (ssh->state->compression_out_started != 1)
748 		return SSH_ERR_INTERNAL_ERROR;
749 
750 	/* This case is not handled below. */
751 	if (sshbuf_len(in) == 0)
752 		return 0;
753 
754 	/* Input is the contents of the input buffer. */
755 	if ((ssh->state->compression_out_stream.next_in =
756 	    sshbuf_mutable_ptr(in)) == NULL)
757 		return SSH_ERR_INTERNAL_ERROR;
758 	ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
759 
760 	/* Loop compressing until deflate() returns with avail_out != 0. */
761 	do {
762 		/* Set up fixed-size output buffer. */
763 		ssh->state->compression_out_stream.next_out = buf;
764 		ssh->state->compression_out_stream.avail_out = sizeof(buf);
765 
766 		/* Compress as much data into the buffer as possible. */
767 		status = deflate(&ssh->state->compression_out_stream,
768 		    Z_PARTIAL_FLUSH);
769 		switch (status) {
770 		case Z_MEM_ERROR:
771 			return SSH_ERR_ALLOC_FAIL;
772 		case Z_OK:
773 			/* Append compressed data to output_buffer. */
774 			if ((r = sshbuf_put(out, buf, sizeof(buf) -
775 			    ssh->state->compression_out_stream.avail_out)) != 0)
776 				return r;
777 			break;
778 		case Z_STREAM_ERROR:
779 		default:
780 			ssh->state->compression_out_failures++;
781 			return SSH_ERR_INVALID_FORMAT;
782 		}
783 	} while (ssh->state->compression_out_stream.avail_out == 0);
784 	return 0;
785 }
786 
787 static int
788 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
789 {
790 	u_char buf[4096];
791 	int r, status;
792 
793 	if (ssh->state->compression_in_started != 1)
794 		return SSH_ERR_INTERNAL_ERROR;
795 
796 	if ((ssh->state->compression_in_stream.next_in =
797 	    sshbuf_mutable_ptr(in)) == NULL)
798 		return SSH_ERR_INTERNAL_ERROR;
799 	ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
800 
801 	for (;;) {
802 		/* Set up fixed-size output buffer. */
803 		ssh->state->compression_in_stream.next_out = buf;
804 		ssh->state->compression_in_stream.avail_out = sizeof(buf);
805 
806 		status = inflate(&ssh->state->compression_in_stream,
807 		    Z_PARTIAL_FLUSH);
808 		switch (status) {
809 		case Z_OK:
810 			if ((r = sshbuf_put(out, buf, sizeof(buf) -
811 			    ssh->state->compression_in_stream.avail_out)) != 0)
812 				return r;
813 			break;
814 		case Z_BUF_ERROR:
815 			/*
816 			 * Comments in zlib.h say that we should keep calling
817 			 * inflate() until we get an error.  This appears to
818 			 * be the error that we get.
819 			 */
820 			return 0;
821 		case Z_DATA_ERROR:
822 			return SSH_ERR_INVALID_FORMAT;
823 		case Z_MEM_ERROR:
824 			return SSH_ERR_ALLOC_FAIL;
825 		case Z_STREAM_ERROR:
826 		default:
827 			ssh->state->compression_in_failures++;
828 			return SSH_ERR_INTERNAL_ERROR;
829 		}
830 	}
831 	/* NOTREACHED */
832 }
833 
834 #else	/* WITH_ZLIB */
835 
836 static int
837 start_compression_out(struct ssh *ssh, int level)
838 {
839 	return SSH_ERR_INTERNAL_ERROR;
840 }
841 
842 static int
843 start_compression_in(struct ssh *ssh)
844 {
845 	return SSH_ERR_INTERNAL_ERROR;
846 }
847 
848 static int
849 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
850 {
851 	return SSH_ERR_INTERNAL_ERROR;
852 }
853 
854 static int
855 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
856 {
857 	return SSH_ERR_INTERNAL_ERROR;
858 }
859 #endif	/* WITH_ZLIB */
860 
861 void
862 ssh_clear_newkeys(struct ssh *ssh, int mode)
863 {
864 	if (ssh->kex && ssh->kex->newkeys[mode]) {
865 		kex_free_newkeys(ssh->kex->newkeys[mode]);
866 		ssh->kex->newkeys[mode] = NULL;
867 	}
868 }
869 
870 int
871 ssh_set_newkeys(struct ssh *ssh, int mode)
872 {
873 	struct session_state *state = ssh->state;
874 	struct sshenc *enc;
875 	struct sshmac *mac;
876 	struct sshcomp *comp;
877 	struct sshcipher_ctx **ccp;
878 	struct packet_state *ps;
879 	u_int64_t *max_blocks;
880 	const char *wmsg;
881 	int r, crypt_type;
882 	const char *dir = mode == MODE_OUT ? "out" : "in";
883 
884 	debug2("set_newkeys: mode %d", mode);
885 
886 	if (mode == MODE_OUT) {
887 		ccp = &state->send_context;
888 		crypt_type = CIPHER_ENCRYPT;
889 		ps = &state->p_send;
890 		max_blocks = &state->max_blocks_out;
891 	} else {
892 		ccp = &state->receive_context;
893 		crypt_type = CIPHER_DECRYPT;
894 		ps = &state->p_read;
895 		max_blocks = &state->max_blocks_in;
896 	}
897 	if (state->newkeys[mode] != NULL) {
898 		debug("%s: rekeying %s, input %llu bytes %llu blocks, "
899 		   "output %llu bytes %llu blocks", __func__, dir,
900 		   (unsigned long long)state->p_read.bytes,
901 		   (unsigned long long)state->p_read.blocks,
902 		   (unsigned long long)state->p_send.bytes,
903 		   (unsigned long long)state->p_send.blocks);
904 		kex_free_newkeys(state->newkeys[mode]);
905 		state->newkeys[mode] = NULL;
906 	}
907 	/* note that both bytes and the seqnr are not reset */
908 	ps->packets = ps->blocks = 0;
909 	/* move newkeys from kex to state */
910 	if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
911 		return SSH_ERR_INTERNAL_ERROR;
912 	ssh->kex->newkeys[mode] = NULL;
913 	enc  = &state->newkeys[mode]->enc;
914 	mac  = &state->newkeys[mode]->mac;
915 	comp = &state->newkeys[mode]->comp;
916 	if (cipher_authlen(enc->cipher) == 0) {
917 		if ((r = mac_init(mac)) != 0)
918 			return r;
919 	}
920 	mac->enabled = 1;
921 	DBG(debug("%s: cipher_init_context: %s", __func__, dir));
922 	cipher_free(*ccp);
923 	*ccp = NULL;
924 	if ((r = cipher_init(ccp, enc->cipher, enc->key, enc->key_len,
925 	    enc->iv, enc->iv_len, crypt_type)) != 0)
926 		return r;
927 	if (!state->cipher_warning_done &&
928 	    (wmsg = cipher_warning_message(*ccp)) != NULL) {
929 		error("Warning: %s", wmsg);
930 		state->cipher_warning_done = 1;
931 	}
932 	/* Deleting the keys does not gain extra security */
933 	/* explicit_bzero(enc->iv,  enc->block_size);
934 	   explicit_bzero(enc->key, enc->key_len);
935 	   explicit_bzero(mac->key, mac->key_len); */
936 	if ((comp->type == COMP_ZLIB ||
937 	    (comp->type == COMP_DELAYED &&
938 	     state->after_authentication)) && comp->enabled == 0) {
939 		if ((r = ssh_packet_init_compression(ssh)) < 0)
940 			return r;
941 		if (mode == MODE_OUT) {
942 			if ((r = start_compression_out(ssh, 6)) != 0)
943 				return r;
944 		} else {
945 			if ((r = start_compression_in(ssh)) != 0)
946 				return r;
947 		}
948 		comp->enabled = 1;
949 	}
950 	/*
951 	 * The 2^(blocksize*2) limit is too expensive for 3DES,
952 	 * so enforce a 1GB limit for small blocksizes.
953 	 * See RFC4344 section 3.2.
954 	 */
955 	if (enc->block_size >= 16)
956 		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
957 	else
958 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
959 	if (state->rekey_limit)
960 		*max_blocks = MINIMUM(*max_blocks,
961 		    state->rekey_limit / enc->block_size);
962 	debug("rekey %s after %llu blocks", dir,
963 	    (unsigned long long)*max_blocks);
964 	return 0;
965 }
966 
967 #define MAX_PACKETS	(1U<<31)
968 static int
969 ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
970 {
971 	struct session_state *state = ssh->state;
972 	u_int32_t out_blocks;
973 
974 	/* XXX client can't cope with rekeying pre-auth */
975 	if (!state->after_authentication)
976 		return 0;
977 
978 	/* Haven't keyed yet or KEX in progress. */
979 	if (ssh_packet_is_rekeying(ssh))
980 		return 0;
981 
982 	/* Peer can't rekey */
983 	if (ssh->compat & SSH_BUG_NOREKEY)
984 		return 0;
985 
986 	/*
987 	 * Permit one packet in or out per rekey - this allows us to
988 	 * make progress when rekey limits are very small.
989 	 */
990 	if (state->p_send.packets == 0 && state->p_read.packets == 0)
991 		return 0;
992 
993 	/* Time-based rekeying */
994 	if (state->rekey_interval != 0 &&
995 	    (int64_t)state->rekey_time + state->rekey_interval <= monotime())
996 		return 1;
997 
998 	/*
999 	 * Always rekey when MAX_PACKETS sent in either direction
1000 	 * As per RFC4344 section 3.1 we do this after 2^31 packets.
1001 	 */
1002 	if (state->p_send.packets > MAX_PACKETS ||
1003 	    state->p_read.packets > MAX_PACKETS)
1004 		return 1;
1005 
1006 	/* Rekey after (cipher-specific) maximum blocks */
1007 	out_blocks = ROUNDUP(outbound_packet_len,
1008 	    state->newkeys[MODE_OUT]->enc.block_size);
1009 	return (state->max_blocks_out &&
1010 	    (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
1011 	    (state->max_blocks_in &&
1012 	    (state->p_read.blocks > state->max_blocks_in));
1013 }
1014 
1015 /*
1016  * Delayed compression for SSH2 is enabled after authentication:
1017  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1018  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1019  */
1020 static int
1021 ssh_packet_enable_delayed_compress(struct ssh *ssh)
1022 {
1023 	struct session_state *state = ssh->state;
1024 	struct sshcomp *comp = NULL;
1025 	int r, mode;
1026 
1027 	/*
1028 	 * Remember that we are past the authentication step, so rekeying
1029 	 * with COMP_DELAYED will turn on compression immediately.
1030 	 */
1031 	state->after_authentication = 1;
1032 	for (mode = 0; mode < MODE_MAX; mode++) {
1033 		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1034 		if (state->newkeys[mode] == NULL)
1035 			continue;
1036 		comp = &state->newkeys[mode]->comp;
1037 		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1038 			if ((r = ssh_packet_init_compression(ssh)) != 0)
1039 				return r;
1040 			if (mode == MODE_OUT) {
1041 				if ((r = start_compression_out(ssh, 6)) != 0)
1042 					return r;
1043 			} else {
1044 				if ((r = start_compression_in(ssh)) != 0)
1045 					return r;
1046 			}
1047 			comp->enabled = 1;
1048 		}
1049 	}
1050 	return 0;
1051 }
1052 
1053 /* Used to mute debug logging for noisy packet types */
1054 int
1055 ssh_packet_log_type(u_char type)
1056 {
1057 	switch (type) {
1058 	case SSH2_MSG_CHANNEL_DATA:
1059 	case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1060 	case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1061 		return 0;
1062 	default:
1063 		return 1;
1064 	}
1065 }
1066 
1067 /*
1068  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1069  */
1070 int
1071 ssh_packet_send2_wrapped(struct ssh *ssh)
1072 {
1073 	struct session_state *state = ssh->state;
1074 	u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1075 	u_char tmp, padlen, pad = 0;
1076 	u_int authlen = 0, aadlen = 0;
1077 	u_int len;
1078 	struct sshenc *enc   = NULL;
1079 	struct sshmac *mac   = NULL;
1080 	struct sshcomp *comp = NULL;
1081 	int r, block_size;
1082 
1083 	if (state->newkeys[MODE_OUT] != NULL) {
1084 		enc  = &state->newkeys[MODE_OUT]->enc;
1085 		mac  = &state->newkeys[MODE_OUT]->mac;
1086 		comp = &state->newkeys[MODE_OUT]->comp;
1087 		/* disable mac for authenticated encryption */
1088 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
1089 			mac = NULL;
1090 	}
1091 	block_size = enc ? enc->block_size : 8;
1092 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1093 
1094 	type = (sshbuf_ptr(state->outgoing_packet))[5];
1095 	if (ssh_packet_log_type(type))
1096 		debug3("send packet: type %u", type);
1097 #ifdef PACKET_DEBUG
1098 	fprintf(stderr, "plain:     ");
1099 	sshbuf_dump(state->outgoing_packet, stderr);
1100 #endif
1101 
1102 	if (comp && comp->enabled) {
1103 		len = sshbuf_len(state->outgoing_packet);
1104 		/* skip header, compress only payload */
1105 		if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1106 			goto out;
1107 		sshbuf_reset(state->compression_buffer);
1108 		if ((r = compress_buffer(ssh, state->outgoing_packet,
1109 		    state->compression_buffer)) != 0)
1110 			goto out;
1111 		sshbuf_reset(state->outgoing_packet);
1112 		if ((r = sshbuf_put(state->outgoing_packet,
1113 		    "\0\0\0\0\0", 5)) != 0 ||
1114 		    (r = sshbuf_putb(state->outgoing_packet,
1115 		    state->compression_buffer)) != 0)
1116 			goto out;
1117 		DBG(debug("compression: raw %d compressed %zd", len,
1118 		    sshbuf_len(state->outgoing_packet)));
1119 	}
1120 
1121 	/* sizeof (packet_len + pad_len + payload) */
1122 	len = sshbuf_len(state->outgoing_packet);
1123 
1124 	/*
1125 	 * calc size of padding, alloc space, get random data,
1126 	 * minimum padding is 4 bytes
1127 	 */
1128 	len -= aadlen; /* packet length is not encrypted for EtM modes */
1129 	padlen = block_size - (len % block_size);
1130 	if (padlen < 4)
1131 		padlen += block_size;
1132 	if (state->extra_pad) {
1133 		tmp = state->extra_pad;
1134 		state->extra_pad =
1135 		    ROUNDUP(state->extra_pad, block_size);
1136 		/* check if roundup overflowed */
1137 		if (state->extra_pad < tmp)
1138 			return SSH_ERR_INVALID_ARGUMENT;
1139 		tmp = (len + padlen) % state->extra_pad;
1140 		/* Check whether pad calculation below will underflow */
1141 		if (tmp > state->extra_pad)
1142 			return SSH_ERR_INVALID_ARGUMENT;
1143 		pad = state->extra_pad - tmp;
1144 		DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
1145 		    __func__, pad, len, padlen, state->extra_pad));
1146 		tmp = padlen;
1147 		padlen += pad;
1148 		/* Check whether padlen calculation overflowed */
1149 		if (padlen < tmp)
1150 			return SSH_ERR_INVALID_ARGUMENT; /* overflow */
1151 		state->extra_pad = 0;
1152 	}
1153 	if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1154 		goto out;
1155 	if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
1156 		/* random padding */
1157 		arc4random_buf(cp, padlen);
1158 	} else {
1159 		/* clear padding */
1160 		explicit_bzero(cp, padlen);
1161 	}
1162 	/* sizeof (packet_len + pad_len + payload + padding) */
1163 	len = sshbuf_len(state->outgoing_packet);
1164 	cp = sshbuf_mutable_ptr(state->outgoing_packet);
1165 	if (cp == NULL) {
1166 		r = SSH_ERR_INTERNAL_ERROR;
1167 		goto out;
1168 	}
1169 	/* packet_length includes payload, padding and padding length field */
1170 	POKE_U32(cp, len - 4);
1171 	cp[4] = padlen;
1172 	DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1173 	    len, padlen, aadlen));
1174 
1175 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
1176 	if (mac && mac->enabled && !mac->etm) {
1177 		if ((r = mac_compute(mac, state->p_send.seqnr,
1178 		    sshbuf_ptr(state->outgoing_packet), len,
1179 		    macbuf, sizeof(macbuf))) != 0)
1180 			goto out;
1181 		DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1182 	}
1183 	/* encrypt packet and append to output buffer. */
1184 	if ((r = sshbuf_reserve(state->output,
1185 	    sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1186 		goto out;
1187 	if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
1188 	    sshbuf_ptr(state->outgoing_packet),
1189 	    len - aadlen, aadlen, authlen)) != 0)
1190 		goto out;
1191 	/* append unencrypted MAC */
1192 	if (mac && mac->enabled) {
1193 		if (mac->etm) {
1194 			/* EtM: compute mac over aadlen + cipher text */
1195 			if ((r = mac_compute(mac, state->p_send.seqnr,
1196 			    cp, len, macbuf, sizeof(macbuf))) != 0)
1197 				goto out;
1198 			DBG(debug("done calc MAC(EtM) out #%d",
1199 			    state->p_send.seqnr));
1200 		}
1201 		if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1202 			goto out;
1203 	}
1204 #ifdef PACKET_DEBUG
1205 	fprintf(stderr, "encrypted: ");
1206 	sshbuf_dump(state->output, stderr);
1207 #endif
1208 	/* increment sequence number for outgoing packets */
1209 	if (++state->p_send.seqnr == 0)
1210 		logit("outgoing seqnr wraps around");
1211 	if (++state->p_send.packets == 0)
1212 		if (!(ssh->compat & SSH_BUG_NOREKEY))
1213 			return SSH_ERR_NEED_REKEY;
1214 	state->p_send.blocks += len / block_size;
1215 	state->p_send.bytes += len;
1216 	sshbuf_reset(state->outgoing_packet);
1217 
1218 	if (type == SSH2_MSG_NEWKEYS)
1219 		r = ssh_set_newkeys(ssh, MODE_OUT);
1220 	else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1221 		r = ssh_packet_enable_delayed_compress(ssh);
1222 	else
1223 		r = 0;
1224  out:
1225 	return r;
1226 }
1227 
1228 /* returns non-zero if the specified packet type is usec by KEX */
1229 static int
1230 ssh_packet_type_is_kex(u_char type)
1231 {
1232 	return
1233 	    type >= SSH2_MSG_TRANSPORT_MIN &&
1234 	    type <= SSH2_MSG_TRANSPORT_MAX &&
1235 	    type != SSH2_MSG_SERVICE_REQUEST &&
1236 	    type != SSH2_MSG_SERVICE_ACCEPT &&
1237 	    type != SSH2_MSG_EXT_INFO;
1238 }
1239 
1240 int
1241 ssh_packet_send2(struct ssh *ssh)
1242 {
1243 	struct session_state *state = ssh->state;
1244 	struct packet *p;
1245 	u_char type;
1246 	int r, need_rekey;
1247 
1248 	if (sshbuf_len(state->outgoing_packet) < 6)
1249 		return SSH_ERR_INTERNAL_ERROR;
1250 	type = sshbuf_ptr(state->outgoing_packet)[5];
1251 	need_rekey = !ssh_packet_type_is_kex(type) &&
1252 	    ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1253 
1254 	/*
1255 	 * During rekeying we can only send key exchange messages.
1256 	 * Queue everything else.
1257 	 */
1258 	if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
1259 		if (need_rekey)
1260 			debug3("%s: rekex triggered", __func__);
1261 		debug("enqueue packet: %u", type);
1262 		p = calloc(1, sizeof(*p));
1263 		if (p == NULL)
1264 			return SSH_ERR_ALLOC_FAIL;
1265 		p->type = type;
1266 		p->payload = state->outgoing_packet;
1267 		TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1268 		state->outgoing_packet = sshbuf_new();
1269 		if (state->outgoing_packet == NULL)
1270 			return SSH_ERR_ALLOC_FAIL;
1271 		if (need_rekey) {
1272 			/*
1273 			 * This packet triggered a rekey, so send the
1274 			 * KEXINIT now.
1275 			 * NB. reenters this function via kex_start_rekex().
1276 			 */
1277 			return kex_start_rekex(ssh);
1278 		}
1279 		return 0;
1280 	}
1281 
1282 	/* rekeying starts with sending KEXINIT */
1283 	if (type == SSH2_MSG_KEXINIT)
1284 		state->rekeying = 1;
1285 
1286 	if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1287 		return r;
1288 
1289 	/* after a NEWKEYS message we can send the complete queue */
1290 	if (type == SSH2_MSG_NEWKEYS) {
1291 		state->rekeying = 0;
1292 		state->rekey_time = monotime();
1293 		while ((p = TAILQ_FIRST(&state->outgoing))) {
1294 			type = p->type;
1295 			/*
1296 			 * If this packet triggers a rekex, then skip the
1297 			 * remaining packets in the queue for now.
1298 			 * NB. re-enters this function via kex_start_rekex.
1299 			 */
1300 			if (ssh_packet_need_rekeying(ssh,
1301 			    sshbuf_len(p->payload))) {
1302 				debug3("%s: queued packet triggered rekex",
1303 				    __func__);
1304 				return kex_start_rekex(ssh);
1305 			}
1306 			debug("dequeue packet: %u", type);
1307 			sshbuf_free(state->outgoing_packet);
1308 			state->outgoing_packet = p->payload;
1309 			TAILQ_REMOVE(&state->outgoing, p, next);
1310 			memset(p, 0, sizeof(*p));
1311 			free(p);
1312 			if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1313 				return r;
1314 		}
1315 	}
1316 	return 0;
1317 }
1318 
1319 /*
1320  * Waits until a packet has been received, and returns its type.  Note that
1321  * no other data is processed until this returns, so this function should not
1322  * be used during the interactive session.
1323  */
1324 
1325 int
1326 ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1327 {
1328 	struct session_state *state = ssh->state;
1329 	int len, r, ms_remain;
1330 	fd_set *setp;
1331 	char buf[8192];
1332 	struct timeval timeout, start, *timeoutp = NULL;
1333 
1334 	DBG(debug("packet_read()"));
1335 
1336 	setp = calloc(howmany(state->connection_in + 1,
1337 	    NFDBITS), sizeof(fd_mask));
1338 	if (setp == NULL)
1339 		return SSH_ERR_ALLOC_FAIL;
1340 
1341 	/*
1342 	 * Since we are blocking, ensure that all written packets have
1343 	 * been sent.
1344 	 */
1345 	if ((r = ssh_packet_write_wait(ssh)) != 0)
1346 		goto out;
1347 
1348 	/* Stay in the loop until we have received a complete packet. */
1349 	for (;;) {
1350 		/* Try to read a packet from the buffer. */
1351 		r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
1352 		if (r != 0)
1353 			break;
1354 		/* If we got a packet, return it. */
1355 		if (*typep != SSH_MSG_NONE)
1356 			break;
1357 		/*
1358 		 * Otherwise, wait for some data to arrive, add it to the
1359 		 * buffer, and try again.
1360 		 */
1361 		memset(setp, 0, howmany(state->connection_in + 1,
1362 		    NFDBITS) * sizeof(fd_mask));
1363 		FD_SET(state->connection_in, setp);
1364 
1365 		if (state->packet_timeout_ms > 0) {
1366 			ms_remain = state->packet_timeout_ms;
1367 			timeoutp = &timeout;
1368 		}
1369 		/* Wait for some data to arrive. */
1370 		for (;;) {
1371 			if (state->packet_timeout_ms > 0) {
1372 				ms_to_timeval(&timeout, ms_remain);
1373 				monotime_tv(&start);
1374 			}
1375 			if ((r = select(state->connection_in + 1, setp,
1376 			    NULL, NULL, timeoutp)) >= 0)
1377 				break;
1378 			if (errno != EAGAIN && errno != EINTR &&
1379 			    errno != EWOULDBLOCK) {
1380 				r = SSH_ERR_SYSTEM_ERROR;
1381 				goto out;
1382 			}
1383 			if (state->packet_timeout_ms <= 0)
1384 				continue;
1385 			ms_subtract_diff(&start, &ms_remain);
1386 			if (ms_remain <= 0) {
1387 				r = 0;
1388 				break;
1389 			}
1390 		}
1391 		if (r == 0) {
1392 			r = SSH_ERR_CONN_TIMEOUT;
1393 			goto out;
1394 		}
1395 		/* Read data from the socket. */
1396 		len = read(state->connection_in, buf, sizeof(buf));
1397 		if (len == 0) {
1398 			r = SSH_ERR_CONN_CLOSED;
1399 			goto out;
1400 		}
1401 		if (len == -1) {
1402 			r = SSH_ERR_SYSTEM_ERROR;
1403 			goto out;
1404 		}
1405 
1406 		/* Append it to the buffer. */
1407 		if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1408 			goto out;
1409 	}
1410  out:
1411 	free(setp);
1412 	return r;
1413 }
1414 
1415 int
1416 ssh_packet_read(struct ssh *ssh)
1417 {
1418 	u_char type;
1419 	int r;
1420 
1421 	if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1422 		fatal("%s: %s", __func__, ssh_err(r));
1423 	return type;
1424 }
1425 
1426 /*
1427  * Waits until a packet has been received, verifies that its type matches
1428  * that given, and gives a fatal error and exits if there is a mismatch.
1429  */
1430 
1431 int
1432 ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
1433 {
1434 	int r;
1435 	u_char type;
1436 
1437 	if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1438 		return r;
1439 	if (type != expected_type) {
1440 		if ((r = sshpkt_disconnect(ssh,
1441 		    "Protocol error: expected packet type %d, got %d",
1442 		    expected_type, type)) != 0)
1443 			return r;
1444 		return SSH_ERR_PROTOCOL_ERROR;
1445 	}
1446 	return 0;
1447 }
1448 
1449 static int
1450 ssh_packet_read_poll2_mux(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1451 {
1452 	struct session_state *state = ssh->state;
1453 	const u_char *cp;
1454 	size_t need;
1455 	int r;
1456 
1457 	if (ssh->kex)
1458 		return SSH_ERR_INTERNAL_ERROR;
1459 	*typep = SSH_MSG_NONE;
1460 	cp = sshbuf_ptr(state->input);
1461 	if (state->packlen == 0) {
1462 		if (sshbuf_len(state->input) < 4 + 1)
1463 			return 0; /* packet is incomplete */
1464 		state->packlen = PEEK_U32(cp);
1465 		if (state->packlen < 4 + 1 ||
1466 		    state->packlen > PACKET_MAX_SIZE)
1467 			return SSH_ERR_MESSAGE_INCOMPLETE;
1468 	}
1469 	need = state->packlen + 4;
1470 	if (sshbuf_len(state->input) < need)
1471 		return 0; /* packet is incomplete */
1472 	sshbuf_reset(state->incoming_packet);
1473 	if ((r = sshbuf_put(state->incoming_packet, cp + 4,
1474 	    state->packlen)) != 0 ||
1475 	    (r = sshbuf_consume(state->input, need)) != 0 ||
1476 	    (r = sshbuf_get_u8(state->incoming_packet, NULL)) != 0 ||
1477 	    (r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1478 		return r;
1479 	if (ssh_packet_log_type(*typep))
1480 		debug3("%s: type %u", __func__, *typep);
1481 	/* sshbuf_dump(state->incoming_packet, stderr); */
1482 	/* reset for next packet */
1483 	state->packlen = 0;
1484 	return r;
1485 }
1486 
1487 int
1488 ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1489 {
1490 	struct session_state *state = ssh->state;
1491 	u_int padlen, need;
1492 	u_char *cp;
1493 	u_int maclen, aadlen = 0, authlen = 0, block_size;
1494 	struct sshenc *enc   = NULL;
1495 	struct sshmac *mac   = NULL;
1496 	struct sshcomp *comp = NULL;
1497 	int r;
1498 
1499 	if (state->mux)
1500 		return ssh_packet_read_poll2_mux(ssh, typep, seqnr_p);
1501 
1502 	*typep = SSH_MSG_NONE;
1503 
1504 	if (state->packet_discard)
1505 		return 0;
1506 
1507 	if (state->newkeys[MODE_IN] != NULL) {
1508 		enc  = &state->newkeys[MODE_IN]->enc;
1509 		mac  = &state->newkeys[MODE_IN]->mac;
1510 		comp = &state->newkeys[MODE_IN]->comp;
1511 		/* disable mac for authenticated encryption */
1512 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
1513 			mac = NULL;
1514 	}
1515 	maclen = mac && mac->enabled ? mac->mac_len : 0;
1516 	block_size = enc ? enc->block_size : 8;
1517 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1518 
1519 	if (aadlen && state->packlen == 0) {
1520 		if (cipher_get_length(state->receive_context,
1521 		    &state->packlen, state->p_read.seqnr,
1522 		    sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
1523 			return 0;
1524 		if (state->packlen < 1 + 4 ||
1525 		    state->packlen > PACKET_MAX_SIZE) {
1526 #ifdef PACKET_DEBUG
1527 			sshbuf_dump(state->input, stderr);
1528 #endif
1529 			logit("Bad packet length %u.", state->packlen);
1530 			if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1531 				return r;
1532 			return SSH_ERR_CONN_CORRUPT;
1533 		}
1534 		sshbuf_reset(state->incoming_packet);
1535 	} else if (state->packlen == 0) {
1536 		/*
1537 		 * check if input size is less than the cipher block size,
1538 		 * decrypt first block and extract length of incoming packet
1539 		 */
1540 		if (sshbuf_len(state->input) < block_size)
1541 			return 0;
1542 		sshbuf_reset(state->incoming_packet);
1543 		if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1544 		    &cp)) != 0)
1545 			goto out;
1546 		if ((r = cipher_crypt(state->receive_context,
1547 		    state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1548 		    block_size, 0, 0)) != 0)
1549 			goto out;
1550 		state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1551 		if (state->packlen < 1 + 4 ||
1552 		    state->packlen > PACKET_MAX_SIZE) {
1553 #ifdef PACKET_DEBUG
1554 			fprintf(stderr, "input: \n");
1555 			sshbuf_dump(state->input, stderr);
1556 			fprintf(stderr, "incoming_packet: \n");
1557 			sshbuf_dump(state->incoming_packet, stderr);
1558 #endif
1559 			logit("Bad packet length %u.", state->packlen);
1560 			return ssh_packet_start_discard(ssh, enc, mac, 0,
1561 			    PACKET_MAX_SIZE);
1562 		}
1563 		if ((r = sshbuf_consume(state->input, block_size)) != 0)
1564 			goto out;
1565 	}
1566 	DBG(debug("input: packet len %u", state->packlen+4));
1567 
1568 	if (aadlen) {
1569 		/* only the payload is encrypted */
1570 		need = state->packlen;
1571 	} else {
1572 		/*
1573 		 * the payload size and the payload are encrypted, but we
1574 		 * have a partial packet of block_size bytes
1575 		 */
1576 		need = 4 + state->packlen - block_size;
1577 	}
1578 	DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1579 	    " aadlen %d", block_size, need, maclen, authlen, aadlen));
1580 	if (need % block_size != 0) {
1581 		logit("padding error: need %d block %d mod %d",
1582 		    need, block_size, need % block_size);
1583 		return ssh_packet_start_discard(ssh, enc, mac, 0,
1584 		    PACKET_MAX_SIZE - block_size);
1585 	}
1586 	/*
1587 	 * check if the entire packet has been received and
1588 	 * decrypt into incoming_packet:
1589 	 * 'aadlen' bytes are unencrypted, but authenticated.
1590 	 * 'need' bytes are encrypted, followed by either
1591 	 * 'authlen' bytes of authentication tag or
1592 	 * 'maclen' bytes of message authentication code.
1593 	 */
1594 	if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1595 		return 0; /* packet is incomplete */
1596 #ifdef PACKET_DEBUG
1597 	fprintf(stderr, "read_poll enc/full: ");
1598 	sshbuf_dump(state->input, stderr);
1599 #endif
1600 	/* EtM: check mac over encrypted input */
1601 	if (mac && mac->enabled && mac->etm) {
1602 		if ((r = mac_check(mac, state->p_read.seqnr,
1603 		    sshbuf_ptr(state->input), aadlen + need,
1604 		    sshbuf_ptr(state->input) + aadlen + need + authlen,
1605 		    maclen)) != 0) {
1606 			if (r == SSH_ERR_MAC_INVALID)
1607 				logit("Corrupted MAC on input.");
1608 			goto out;
1609 		}
1610 	}
1611 	if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1612 	    &cp)) != 0)
1613 		goto out;
1614 	if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
1615 	    sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1616 		goto out;
1617 	if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1618 		goto out;
1619 	if (mac && mac->enabled) {
1620 		/* Not EtM: check MAC over cleartext */
1621 		if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
1622 		    sshbuf_ptr(state->incoming_packet),
1623 		    sshbuf_len(state->incoming_packet),
1624 		    sshbuf_ptr(state->input), maclen)) != 0) {
1625 			if (r != SSH_ERR_MAC_INVALID)
1626 				goto out;
1627 			logit("Corrupted MAC on input.");
1628 			if (need + block_size > PACKET_MAX_SIZE)
1629 				return SSH_ERR_INTERNAL_ERROR;
1630 			return ssh_packet_start_discard(ssh, enc, mac,
1631 			    sshbuf_len(state->incoming_packet),
1632 			    PACKET_MAX_SIZE - need - block_size);
1633 		}
1634 		/* Remove MAC from input buffer */
1635 		DBG(debug("MAC #%d ok", state->p_read.seqnr));
1636 		if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1637 			goto out;
1638 	}
1639 	if (seqnr_p != NULL)
1640 		*seqnr_p = state->p_read.seqnr;
1641 	if (++state->p_read.seqnr == 0)
1642 		logit("incoming seqnr wraps around");
1643 	if (++state->p_read.packets == 0)
1644 		if (!(ssh->compat & SSH_BUG_NOREKEY))
1645 			return SSH_ERR_NEED_REKEY;
1646 	state->p_read.blocks += (state->packlen + 4) / block_size;
1647 	state->p_read.bytes += state->packlen + 4;
1648 
1649 	/* get padlen */
1650 	padlen = sshbuf_ptr(state->incoming_packet)[4];
1651 	DBG(debug("input: padlen %d", padlen));
1652 	if (padlen < 4)	{
1653 		if ((r = sshpkt_disconnect(ssh,
1654 		    "Corrupted padlen %d on input.", padlen)) != 0 ||
1655 		    (r = ssh_packet_write_wait(ssh)) != 0)
1656 			return r;
1657 		return SSH_ERR_CONN_CORRUPT;
1658 	}
1659 
1660 	/* skip packet size + padlen, discard padding */
1661 	if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1662 	    ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1663 		goto out;
1664 
1665 	DBG(debug("input: len before de-compress %zd",
1666 	    sshbuf_len(state->incoming_packet)));
1667 	if (comp && comp->enabled) {
1668 		sshbuf_reset(state->compression_buffer);
1669 		if ((r = uncompress_buffer(ssh, state->incoming_packet,
1670 		    state->compression_buffer)) != 0)
1671 			goto out;
1672 		sshbuf_reset(state->incoming_packet);
1673 		if ((r = sshbuf_putb(state->incoming_packet,
1674 		    state->compression_buffer)) != 0)
1675 			goto out;
1676 		DBG(debug("input: len after de-compress %zd",
1677 		    sshbuf_len(state->incoming_packet)));
1678 	}
1679 	/*
1680 	 * get packet type, implies consume.
1681 	 * return length of payload (without type field)
1682 	 */
1683 	if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1684 		goto out;
1685 	if (ssh_packet_log_type(*typep))
1686 		debug3("receive packet: type %u", *typep);
1687 	if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
1688 		if ((r = sshpkt_disconnect(ssh,
1689 		    "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1690 		    (r = ssh_packet_write_wait(ssh)) != 0)
1691 			return r;
1692 		return SSH_ERR_PROTOCOL_ERROR;
1693 	}
1694 	if (state->hook_in != NULL &&
1695 	    (r = state->hook_in(ssh, state->incoming_packet, typep,
1696 	    state->hook_in_ctx)) != 0)
1697 		return r;
1698 	if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1699 		r = ssh_packet_enable_delayed_compress(ssh);
1700 	else
1701 		r = 0;
1702 #ifdef PACKET_DEBUG
1703 	fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1704 	sshbuf_dump(state->incoming_packet, stderr);
1705 #endif
1706 	/* reset for next packet */
1707 	state->packlen = 0;
1708 
1709 	/* do we need to rekey? */
1710 	if (ssh_packet_need_rekeying(ssh, 0)) {
1711 		debug3("%s: rekex triggered", __func__);
1712 		if ((r = kex_start_rekex(ssh)) != 0)
1713 			return r;
1714 	}
1715  out:
1716 	return r;
1717 }
1718 
1719 int
1720 ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1721 {
1722 	struct session_state *state = ssh->state;
1723 	u_int reason, seqnr;
1724 	int r;
1725 	u_char *msg;
1726 
1727 	for (;;) {
1728 		msg = NULL;
1729 		r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1730 		if (r != 0)
1731 			return r;
1732 		if (*typep) {
1733 			state->keep_alive_timeouts = 0;
1734 			DBG(debug("received packet type %d", *typep));
1735 		}
1736 		switch (*typep) {
1737 		case SSH2_MSG_IGNORE:
1738 			debug3("Received SSH2_MSG_IGNORE");
1739 			break;
1740 		case SSH2_MSG_DEBUG:
1741 			if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1742 			    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1743 			    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1744 				free(msg);
1745 				return r;
1746 			}
1747 			debug("Remote: %.900s", msg);
1748 			free(msg);
1749 			break;
1750 		case SSH2_MSG_DISCONNECT:
1751 			if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1752 			    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1753 				return r;
1754 			/* Ignore normal client exit notifications */
1755 			do_log2(ssh->state->server_side &&
1756 			    reason == SSH2_DISCONNECT_BY_APPLICATION ?
1757 			    SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1758 			    "Received disconnect from %s port %d:"
1759 			    "%u: %.400s", ssh_remote_ipaddr(ssh),
1760 			    ssh_remote_port(ssh), reason, msg);
1761 			free(msg);
1762 			return SSH_ERR_DISCONNECTED;
1763 		case SSH2_MSG_UNIMPLEMENTED:
1764 			if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1765 				return r;
1766 			debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1767 			    seqnr);
1768 			break;
1769 		default:
1770 			return 0;
1771 		}
1772 	}
1773 }
1774 
1775 /*
1776  * Buffers the given amount of input characters.  This is intended to be used
1777  * together with packet_read_poll.
1778  */
1779 
1780 int
1781 ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
1782 {
1783 	struct session_state *state = ssh->state;
1784 	int r;
1785 
1786 	if (state->packet_discard) {
1787 		state->keep_alive_timeouts = 0; /* ?? */
1788 		if (len >= state->packet_discard) {
1789 			if ((r = ssh_packet_stop_discard(ssh)) != 0)
1790 				return r;
1791 		}
1792 		state->packet_discard -= len;
1793 		return 0;
1794 	}
1795 	if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
1796 		return r;
1797 
1798 	return 0;
1799 }
1800 
1801 int
1802 ssh_packet_remaining(struct ssh *ssh)
1803 {
1804 	return sshbuf_len(ssh->state->incoming_packet);
1805 }
1806 
1807 /*
1808  * Sends a diagnostic message from the server to the client.  This message
1809  * can be sent at any time (but not while constructing another message). The
1810  * message is printed immediately, but only if the client is being executed
1811  * in verbose mode.  These messages are primarily intended to ease debugging
1812  * authentication problems.   The length of the formatted message must not
1813  * exceed 1024 bytes.  This will automatically call ssh_packet_write_wait.
1814  */
1815 void
1816 ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
1817 {
1818 	char buf[1024];
1819 	va_list args;
1820 	int r;
1821 
1822 	if ((ssh->compat & SSH_BUG_DEBUG))
1823 		return;
1824 
1825 	va_start(args, fmt);
1826 	vsnprintf(buf, sizeof(buf), fmt, args);
1827 	va_end(args);
1828 
1829 	debug3("sending debug message: %s", buf);
1830 
1831 	if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
1832 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
1833 	    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
1834 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1835 	    (r = sshpkt_send(ssh)) != 0 ||
1836 	    (r = ssh_packet_write_wait(ssh)) != 0)
1837 		fatal("%s: %s", __func__, ssh_err(r));
1838 }
1839 
1840 void
1841 sshpkt_fmt_connection_id(struct ssh *ssh, char *s, size_t l)
1842 {
1843 	snprintf(s, l, "%.200s%s%s port %d",
1844 	    ssh->log_preamble ? ssh->log_preamble : "",
1845 	    ssh->log_preamble ? " " : "",
1846 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1847 }
1848 
1849 /*
1850  * Pretty-print connection-terminating errors and exit.
1851  */
1852 static void
1853 sshpkt_vfatal(struct ssh *ssh, int r, const char *fmt, va_list ap)
1854 {
1855 	char *tag = NULL, remote_id[512];
1856 	int oerrno = errno;
1857 
1858 	sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1859 
1860 	switch (r) {
1861 	case SSH_ERR_CONN_CLOSED:
1862 		ssh_packet_clear_keys(ssh);
1863 		logdie("Connection closed by %s", remote_id);
1864 	case SSH_ERR_CONN_TIMEOUT:
1865 		ssh_packet_clear_keys(ssh);
1866 		logdie("Connection %s %s timed out",
1867 		    ssh->state->server_side ? "from" : "to", remote_id);
1868 	case SSH_ERR_DISCONNECTED:
1869 		ssh_packet_clear_keys(ssh);
1870 		logdie("Disconnected from %s", remote_id);
1871 	case SSH_ERR_SYSTEM_ERROR:
1872 		if (errno == ECONNRESET) {
1873 			ssh_packet_clear_keys(ssh);
1874 			logdie("Connection reset by %s", remote_id);
1875 		}
1876 		/* FALLTHROUGH */
1877 	case SSH_ERR_NO_CIPHER_ALG_MATCH:
1878 	case SSH_ERR_NO_MAC_ALG_MATCH:
1879 	case SSH_ERR_NO_COMPRESS_ALG_MATCH:
1880 	case SSH_ERR_NO_KEX_ALG_MATCH:
1881 	case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
1882 		if (ssh && ssh->kex && ssh->kex->failed_choice) {
1883 			ssh_packet_clear_keys(ssh);
1884 			errno = oerrno;
1885 			logdie("Unable to negotiate with %s: %s. "
1886 			    "Their offer: %s", remote_id, ssh_err(r),
1887 			    ssh->kex->failed_choice);
1888 		}
1889 		/* FALLTHROUGH */
1890 	default:
1891 		if (vasprintf(&tag, fmt, ap) == -1) {
1892 			ssh_packet_clear_keys(ssh);
1893 			logdie("%s: could not allocate failure message",
1894 			    __func__);
1895 		}
1896 		ssh_packet_clear_keys(ssh);
1897 		errno = oerrno;
1898 		logdie("%s%sConnection %s %s: %s",
1899 		    tag != NULL ? tag : "", tag != NULL ? ": " : "",
1900 		    ssh->state->server_side ? "from" : "to",
1901 		    remote_id, ssh_err(r));
1902 	}
1903 }
1904 
1905 void
1906 sshpkt_fatal(struct ssh *ssh, int r, const char *fmt, ...)
1907 {
1908 	va_list ap;
1909 
1910 	va_start(ap, fmt);
1911 	sshpkt_vfatal(ssh, r, fmt, ap);
1912 	/* NOTREACHED */
1913 	va_end(ap);
1914 	logdie("%s: should have exited", __func__);
1915 }
1916 
1917 /*
1918  * Logs the error plus constructs and sends a disconnect packet, closes the
1919  * connection, and exits.  This function never returns. The error message
1920  * should not contain a newline.  The length of the formatted message must
1921  * not exceed 1024 bytes.
1922  */
1923 void
1924 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
1925 {
1926 	char buf[1024], remote_id[512];
1927 	va_list args;
1928 	static int disconnecting = 0;
1929 	int r;
1930 
1931 	if (disconnecting)	/* Guard against recursive invocations. */
1932 		fatal("packet_disconnect called recursively.");
1933 	disconnecting = 1;
1934 
1935 	/*
1936 	 * Format the message.  Note that the caller must make sure the
1937 	 * message is of limited size.
1938 	 */
1939 	sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1940 	va_start(args, fmt);
1941 	vsnprintf(buf, sizeof(buf), fmt, args);
1942 	va_end(args);
1943 
1944 	/* Display the error locally */
1945 	logit("Disconnecting %s: %.100s", remote_id, buf);
1946 
1947 	/*
1948 	 * Send the disconnect message to the other side, and wait
1949 	 * for it to get sent.
1950 	 */
1951 	if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
1952 		sshpkt_fatal(ssh, r, "%s", __func__);
1953 
1954 	if ((r = ssh_packet_write_wait(ssh)) != 0)
1955 		sshpkt_fatal(ssh, r, "%s", __func__);
1956 
1957 	/* Close the connection. */
1958 	ssh_packet_close(ssh);
1959 	cleanup_exit(255);
1960 }
1961 
1962 /*
1963  * Checks if there is any buffered output, and tries to write some of
1964  * the output.
1965  */
1966 int
1967 ssh_packet_write_poll(struct ssh *ssh)
1968 {
1969 	struct session_state *state = ssh->state;
1970 	int len = sshbuf_len(state->output);
1971 	int r;
1972 
1973 	if (len > 0) {
1974 		len = write(state->connection_out,
1975 		    sshbuf_ptr(state->output), len);
1976 		if (len == -1) {
1977 			if (errno == EINTR || errno == EAGAIN ||
1978 			    errno == EWOULDBLOCK)
1979 				return 0;
1980 			return SSH_ERR_SYSTEM_ERROR;
1981 		}
1982 		if (len == 0)
1983 			return SSH_ERR_CONN_CLOSED;
1984 		if ((r = sshbuf_consume(state->output, len)) != 0)
1985 			return r;
1986 	}
1987 	return 0;
1988 }
1989 
1990 /*
1991  * Calls packet_write_poll repeatedly until all pending output data has been
1992  * written.
1993  */
1994 int
1995 ssh_packet_write_wait(struct ssh *ssh)
1996 {
1997 	fd_set *setp;
1998 	int ret, r, ms_remain = 0;
1999 	struct timeval start, timeout, *timeoutp = NULL;
2000 	struct session_state *state = ssh->state;
2001 
2002 	setp = calloc(howmany(state->connection_out + 1,
2003 	    NFDBITS), sizeof(fd_mask));
2004 	if (setp == NULL)
2005 		return SSH_ERR_ALLOC_FAIL;
2006 	if ((r = ssh_packet_write_poll(ssh)) != 0) {
2007 		free(setp);
2008 		return r;
2009 	}
2010 	while (ssh_packet_have_data_to_write(ssh)) {
2011 		memset(setp, 0, howmany(state->connection_out + 1,
2012 		    NFDBITS) * sizeof(fd_mask));
2013 		FD_SET(state->connection_out, setp);
2014 
2015 		if (state->packet_timeout_ms > 0) {
2016 			ms_remain = state->packet_timeout_ms;
2017 			timeoutp = &timeout;
2018 		}
2019 		for (;;) {
2020 			if (state->packet_timeout_ms > 0) {
2021 				ms_to_timeval(&timeout, ms_remain);
2022 				monotime_tv(&start);
2023 			}
2024 			if ((ret = select(state->connection_out + 1,
2025 			    NULL, setp, NULL, timeoutp)) >= 0)
2026 				break;
2027 			if (errno != EAGAIN && errno != EINTR &&
2028 			    errno != EWOULDBLOCK)
2029 				break;
2030 			if (state->packet_timeout_ms <= 0)
2031 				continue;
2032 			ms_subtract_diff(&start, &ms_remain);
2033 			if (ms_remain <= 0) {
2034 				ret = 0;
2035 				break;
2036 			}
2037 		}
2038 		if (ret == 0) {
2039 			free(setp);
2040 			return SSH_ERR_CONN_TIMEOUT;
2041 		}
2042 		if ((r = ssh_packet_write_poll(ssh)) != 0) {
2043 			free(setp);
2044 			return r;
2045 		}
2046 	}
2047 	free(setp);
2048 	return 0;
2049 }
2050 
2051 /* Returns true if there is buffered data to write to the connection. */
2052 
2053 int
2054 ssh_packet_have_data_to_write(struct ssh *ssh)
2055 {
2056 	return sshbuf_len(ssh->state->output) != 0;
2057 }
2058 
2059 /* Returns true if there is not too much data to write to the connection. */
2060 
2061 int
2062 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2063 {
2064 	if (ssh->state->interactive_mode)
2065 		return sshbuf_len(ssh->state->output) < 16384;
2066 	else
2067 		return sshbuf_len(ssh->state->output) < 128 * 1024;
2068 }
2069 
2070 void
2071 ssh_packet_set_tos(struct ssh *ssh, int tos)
2072 {
2073 #ifndef IP_TOS_IS_BROKEN
2074 	if (!ssh_packet_connection_is_on_socket(ssh) || tos == INT_MAX)
2075 		return;
2076 	switch (ssh_packet_connection_af(ssh)) {
2077 # ifdef IP_TOS
2078 	case AF_INET:
2079 		debug3("%s: set IP_TOS 0x%02x", __func__, tos);
2080 		if (setsockopt(ssh->state->connection_in,
2081 		    IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) == -1)
2082 			error("setsockopt IP_TOS %d: %.100s:",
2083 			    tos, strerror(errno));
2084 		break;
2085 # endif /* IP_TOS */
2086 # ifdef IPV6_TCLASS
2087 	case AF_INET6:
2088 		debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
2089 		if (setsockopt(ssh->state->connection_in,
2090 		    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) == -1)
2091 			error("setsockopt IPV6_TCLASS %d: %.100s:",
2092 			    tos, strerror(errno));
2093 		break;
2094 # endif /* IPV6_TCLASS */
2095 	}
2096 #endif /* IP_TOS_IS_BROKEN */
2097 }
2098 
2099 /* Informs that the current session is interactive.  Sets IP flags for that. */
2100 
2101 void
2102 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
2103 {
2104 	struct session_state *state = ssh->state;
2105 
2106 	if (state->set_interactive_called)
2107 		return;
2108 	state->set_interactive_called = 1;
2109 
2110 	/* Record that we are in interactive mode. */
2111 	state->interactive_mode = interactive;
2112 
2113 	/* Only set socket options if using a socket.  */
2114 	if (!ssh_packet_connection_is_on_socket(ssh))
2115 		return;
2116 	set_nodelay(state->connection_in);
2117 	ssh_packet_set_tos(ssh, interactive ? qos_interactive :
2118 	    qos_bulk);
2119 }
2120 
2121 /* Returns true if the current connection is interactive. */
2122 
2123 int
2124 ssh_packet_is_interactive(struct ssh *ssh)
2125 {
2126 	return ssh->state->interactive_mode;
2127 }
2128 
2129 int
2130 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2131 {
2132 	struct session_state *state = ssh->state;
2133 
2134 	if (state->set_maxsize_called) {
2135 		logit("packet_set_maxsize: called twice: old %d new %d",
2136 		    state->max_packet_size, s);
2137 		return -1;
2138 	}
2139 	if (s < 4 * 1024 || s > 1024 * 1024) {
2140 		logit("packet_set_maxsize: bad size %d", s);
2141 		return -1;
2142 	}
2143 	state->set_maxsize_called = 1;
2144 	debug("packet_set_maxsize: setting to %d", s);
2145 	state->max_packet_size = s;
2146 	return s;
2147 }
2148 
2149 int
2150 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2151 {
2152 	return ++ssh->state->keep_alive_timeouts;
2153 }
2154 
2155 void
2156 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2157 {
2158 	ssh->state->keep_alive_timeouts = ka;
2159 }
2160 
2161 u_int
2162 ssh_packet_get_maxsize(struct ssh *ssh)
2163 {
2164 	return ssh->state->max_packet_size;
2165 }
2166 
2167 void
2168 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, u_int32_t seconds)
2169 {
2170 	debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
2171 	    (unsigned int)seconds);
2172 	ssh->state->rekey_limit = bytes;
2173 	ssh->state->rekey_interval = seconds;
2174 }
2175 
2176 time_t
2177 ssh_packet_get_rekey_timeout(struct ssh *ssh)
2178 {
2179 	time_t seconds;
2180 
2181 	seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2182 	    monotime();
2183 	return (seconds <= 0 ? 1 : seconds);
2184 }
2185 
2186 void
2187 ssh_packet_set_server(struct ssh *ssh)
2188 {
2189 	ssh->state->server_side = 1;
2190 	ssh->kex->server = 1; /* XXX unify? */
2191 }
2192 
2193 void
2194 ssh_packet_set_authenticated(struct ssh *ssh)
2195 {
2196 	ssh->state->after_authentication = 1;
2197 }
2198 
2199 void *
2200 ssh_packet_get_input(struct ssh *ssh)
2201 {
2202 	return (void *)ssh->state->input;
2203 }
2204 
2205 void *
2206 ssh_packet_get_output(struct ssh *ssh)
2207 {
2208 	return (void *)ssh->state->output;
2209 }
2210 
2211 /* Reset after_authentication and reset compression in post-auth privsep */
2212 static int
2213 ssh_packet_set_postauth(struct ssh *ssh)
2214 {
2215 	int r;
2216 
2217 	debug("%s: called", __func__);
2218 	/* This was set in net child, but is not visible in user child */
2219 	ssh->state->after_authentication = 1;
2220 	ssh->state->rekeying = 0;
2221 	if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
2222 		return r;
2223 	return 0;
2224 }
2225 
2226 /* Packet state (de-)serialization for privsep */
2227 
2228 /* turn kex into a blob for packet state serialization */
2229 static int
2230 kex_to_blob(struct sshbuf *m, struct kex *kex)
2231 {
2232 	int r;
2233 
2234 	if ((r = sshbuf_put_string(m, kex->session_id,
2235 	    kex->session_id_len)) != 0 ||
2236 	    (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2237 	    (r = sshbuf_put_cstring(m, kex->hostkey_alg)) != 0 ||
2238 	    (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2239 	    (r = sshbuf_put_u32(m, kex->hostkey_nid)) != 0 ||
2240 	    (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2241 	    (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2242 	    (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2243 	    (r = sshbuf_put_stringb(m, kex->client_version)) != 0 ||
2244 	    (r = sshbuf_put_stringb(m, kex->server_version)) != 0 ||
2245 	    (r = sshbuf_put_u32(m, kex->flags)) != 0)
2246 		return r;
2247 	return 0;
2248 }
2249 
2250 /* turn key exchange results into a blob for packet state serialization */
2251 static int
2252 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2253 {
2254 	struct sshbuf *b;
2255 	struct sshcipher_ctx *cc;
2256 	struct sshcomp *comp;
2257 	struct sshenc *enc;
2258 	struct sshmac *mac;
2259 	struct newkeys *newkey;
2260 	int r;
2261 
2262 	if ((newkey = ssh->state->newkeys[mode]) == NULL)
2263 		return SSH_ERR_INTERNAL_ERROR;
2264 	enc = &newkey->enc;
2265 	mac = &newkey->mac;
2266 	comp = &newkey->comp;
2267 	cc = (mode == MODE_OUT) ? ssh->state->send_context :
2268 	    ssh->state->receive_context;
2269 	if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2270 		return r;
2271 	if ((b = sshbuf_new()) == NULL)
2272 		return SSH_ERR_ALLOC_FAIL;
2273 	if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2274 	    (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2275 	    (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2276 	    (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2277 	    (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2278 		goto out;
2279 	if (cipher_authlen(enc->cipher) == 0) {
2280 		if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2281 		    (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2282 		    (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2283 			goto out;
2284 	}
2285 	if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2286 	    (r = sshbuf_put_cstring(b, comp->name)) != 0)
2287 		goto out;
2288 	r = sshbuf_put_stringb(m, b);
2289  out:
2290 	sshbuf_free(b);
2291 	return r;
2292 }
2293 
2294 /* serialize packet state into a blob */
2295 int
2296 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2297 {
2298 	struct session_state *state = ssh->state;
2299 	int r;
2300 
2301 	if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2302 	    (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2303 	    (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2304 	    (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2305 	    (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2306 	    (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2307 	    (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2308 	    (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2309 	    (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2310 	    (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2311 	    (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2312 	    (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2313 	    (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0 ||
2314 	    (r = sshbuf_put_stringb(m, state->input)) != 0 ||
2315 	    (r = sshbuf_put_stringb(m, state->output)) != 0)
2316 		return r;
2317 
2318 	return 0;
2319 }
2320 
2321 /* restore key exchange results from blob for packet state de-serialization */
2322 static int
2323 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2324 {
2325 	struct sshbuf *b = NULL;
2326 	struct sshcomp *comp;
2327 	struct sshenc *enc;
2328 	struct sshmac *mac;
2329 	struct newkeys *newkey = NULL;
2330 	size_t keylen, ivlen, maclen;
2331 	int r;
2332 
2333 	if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2334 		r = SSH_ERR_ALLOC_FAIL;
2335 		goto out;
2336 	}
2337 	if ((r = sshbuf_froms(m, &b)) != 0)
2338 		goto out;
2339 #ifdef DEBUG_PK
2340 	sshbuf_dump(b, stderr);
2341 #endif
2342 	enc = &newkey->enc;
2343 	mac = &newkey->mac;
2344 	comp = &newkey->comp;
2345 
2346 	if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2347 	    (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2348 	    (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2349 	    (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2350 	    (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2351 		goto out;
2352 	if ((enc->cipher = cipher_by_name(enc->name)) == NULL) {
2353 		r = SSH_ERR_INVALID_FORMAT;
2354 		goto out;
2355 	}
2356 	if (cipher_authlen(enc->cipher) == 0) {
2357 		if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2358 			goto out;
2359 		if ((r = mac_setup(mac, mac->name)) != 0)
2360 			goto out;
2361 		if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2362 		    (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2363 			goto out;
2364 		if (maclen > mac->key_len) {
2365 			r = SSH_ERR_INVALID_FORMAT;
2366 			goto out;
2367 		}
2368 		mac->key_len = maclen;
2369 	}
2370 	if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2371 	    (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2372 		goto out;
2373 	if (sshbuf_len(b) != 0) {
2374 		r = SSH_ERR_INVALID_FORMAT;
2375 		goto out;
2376 	}
2377 	enc->key_len = keylen;
2378 	enc->iv_len = ivlen;
2379 	ssh->kex->newkeys[mode] = newkey;
2380 	newkey = NULL;
2381 	r = 0;
2382  out:
2383 	free(newkey);
2384 	sshbuf_free(b);
2385 	return r;
2386 }
2387 
2388 /* restore kex from blob for packet state de-serialization */
2389 static int
2390 kex_from_blob(struct sshbuf *m, struct kex **kexp)
2391 {
2392 	struct kex *kex;
2393 	int r;
2394 
2395 	if ((kex = kex_new()) == NULL)
2396 		return SSH_ERR_ALLOC_FAIL;
2397 	if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
2398 	    (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2399 	    (r = sshbuf_get_cstring(m, &kex->hostkey_alg, NULL)) != 0 ||
2400 	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2401 	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_nid)) != 0 ||
2402 	    (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2403 	    (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2404 	    (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2405 	    (r = sshbuf_get_stringb(m, kex->client_version)) != 0 ||
2406 	    (r = sshbuf_get_stringb(m, kex->server_version)) != 0 ||
2407 	    (r = sshbuf_get_u32(m, &kex->flags)) != 0)
2408 		goto out;
2409 	kex->server = 1;
2410 	kex->done = 1;
2411 	r = 0;
2412  out:
2413 	if (r != 0 || kexp == NULL) {
2414 		kex_free(kex);
2415 		if (kexp != NULL)
2416 			*kexp = NULL;
2417 	} else {
2418 		kex_free(*kexp);
2419 		*kexp = kex;
2420 	}
2421 	return r;
2422 }
2423 
2424 /*
2425  * Restore packet state from content of blob 'm' (de-serialization).
2426  * Note that 'm' will be partially consumed on parsing or any other errors.
2427  */
2428 int
2429 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2430 {
2431 	struct session_state *state = ssh->state;
2432 	const u_char *input, *output;
2433 	size_t ilen, olen;
2434 	int r;
2435 
2436 	if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2437 	    (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2438 	    (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2439 	    (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2440 	    (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2441 	    (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2442 	    (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2443 	    (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2444 	    (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2445 	    (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2446 	    (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2447 	    (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2448 	    (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2449 		return r;
2450 	/*
2451 	 * We set the time here so that in post-auth privsep slave we
2452 	 * count from the completion of the authentication.
2453 	 */
2454 	state->rekey_time = monotime();
2455 	/* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2456 	if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2457 	    (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2458 		return r;
2459 
2460 	if ((r = ssh_packet_set_postauth(ssh)) != 0)
2461 		return r;
2462 
2463 	sshbuf_reset(state->input);
2464 	sshbuf_reset(state->output);
2465 	if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2466 	    (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2467 	    (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2468 	    (r = sshbuf_put(state->output, output, olen)) != 0)
2469 		return r;
2470 
2471 	if (sshbuf_len(m))
2472 		return SSH_ERR_INVALID_FORMAT;
2473 	debug3("%s: done", __func__);
2474 	return 0;
2475 }
2476 
2477 /* NEW API */
2478 
2479 /* put data to the outgoing packet */
2480 
2481 int
2482 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2483 {
2484 	return sshbuf_put(ssh->state->outgoing_packet, v, len);
2485 }
2486 
2487 int
2488 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2489 {
2490 	return sshbuf_putb(ssh->state->outgoing_packet, b);
2491 }
2492 
2493 int
2494 sshpkt_put_u8(struct ssh *ssh, u_char val)
2495 {
2496 	return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2497 }
2498 
2499 int
2500 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2501 {
2502 	return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2503 }
2504 
2505 int
2506 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2507 {
2508 	return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2509 }
2510 
2511 int
2512 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2513 {
2514 	return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2515 }
2516 
2517 int
2518 sshpkt_put_cstring(struct ssh *ssh, const void *v)
2519 {
2520 	return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2521 }
2522 
2523 int
2524 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2525 {
2526 	return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2527 }
2528 
2529 int
2530 sshpkt_getb_froms(struct ssh *ssh, struct sshbuf **valp)
2531 {
2532 	return sshbuf_froms(ssh->state->incoming_packet, valp);
2533 }
2534 
2535 #ifdef WITH_OPENSSL
2536 #ifdef OPENSSL_HAS_ECC
2537 int
2538 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2539 {
2540 	return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2541 }
2542 #endif /* OPENSSL_HAS_ECC */
2543 
2544 
2545 int
2546 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2547 {
2548 	return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2549 }
2550 #endif /* WITH_OPENSSL */
2551 
2552 /* fetch data from the incoming packet */
2553 
2554 int
2555 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2556 {
2557 	return sshbuf_get(ssh->state->incoming_packet, valp, len);
2558 }
2559 
2560 int
2561 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2562 {
2563 	return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2564 }
2565 
2566 int
2567 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2568 {
2569 	return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2570 }
2571 
2572 int
2573 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2574 {
2575 	return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2576 }
2577 
2578 int
2579 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2580 {
2581 	return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2582 }
2583 
2584 int
2585 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2586 {
2587 	return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2588 }
2589 
2590 int
2591 sshpkt_peek_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2592 {
2593 	return sshbuf_peek_string_direct(ssh->state->incoming_packet, valp, lenp);
2594 }
2595 
2596 int
2597 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2598 {
2599 	return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2600 }
2601 
2602 #ifdef WITH_OPENSSL
2603 #ifdef OPENSSL_HAS_ECC
2604 int
2605 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2606 {
2607 	return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2608 }
2609 #endif /* OPENSSL_HAS_ECC */
2610 
2611 int
2612 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM **valp)
2613 {
2614 	return sshbuf_get_bignum2(ssh->state->incoming_packet, valp);
2615 }
2616 #endif /* WITH_OPENSSL */
2617 
2618 int
2619 sshpkt_get_end(struct ssh *ssh)
2620 {
2621 	if (sshbuf_len(ssh->state->incoming_packet) > 0)
2622 		return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2623 	return 0;
2624 }
2625 
2626 const u_char *
2627 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2628 {
2629 	if (lenp != NULL)
2630 		*lenp = sshbuf_len(ssh->state->incoming_packet);
2631 	return sshbuf_ptr(ssh->state->incoming_packet);
2632 }
2633 
2634 /* start a new packet */
2635 
2636 int
2637 sshpkt_start(struct ssh *ssh, u_char type)
2638 {
2639 	u_char buf[6]; /* u32 packet length, u8 pad len, u8 type */
2640 
2641 	DBG(debug("packet_start[%d]", type));
2642 	memset(buf, 0, sizeof(buf));
2643 	buf[sizeof(buf) - 1] = type;
2644 	sshbuf_reset(ssh->state->outgoing_packet);
2645 	return sshbuf_put(ssh->state->outgoing_packet, buf, sizeof(buf));
2646 }
2647 
2648 static int
2649 ssh_packet_send_mux(struct ssh *ssh)
2650 {
2651 	struct session_state *state = ssh->state;
2652 	u_char type, *cp;
2653 	size_t len;
2654 	int r;
2655 
2656 	if (ssh->kex)
2657 		return SSH_ERR_INTERNAL_ERROR;
2658 	len = sshbuf_len(state->outgoing_packet);
2659 	if (len < 6)
2660 		return SSH_ERR_INTERNAL_ERROR;
2661 	cp = sshbuf_mutable_ptr(state->outgoing_packet);
2662 	type = cp[5];
2663 	if (ssh_packet_log_type(type))
2664 		debug3("%s: type %u", __func__, type);
2665 	/* drop everything, but the connection protocol */
2666 	if (type >= SSH2_MSG_CONNECTION_MIN &&
2667 	    type <= SSH2_MSG_CONNECTION_MAX) {
2668 		POKE_U32(cp, len - 4);
2669 		if ((r = sshbuf_putb(state->output,
2670 		    state->outgoing_packet)) != 0)
2671 			return r;
2672 		/* sshbuf_dump(state->output, stderr); */
2673 	}
2674 	sshbuf_reset(state->outgoing_packet);
2675 	return 0;
2676 }
2677 
2678 /*
2679  * 9.2.  Ignored Data Message
2680  *
2681  *   byte      SSH_MSG_IGNORE
2682  *   string    data
2683  *
2684  * All implementations MUST understand (and ignore) this message at any
2685  * time (after receiving the protocol version). No implementation is
2686  * required to send them. This message can be used as an additional
2687  * protection measure against advanced traffic analysis techniques.
2688  */
2689 int
2690 sshpkt_msg_ignore(struct ssh *ssh, u_int nbytes)
2691 {
2692 	u_int32_t rnd = 0;
2693 	int r;
2694 	u_int i;
2695 
2696 	if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2697 	    (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2698 		return r;
2699 	for (i = 0; i < nbytes; i++) {
2700 		if (i % 4 == 0)
2701 			rnd = arc4random();
2702 		if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2703 			return r;
2704 		rnd >>= 8;
2705 	}
2706 	return 0;
2707 }
2708 
2709 /* send it */
2710 
2711 int
2712 sshpkt_send(struct ssh *ssh)
2713 {
2714 	if (ssh->state && ssh->state->mux)
2715 		return ssh_packet_send_mux(ssh);
2716 	return ssh_packet_send2(ssh);
2717 }
2718 
2719 int
2720 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
2721 {
2722 	char buf[1024];
2723 	va_list args;
2724 	int r;
2725 
2726 	va_start(args, fmt);
2727 	vsnprintf(buf, sizeof(buf), fmt, args);
2728 	va_end(args);
2729 
2730 	if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
2731 	    (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
2732 	    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2733 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2734 	    (r = sshpkt_send(ssh)) != 0)
2735 		return r;
2736 	return 0;
2737 }
2738 
2739 /* roundup current message to pad bytes */
2740 int
2741 sshpkt_add_padding(struct ssh *ssh, u_char pad)
2742 {
2743 	ssh->state->extra_pad = pad;
2744 	return 0;
2745 }
2746