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