xref: /openssh-portable/packet.c (revision 07f5f369)
1 /* $OpenBSD: packet.c,v 1.293 2020/06/24 15:12:09 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 	kex_free(ssh->kex);
620 	ssh->kex = NULL;
621 #ifdef WITH_ZLIB
622 	/* compression state is in shared mem, so we can only release it once */
623 	if (do_close && state->compression_buffer) {
624 		sshbuf_free(state->compression_buffer);
625 		if (state->compression_out_started) {
626 			z_streamp stream = &state->compression_out_stream;
627 			debug("compress outgoing: "
628 			    "raw data %llu, compressed %llu, factor %.2f",
629 				(unsigned long long)stream->total_in,
630 				(unsigned long long)stream->total_out,
631 				stream->total_in == 0 ? 0.0 :
632 				(double) stream->total_out / stream->total_in);
633 			if (state->compression_out_failures == 0)
634 				deflateEnd(stream);
635 		}
636 		if (state->compression_in_started) {
637 			z_streamp stream = &state->compression_in_stream;
638 			debug("compress incoming: "
639 			    "raw data %llu, compressed %llu, factor %.2f",
640 			    (unsigned long long)stream->total_out,
641 			    (unsigned long long)stream->total_in,
642 			    stream->total_out == 0 ? 0.0 :
643 			    (double) stream->total_in / stream->total_out);
644 			if (state->compression_in_failures == 0)
645 				inflateEnd(stream);
646 		}
647 	}
648 #endif	/* WITH_ZLIB */
649 	cipher_free(state->send_context);
650 	cipher_free(state->receive_context);
651 	state->send_context = state->receive_context = NULL;
652 	if (do_close) {
653 		free(ssh->local_ipaddr);
654 		ssh->local_ipaddr = NULL;
655 		free(ssh->remote_ipaddr);
656 		ssh->remote_ipaddr = NULL;
657 		free(ssh->state);
658 		ssh->state = NULL;
659 	}
660 }
661 
662 void
663 ssh_packet_close(struct ssh *ssh)
664 {
665 	ssh_packet_close_internal(ssh, 1);
666 }
667 
668 void
669 ssh_packet_clear_keys(struct ssh *ssh)
670 {
671 	ssh_packet_close_internal(ssh, 0);
672 }
673 
674 /* Sets remote side protocol flags. */
675 
676 void
677 ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
678 {
679 	ssh->state->remote_protocol_flags = protocol_flags;
680 }
681 
682 /* Returns the remote protocol flags set earlier by the above function. */
683 
684 u_int
685 ssh_packet_get_protocol_flags(struct ssh *ssh)
686 {
687 	return ssh->state->remote_protocol_flags;
688 }
689 
690 /*
691  * Starts packet compression from the next packet on in both directions.
692  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
693  */
694 
695 static int
696 ssh_packet_init_compression(struct ssh *ssh)
697 {
698 	if (!ssh->state->compression_buffer &&
699 	   ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
700 		return SSH_ERR_ALLOC_FAIL;
701 	return 0;
702 }
703 
704 #ifdef WITH_ZLIB
705 static int
706 start_compression_out(struct ssh *ssh, int level)
707 {
708 	if (level < 1 || level > 9)
709 		return SSH_ERR_INVALID_ARGUMENT;
710 	debug("Enabling compression at level %d.", level);
711 	if (ssh->state->compression_out_started == 1)
712 		deflateEnd(&ssh->state->compression_out_stream);
713 	switch (deflateInit(&ssh->state->compression_out_stream, level)) {
714 	case Z_OK:
715 		ssh->state->compression_out_started = 1;
716 		break;
717 	case Z_MEM_ERROR:
718 		return SSH_ERR_ALLOC_FAIL;
719 	default:
720 		return SSH_ERR_INTERNAL_ERROR;
721 	}
722 	return 0;
723 }
724 
725 static int
726 start_compression_in(struct ssh *ssh)
727 {
728 	if (ssh->state->compression_in_started == 1)
729 		inflateEnd(&ssh->state->compression_in_stream);
730 	switch (inflateInit(&ssh->state->compression_in_stream)) {
731 	case Z_OK:
732 		ssh->state->compression_in_started = 1;
733 		break;
734 	case Z_MEM_ERROR:
735 		return SSH_ERR_ALLOC_FAIL;
736 	default:
737 		return SSH_ERR_INTERNAL_ERROR;
738 	}
739 	return 0;
740 }
741 
742 /* XXX remove need for separate compression buffer */
743 static int
744 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
745 {
746 	u_char buf[4096];
747 	int r, status;
748 
749 	if (ssh->state->compression_out_started != 1)
750 		return SSH_ERR_INTERNAL_ERROR;
751 
752 	/* This case is not handled below. */
753 	if (sshbuf_len(in) == 0)
754 		return 0;
755 
756 	/* Input is the contents of the input buffer. */
757 	if ((ssh->state->compression_out_stream.next_in =
758 	    sshbuf_mutable_ptr(in)) == NULL)
759 		return SSH_ERR_INTERNAL_ERROR;
760 	ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
761 
762 	/* Loop compressing until deflate() returns with avail_out != 0. */
763 	do {
764 		/* Set up fixed-size output buffer. */
765 		ssh->state->compression_out_stream.next_out = buf;
766 		ssh->state->compression_out_stream.avail_out = sizeof(buf);
767 
768 		/* Compress as much data into the buffer as possible. */
769 		status = deflate(&ssh->state->compression_out_stream,
770 		    Z_PARTIAL_FLUSH);
771 		switch (status) {
772 		case Z_MEM_ERROR:
773 			return SSH_ERR_ALLOC_FAIL;
774 		case Z_OK:
775 			/* Append compressed data to output_buffer. */
776 			if ((r = sshbuf_put(out, buf, sizeof(buf) -
777 			    ssh->state->compression_out_stream.avail_out)) != 0)
778 				return r;
779 			break;
780 		case Z_STREAM_ERROR:
781 		default:
782 			ssh->state->compression_out_failures++;
783 			return SSH_ERR_INVALID_FORMAT;
784 		}
785 	} while (ssh->state->compression_out_stream.avail_out == 0);
786 	return 0;
787 }
788 
789 static int
790 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
791 {
792 	u_char buf[4096];
793 	int r, status;
794 
795 	if (ssh->state->compression_in_started != 1)
796 		return SSH_ERR_INTERNAL_ERROR;
797 
798 	if ((ssh->state->compression_in_stream.next_in =
799 	    sshbuf_mutable_ptr(in)) == NULL)
800 		return SSH_ERR_INTERNAL_ERROR;
801 	ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
802 
803 	for (;;) {
804 		/* Set up fixed-size output buffer. */
805 		ssh->state->compression_in_stream.next_out = buf;
806 		ssh->state->compression_in_stream.avail_out = sizeof(buf);
807 
808 		status = inflate(&ssh->state->compression_in_stream,
809 		    Z_PARTIAL_FLUSH);
810 		switch (status) {
811 		case Z_OK:
812 			if ((r = sshbuf_put(out, buf, sizeof(buf) -
813 			    ssh->state->compression_in_stream.avail_out)) != 0)
814 				return r;
815 			break;
816 		case Z_BUF_ERROR:
817 			/*
818 			 * Comments in zlib.h say that we should keep calling
819 			 * inflate() until we get an error.  This appears to
820 			 * be the error that we get.
821 			 */
822 			return 0;
823 		case Z_DATA_ERROR:
824 			return SSH_ERR_INVALID_FORMAT;
825 		case Z_MEM_ERROR:
826 			return SSH_ERR_ALLOC_FAIL;
827 		case Z_STREAM_ERROR:
828 		default:
829 			ssh->state->compression_in_failures++;
830 			return SSH_ERR_INTERNAL_ERROR;
831 		}
832 	}
833 	/* NOTREACHED */
834 }
835 
836 #else	/* WITH_ZLIB */
837 
838 static int
839 start_compression_out(struct ssh *ssh, int level)
840 {
841 	return SSH_ERR_INTERNAL_ERROR;
842 }
843 
844 static int
845 start_compression_in(struct ssh *ssh)
846 {
847 	return SSH_ERR_INTERNAL_ERROR;
848 }
849 
850 static int
851 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
852 {
853 	return SSH_ERR_INTERNAL_ERROR;
854 }
855 
856 static int
857 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
858 {
859 	return SSH_ERR_INTERNAL_ERROR;
860 }
861 #endif	/* WITH_ZLIB */
862 
863 void
864 ssh_clear_newkeys(struct ssh *ssh, int mode)
865 {
866 	if (ssh->kex && ssh->kex->newkeys[mode]) {
867 		kex_free_newkeys(ssh->kex->newkeys[mode]);
868 		ssh->kex->newkeys[mode] = NULL;
869 	}
870 }
871 
872 int
873 ssh_set_newkeys(struct ssh *ssh, int mode)
874 {
875 	struct session_state *state = ssh->state;
876 	struct sshenc *enc;
877 	struct sshmac *mac;
878 	struct sshcomp *comp;
879 	struct sshcipher_ctx **ccp;
880 	struct packet_state *ps;
881 	u_int64_t *max_blocks;
882 	const char *wmsg;
883 	int r, crypt_type;
884 	const char *dir = mode == MODE_OUT ? "out" : "in";
885 
886 	debug2("set_newkeys: mode %d", mode);
887 
888 	if (mode == MODE_OUT) {
889 		ccp = &state->send_context;
890 		crypt_type = CIPHER_ENCRYPT;
891 		ps = &state->p_send;
892 		max_blocks = &state->max_blocks_out;
893 	} else {
894 		ccp = &state->receive_context;
895 		crypt_type = CIPHER_DECRYPT;
896 		ps = &state->p_read;
897 		max_blocks = &state->max_blocks_in;
898 	}
899 	if (state->newkeys[mode] != NULL) {
900 		debug("%s: rekeying %s, input %llu bytes %llu blocks, "
901 		   "output %llu bytes %llu blocks", __func__, dir,
902 		   (unsigned long long)state->p_read.bytes,
903 		   (unsigned long long)state->p_read.blocks,
904 		   (unsigned long long)state->p_send.bytes,
905 		   (unsigned long long)state->p_send.blocks);
906 		kex_free_newkeys(state->newkeys[mode]);
907 		state->newkeys[mode] = NULL;
908 	}
909 	/* note that both bytes and the seqnr are not reset */
910 	ps->packets = ps->blocks = 0;
911 	/* move newkeys from kex to state */
912 	if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
913 		return SSH_ERR_INTERNAL_ERROR;
914 	ssh->kex->newkeys[mode] = NULL;
915 	enc  = &state->newkeys[mode]->enc;
916 	mac  = &state->newkeys[mode]->mac;
917 	comp = &state->newkeys[mode]->comp;
918 	if (cipher_authlen(enc->cipher) == 0) {
919 		if ((r = mac_init(mac)) != 0)
920 			return r;
921 	}
922 	mac->enabled = 1;
923 	DBG(debug("%s: cipher_init_context: %s", __func__, dir));
924 	cipher_free(*ccp);
925 	*ccp = NULL;
926 	if ((r = cipher_init(ccp, enc->cipher, enc->key, enc->key_len,
927 	    enc->iv, enc->iv_len, crypt_type)) != 0)
928 		return r;
929 	if (!state->cipher_warning_done &&
930 	    (wmsg = cipher_warning_message(*ccp)) != NULL) {
931 		error("Warning: %s", wmsg);
932 		state->cipher_warning_done = 1;
933 	}
934 	/* Deleting the keys does not gain extra security */
935 	/* explicit_bzero(enc->iv,  enc->block_size);
936 	   explicit_bzero(enc->key, enc->key_len);
937 	   explicit_bzero(mac->key, mac->key_len); */
938 	if ((comp->type == COMP_ZLIB ||
939 	    (comp->type == COMP_DELAYED &&
940 	     state->after_authentication)) && comp->enabled == 0) {
941 		if ((r = ssh_packet_init_compression(ssh)) < 0)
942 			return r;
943 		if (mode == MODE_OUT) {
944 			if ((r = start_compression_out(ssh, 6)) != 0)
945 				return r;
946 		} else {
947 			if ((r = start_compression_in(ssh)) != 0)
948 				return r;
949 		}
950 		comp->enabled = 1;
951 	}
952 	/*
953 	 * The 2^(blocksize*2) limit is too expensive for 3DES,
954 	 * so enforce a 1GB limit for small blocksizes.
955 	 * See RFC4344 section 3.2.
956 	 */
957 	if (enc->block_size >= 16)
958 		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
959 	else
960 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
961 	if (state->rekey_limit)
962 		*max_blocks = MINIMUM(*max_blocks,
963 		    state->rekey_limit / enc->block_size);
964 	debug("rekey %s after %llu blocks", dir,
965 	    (unsigned long long)*max_blocks);
966 	return 0;
967 }
968 
969 #define MAX_PACKETS	(1U<<31)
970 static int
971 ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
972 {
973 	struct session_state *state = ssh->state;
974 	u_int32_t out_blocks;
975 
976 	/* XXX client can't cope with rekeying pre-auth */
977 	if (!state->after_authentication)
978 		return 0;
979 
980 	/* Haven't keyed yet or KEX in progress. */
981 	if (ssh_packet_is_rekeying(ssh))
982 		return 0;
983 
984 	/* Peer can't rekey */
985 	if (ssh->compat & SSH_BUG_NOREKEY)
986 		return 0;
987 
988 	/*
989 	 * Permit one packet in or out per rekey - this allows us to
990 	 * make progress when rekey limits are very small.
991 	 */
992 	if (state->p_send.packets == 0 && state->p_read.packets == 0)
993 		return 0;
994 
995 	/* Time-based rekeying */
996 	if (state->rekey_interval != 0 &&
997 	    (int64_t)state->rekey_time + state->rekey_interval <= monotime())
998 		return 1;
999 
1000 	/*
1001 	 * Always rekey when MAX_PACKETS sent in either direction
1002 	 * As per RFC4344 section 3.1 we do this after 2^31 packets.
1003 	 */
1004 	if (state->p_send.packets > MAX_PACKETS ||
1005 	    state->p_read.packets > MAX_PACKETS)
1006 		return 1;
1007 
1008 	/* Rekey after (cipher-specific) maximum blocks */
1009 	out_blocks = ROUNDUP(outbound_packet_len,
1010 	    state->newkeys[MODE_OUT]->enc.block_size);
1011 	return (state->max_blocks_out &&
1012 	    (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
1013 	    (state->max_blocks_in &&
1014 	    (state->p_read.blocks > state->max_blocks_in));
1015 }
1016 
1017 /*
1018  * Delayed compression for SSH2 is enabled after authentication:
1019  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1020  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1021  */
1022 static int
1023 ssh_packet_enable_delayed_compress(struct ssh *ssh)
1024 {
1025 	struct session_state *state = ssh->state;
1026 	struct sshcomp *comp = NULL;
1027 	int r, mode;
1028 
1029 	/*
1030 	 * Remember that we are past the authentication step, so rekeying
1031 	 * with COMP_DELAYED will turn on compression immediately.
1032 	 */
1033 	state->after_authentication = 1;
1034 	for (mode = 0; mode < MODE_MAX; mode++) {
1035 		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1036 		if (state->newkeys[mode] == NULL)
1037 			continue;
1038 		comp = &state->newkeys[mode]->comp;
1039 		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1040 			if ((r = ssh_packet_init_compression(ssh)) != 0)
1041 				return r;
1042 			if (mode == MODE_OUT) {
1043 				if ((r = start_compression_out(ssh, 6)) != 0)
1044 					return r;
1045 			} else {
1046 				if ((r = start_compression_in(ssh)) != 0)
1047 					return r;
1048 			}
1049 			comp->enabled = 1;
1050 		}
1051 	}
1052 	return 0;
1053 }
1054 
1055 /* Used to mute debug logging for noisy packet types */
1056 int
1057 ssh_packet_log_type(u_char type)
1058 {
1059 	switch (type) {
1060 	case SSH2_MSG_CHANNEL_DATA:
1061 	case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1062 	case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1063 		return 0;
1064 	default:
1065 		return 1;
1066 	}
1067 }
1068 
1069 /*
1070  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1071  */
1072 int
1073 ssh_packet_send2_wrapped(struct ssh *ssh)
1074 {
1075 	struct session_state *state = ssh->state;
1076 	u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1077 	u_char tmp, padlen, pad = 0;
1078 	u_int authlen = 0, aadlen = 0;
1079 	u_int len;
1080 	struct sshenc *enc   = NULL;
1081 	struct sshmac *mac   = NULL;
1082 	struct sshcomp *comp = NULL;
1083 	int r, block_size;
1084 
1085 	if (state->newkeys[MODE_OUT] != NULL) {
1086 		enc  = &state->newkeys[MODE_OUT]->enc;
1087 		mac  = &state->newkeys[MODE_OUT]->mac;
1088 		comp = &state->newkeys[MODE_OUT]->comp;
1089 		/* disable mac for authenticated encryption */
1090 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
1091 			mac = NULL;
1092 	}
1093 	block_size = enc ? enc->block_size : 8;
1094 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1095 
1096 	type = (sshbuf_ptr(state->outgoing_packet))[5];
1097 	if (ssh_packet_log_type(type))
1098 		debug3("send packet: type %u", type);
1099 #ifdef PACKET_DEBUG
1100 	fprintf(stderr, "plain:     ");
1101 	sshbuf_dump(state->outgoing_packet, stderr);
1102 #endif
1103 
1104 	if (comp && comp->enabled) {
1105 		len = sshbuf_len(state->outgoing_packet);
1106 		/* skip header, compress only payload */
1107 		if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1108 			goto out;
1109 		sshbuf_reset(state->compression_buffer);
1110 		if ((r = compress_buffer(ssh, state->outgoing_packet,
1111 		    state->compression_buffer)) != 0)
1112 			goto out;
1113 		sshbuf_reset(state->outgoing_packet);
1114 		if ((r = sshbuf_put(state->outgoing_packet,
1115 		    "\0\0\0\0\0", 5)) != 0 ||
1116 		    (r = sshbuf_putb(state->outgoing_packet,
1117 		    state->compression_buffer)) != 0)
1118 			goto out;
1119 		DBG(debug("compression: raw %d compressed %zd", len,
1120 		    sshbuf_len(state->outgoing_packet)));
1121 	}
1122 
1123 	/* sizeof (packet_len + pad_len + payload) */
1124 	len = sshbuf_len(state->outgoing_packet);
1125 
1126 	/*
1127 	 * calc size of padding, alloc space, get random data,
1128 	 * minimum padding is 4 bytes
1129 	 */
1130 	len -= aadlen; /* packet length is not encrypted for EtM modes */
1131 	padlen = block_size - (len % block_size);
1132 	if (padlen < 4)
1133 		padlen += block_size;
1134 	if (state->extra_pad) {
1135 		tmp = state->extra_pad;
1136 		state->extra_pad =
1137 		    ROUNDUP(state->extra_pad, block_size);
1138 		/* check if roundup overflowed */
1139 		if (state->extra_pad < tmp)
1140 			return SSH_ERR_INVALID_ARGUMENT;
1141 		tmp = (len + padlen) % state->extra_pad;
1142 		/* Check whether pad calculation below will underflow */
1143 		if (tmp > state->extra_pad)
1144 			return SSH_ERR_INVALID_ARGUMENT;
1145 		pad = state->extra_pad - tmp;
1146 		DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
1147 		    __func__, pad, len, padlen, state->extra_pad));
1148 		tmp = padlen;
1149 		padlen += pad;
1150 		/* Check whether padlen calculation overflowed */
1151 		if (padlen < tmp)
1152 			return SSH_ERR_INVALID_ARGUMENT; /* overflow */
1153 		state->extra_pad = 0;
1154 	}
1155 	if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1156 		goto out;
1157 	if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
1158 		/* random padding */
1159 		arc4random_buf(cp, padlen);
1160 	} else {
1161 		/* clear padding */
1162 		explicit_bzero(cp, padlen);
1163 	}
1164 	/* sizeof (packet_len + pad_len + payload + padding) */
1165 	len = sshbuf_len(state->outgoing_packet);
1166 	cp = sshbuf_mutable_ptr(state->outgoing_packet);
1167 	if (cp == NULL) {
1168 		r = SSH_ERR_INTERNAL_ERROR;
1169 		goto out;
1170 	}
1171 	/* packet_length includes payload, padding and padding length field */
1172 	POKE_U32(cp, len - 4);
1173 	cp[4] = padlen;
1174 	DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1175 	    len, padlen, aadlen));
1176 
1177 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
1178 	if (mac && mac->enabled && !mac->etm) {
1179 		if ((r = mac_compute(mac, state->p_send.seqnr,
1180 		    sshbuf_ptr(state->outgoing_packet), len,
1181 		    macbuf, sizeof(macbuf))) != 0)
1182 			goto out;
1183 		DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1184 	}
1185 	/* encrypt packet and append to output buffer. */
1186 	if ((r = sshbuf_reserve(state->output,
1187 	    sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1188 		goto out;
1189 	if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
1190 	    sshbuf_ptr(state->outgoing_packet),
1191 	    len - aadlen, aadlen, authlen)) != 0)
1192 		goto out;
1193 	/* append unencrypted MAC */
1194 	if (mac && mac->enabled) {
1195 		if (mac->etm) {
1196 			/* EtM: compute mac over aadlen + cipher text */
1197 			if ((r = mac_compute(mac, state->p_send.seqnr,
1198 			    cp, len, macbuf, sizeof(macbuf))) != 0)
1199 				goto out;
1200 			DBG(debug("done calc MAC(EtM) out #%d",
1201 			    state->p_send.seqnr));
1202 		}
1203 		if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1204 			goto out;
1205 	}
1206 #ifdef PACKET_DEBUG
1207 	fprintf(stderr, "encrypted: ");
1208 	sshbuf_dump(state->output, stderr);
1209 #endif
1210 	/* increment sequence number for outgoing packets */
1211 	if (++state->p_send.seqnr == 0)
1212 		logit("outgoing seqnr wraps around");
1213 	if (++state->p_send.packets == 0)
1214 		if (!(ssh->compat & SSH_BUG_NOREKEY))
1215 			return SSH_ERR_NEED_REKEY;
1216 	state->p_send.blocks += len / block_size;
1217 	state->p_send.bytes += len;
1218 	sshbuf_reset(state->outgoing_packet);
1219 
1220 	if (type == SSH2_MSG_NEWKEYS)
1221 		r = ssh_set_newkeys(ssh, MODE_OUT);
1222 	else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1223 		r = ssh_packet_enable_delayed_compress(ssh);
1224 	else
1225 		r = 0;
1226  out:
1227 	return r;
1228 }
1229 
1230 /* returns non-zero if the specified packet type is usec by KEX */
1231 static int
1232 ssh_packet_type_is_kex(u_char type)
1233 {
1234 	return
1235 	    type >= SSH2_MSG_TRANSPORT_MIN &&
1236 	    type <= SSH2_MSG_TRANSPORT_MAX &&
1237 	    type != SSH2_MSG_SERVICE_REQUEST &&
1238 	    type != SSH2_MSG_SERVICE_ACCEPT &&
1239 	    type != SSH2_MSG_EXT_INFO;
1240 }
1241 
1242 int
1243 ssh_packet_send2(struct ssh *ssh)
1244 {
1245 	struct session_state *state = ssh->state;
1246 	struct packet *p;
1247 	u_char type;
1248 	int r, need_rekey;
1249 
1250 	if (sshbuf_len(state->outgoing_packet) < 6)
1251 		return SSH_ERR_INTERNAL_ERROR;
1252 	type = sshbuf_ptr(state->outgoing_packet)[5];
1253 	need_rekey = !ssh_packet_type_is_kex(type) &&
1254 	    ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1255 
1256 	/*
1257 	 * During rekeying we can only send key exchange messages.
1258 	 * Queue everything else.
1259 	 */
1260 	if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
1261 		if (need_rekey)
1262 			debug3("%s: rekex triggered", __func__);
1263 		debug("enqueue packet: %u", type);
1264 		p = calloc(1, sizeof(*p));
1265 		if (p == NULL)
1266 			return SSH_ERR_ALLOC_FAIL;
1267 		p->type = type;
1268 		p->payload = state->outgoing_packet;
1269 		TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1270 		state->outgoing_packet = sshbuf_new();
1271 		if (state->outgoing_packet == NULL)
1272 			return SSH_ERR_ALLOC_FAIL;
1273 		if (need_rekey) {
1274 			/*
1275 			 * This packet triggered a rekey, so send the
1276 			 * KEXINIT now.
1277 			 * NB. reenters this function via kex_start_rekex().
1278 			 */
1279 			return kex_start_rekex(ssh);
1280 		}
1281 		return 0;
1282 	}
1283 
1284 	/* rekeying starts with sending KEXINIT */
1285 	if (type == SSH2_MSG_KEXINIT)
1286 		state->rekeying = 1;
1287 
1288 	if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1289 		return r;
1290 
1291 	/* after a NEWKEYS message we can send the complete queue */
1292 	if (type == SSH2_MSG_NEWKEYS) {
1293 		state->rekeying = 0;
1294 		state->rekey_time = monotime();
1295 		while ((p = TAILQ_FIRST(&state->outgoing))) {
1296 			type = p->type;
1297 			/*
1298 			 * If this packet triggers a rekex, then skip the
1299 			 * remaining packets in the queue for now.
1300 			 * NB. re-enters this function via kex_start_rekex.
1301 			 */
1302 			if (ssh_packet_need_rekeying(ssh,
1303 			    sshbuf_len(p->payload))) {
1304 				debug3("%s: queued packet triggered rekex",
1305 				    __func__);
1306 				return kex_start_rekex(ssh);
1307 			}
1308 			debug("dequeue packet: %u", type);
1309 			sshbuf_free(state->outgoing_packet);
1310 			state->outgoing_packet = p->payload;
1311 			TAILQ_REMOVE(&state->outgoing, p, next);
1312 			memset(p, 0, sizeof(*p));
1313 			free(p);
1314 			if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1315 				return r;
1316 		}
1317 	}
1318 	return 0;
1319 }
1320 
1321 /*
1322  * Waits until a packet has been received, and returns its type.  Note that
1323  * no other data is processed until this returns, so this function should not
1324  * be used during the interactive session.
1325  */
1326 
1327 int
1328 ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1329 {
1330 	struct session_state *state = ssh->state;
1331 	int len, r, ms_remain;
1332 	fd_set *setp;
1333 	char buf[8192];
1334 	struct timeval timeout, start, *timeoutp = NULL;
1335 
1336 	DBG(debug("packet_read()"));
1337 
1338 	setp = calloc(howmany(state->connection_in + 1,
1339 	    NFDBITS), sizeof(fd_mask));
1340 	if (setp == NULL)
1341 		return SSH_ERR_ALLOC_FAIL;
1342 
1343 	/*
1344 	 * Since we are blocking, ensure that all written packets have
1345 	 * been sent.
1346 	 */
1347 	if ((r = ssh_packet_write_wait(ssh)) != 0)
1348 		goto out;
1349 
1350 	/* Stay in the loop until we have received a complete packet. */
1351 	for (;;) {
1352 		/* Try to read a packet from the buffer. */
1353 		r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
1354 		if (r != 0)
1355 			break;
1356 		/* If we got a packet, return it. */
1357 		if (*typep != SSH_MSG_NONE)
1358 			break;
1359 		/*
1360 		 * Otherwise, wait for some data to arrive, add it to the
1361 		 * buffer, and try again.
1362 		 */
1363 		memset(setp, 0, howmany(state->connection_in + 1,
1364 		    NFDBITS) * sizeof(fd_mask));
1365 		FD_SET(state->connection_in, setp);
1366 
1367 		if (state->packet_timeout_ms > 0) {
1368 			ms_remain = state->packet_timeout_ms;
1369 			timeoutp = &timeout;
1370 		}
1371 		/* Wait for some data to arrive. */
1372 		for (;;) {
1373 			if (state->packet_timeout_ms > 0) {
1374 				ms_to_timeval(&timeout, ms_remain);
1375 				monotime_tv(&start);
1376 			}
1377 			if ((r = select(state->connection_in + 1, setp,
1378 			    NULL, NULL, timeoutp)) >= 0)
1379 				break;
1380 			if (errno != EAGAIN && errno != EINTR &&
1381 			    errno != EWOULDBLOCK) {
1382 				r = SSH_ERR_SYSTEM_ERROR;
1383 				goto out;
1384 			}
1385 			if (state->packet_timeout_ms <= 0)
1386 				continue;
1387 			ms_subtract_diff(&start, &ms_remain);
1388 			if (ms_remain <= 0) {
1389 				r = 0;
1390 				break;
1391 			}
1392 		}
1393 		if (r == 0) {
1394 			r = SSH_ERR_CONN_TIMEOUT;
1395 			goto out;
1396 		}
1397 		/* Read data from the socket. */
1398 		len = read(state->connection_in, buf, sizeof(buf));
1399 		if (len == 0) {
1400 			r = SSH_ERR_CONN_CLOSED;
1401 			goto out;
1402 		}
1403 		if (len == -1) {
1404 			r = SSH_ERR_SYSTEM_ERROR;
1405 			goto out;
1406 		}
1407 
1408 		/* Append it to the buffer. */
1409 		if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1410 			goto out;
1411 	}
1412  out:
1413 	free(setp);
1414 	return r;
1415 }
1416 
1417 int
1418 ssh_packet_read(struct ssh *ssh)
1419 {
1420 	u_char type;
1421 	int r;
1422 
1423 	if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1424 		fatal("%s: %s", __func__, ssh_err(r));
1425 	return type;
1426 }
1427 
1428 /*
1429  * Waits until a packet has been received, verifies that its type matches
1430  * that given, and gives a fatal error and exits if there is a mismatch.
1431  */
1432 
1433 int
1434 ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
1435 {
1436 	int r;
1437 	u_char type;
1438 
1439 	if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1440 		return r;
1441 	if (type != expected_type) {
1442 		if ((r = sshpkt_disconnect(ssh,
1443 		    "Protocol error: expected packet type %d, got %d",
1444 		    expected_type, type)) != 0)
1445 			return r;
1446 		return SSH_ERR_PROTOCOL_ERROR;
1447 	}
1448 	return 0;
1449 }
1450 
1451 static int
1452 ssh_packet_read_poll2_mux(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1453 {
1454 	struct session_state *state = ssh->state;
1455 	const u_char *cp;
1456 	size_t need;
1457 	int r;
1458 
1459 	if (ssh->kex)
1460 		return SSH_ERR_INTERNAL_ERROR;
1461 	*typep = SSH_MSG_NONE;
1462 	cp = sshbuf_ptr(state->input);
1463 	if (state->packlen == 0) {
1464 		if (sshbuf_len(state->input) < 4 + 1)
1465 			return 0; /* packet is incomplete */
1466 		state->packlen = PEEK_U32(cp);
1467 		if (state->packlen < 4 + 1 ||
1468 		    state->packlen > PACKET_MAX_SIZE)
1469 			return SSH_ERR_MESSAGE_INCOMPLETE;
1470 	}
1471 	need = state->packlen + 4;
1472 	if (sshbuf_len(state->input) < need)
1473 		return 0; /* packet is incomplete */
1474 	sshbuf_reset(state->incoming_packet);
1475 	if ((r = sshbuf_put(state->incoming_packet, cp + 4,
1476 	    state->packlen)) != 0 ||
1477 	    (r = sshbuf_consume(state->input, need)) != 0 ||
1478 	    (r = sshbuf_get_u8(state->incoming_packet, NULL)) != 0 ||
1479 	    (r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1480 		return r;
1481 	if (ssh_packet_log_type(*typep))
1482 		debug3("%s: type %u", __func__, *typep);
1483 	/* sshbuf_dump(state->incoming_packet, stderr); */
1484 	/* reset for next packet */
1485 	state->packlen = 0;
1486 	return r;
1487 }
1488 
1489 int
1490 ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1491 {
1492 	struct session_state *state = ssh->state;
1493 	u_int padlen, need;
1494 	u_char *cp;
1495 	u_int maclen, aadlen = 0, authlen = 0, block_size;
1496 	struct sshenc *enc   = NULL;
1497 	struct sshmac *mac   = NULL;
1498 	struct sshcomp *comp = NULL;
1499 	int r;
1500 
1501 	if (state->mux)
1502 		return ssh_packet_read_poll2_mux(ssh, typep, seqnr_p);
1503 
1504 	*typep = SSH_MSG_NONE;
1505 
1506 	if (state->packet_discard)
1507 		return 0;
1508 
1509 	if (state->newkeys[MODE_IN] != NULL) {
1510 		enc  = &state->newkeys[MODE_IN]->enc;
1511 		mac  = &state->newkeys[MODE_IN]->mac;
1512 		comp = &state->newkeys[MODE_IN]->comp;
1513 		/* disable mac for authenticated encryption */
1514 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
1515 			mac = NULL;
1516 	}
1517 	maclen = mac && mac->enabled ? mac->mac_len : 0;
1518 	block_size = enc ? enc->block_size : 8;
1519 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1520 
1521 	if (aadlen && state->packlen == 0) {
1522 		if (cipher_get_length(state->receive_context,
1523 		    &state->packlen, state->p_read.seqnr,
1524 		    sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
1525 			return 0;
1526 		if (state->packlen < 1 + 4 ||
1527 		    state->packlen > PACKET_MAX_SIZE) {
1528 #ifdef PACKET_DEBUG
1529 			sshbuf_dump(state->input, stderr);
1530 #endif
1531 			logit("Bad packet length %u.", state->packlen);
1532 			if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1533 				return r;
1534 			return SSH_ERR_CONN_CORRUPT;
1535 		}
1536 		sshbuf_reset(state->incoming_packet);
1537 	} else if (state->packlen == 0) {
1538 		/*
1539 		 * check if input size is less than the cipher block size,
1540 		 * decrypt first block and extract length of incoming packet
1541 		 */
1542 		if (sshbuf_len(state->input) < block_size)
1543 			return 0;
1544 		sshbuf_reset(state->incoming_packet);
1545 		if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1546 		    &cp)) != 0)
1547 			goto out;
1548 		if ((r = cipher_crypt(state->receive_context,
1549 		    state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1550 		    block_size, 0, 0)) != 0)
1551 			goto out;
1552 		state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1553 		if (state->packlen < 1 + 4 ||
1554 		    state->packlen > PACKET_MAX_SIZE) {
1555 #ifdef PACKET_DEBUG
1556 			fprintf(stderr, "input: \n");
1557 			sshbuf_dump(state->input, stderr);
1558 			fprintf(stderr, "incoming_packet: \n");
1559 			sshbuf_dump(state->incoming_packet, stderr);
1560 #endif
1561 			logit("Bad packet length %u.", state->packlen);
1562 			return ssh_packet_start_discard(ssh, enc, mac, 0,
1563 			    PACKET_MAX_SIZE);
1564 		}
1565 		if ((r = sshbuf_consume(state->input, block_size)) != 0)
1566 			goto out;
1567 	}
1568 	DBG(debug("input: packet len %u", state->packlen+4));
1569 
1570 	if (aadlen) {
1571 		/* only the payload is encrypted */
1572 		need = state->packlen;
1573 	} else {
1574 		/*
1575 		 * the payload size and the payload are encrypted, but we
1576 		 * have a partial packet of block_size bytes
1577 		 */
1578 		need = 4 + state->packlen - block_size;
1579 	}
1580 	DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1581 	    " aadlen %d", block_size, need, maclen, authlen, aadlen));
1582 	if (need % block_size != 0) {
1583 		logit("padding error: need %d block %d mod %d",
1584 		    need, block_size, need % block_size);
1585 		return ssh_packet_start_discard(ssh, enc, mac, 0,
1586 		    PACKET_MAX_SIZE - block_size);
1587 	}
1588 	/*
1589 	 * check if the entire packet has been received and
1590 	 * decrypt into incoming_packet:
1591 	 * 'aadlen' bytes are unencrypted, but authenticated.
1592 	 * 'need' bytes are encrypted, followed by either
1593 	 * 'authlen' bytes of authentication tag or
1594 	 * 'maclen' bytes of message authentication code.
1595 	 */
1596 	if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1597 		return 0; /* packet is incomplete */
1598 #ifdef PACKET_DEBUG
1599 	fprintf(stderr, "read_poll enc/full: ");
1600 	sshbuf_dump(state->input, stderr);
1601 #endif
1602 	/* EtM: check mac over encrypted input */
1603 	if (mac && mac->enabled && mac->etm) {
1604 		if ((r = mac_check(mac, state->p_read.seqnr,
1605 		    sshbuf_ptr(state->input), aadlen + need,
1606 		    sshbuf_ptr(state->input) + aadlen + need + authlen,
1607 		    maclen)) != 0) {
1608 			if (r == SSH_ERR_MAC_INVALID)
1609 				logit("Corrupted MAC on input.");
1610 			goto out;
1611 		}
1612 	}
1613 	if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1614 	    &cp)) != 0)
1615 		goto out;
1616 	if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
1617 	    sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1618 		goto out;
1619 	if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1620 		goto out;
1621 	if (mac && mac->enabled) {
1622 		/* Not EtM: check MAC over cleartext */
1623 		if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
1624 		    sshbuf_ptr(state->incoming_packet),
1625 		    sshbuf_len(state->incoming_packet),
1626 		    sshbuf_ptr(state->input), maclen)) != 0) {
1627 			if (r != SSH_ERR_MAC_INVALID)
1628 				goto out;
1629 			logit("Corrupted MAC on input.");
1630 			if (need + block_size > PACKET_MAX_SIZE)
1631 				return SSH_ERR_INTERNAL_ERROR;
1632 			return ssh_packet_start_discard(ssh, enc, mac,
1633 			    sshbuf_len(state->incoming_packet),
1634 			    PACKET_MAX_SIZE - need - block_size);
1635 		}
1636 		/* Remove MAC from input buffer */
1637 		DBG(debug("MAC #%d ok", state->p_read.seqnr));
1638 		if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1639 			goto out;
1640 	}
1641 	if (seqnr_p != NULL)
1642 		*seqnr_p = state->p_read.seqnr;
1643 	if (++state->p_read.seqnr == 0)
1644 		logit("incoming seqnr wraps around");
1645 	if (++state->p_read.packets == 0)
1646 		if (!(ssh->compat & SSH_BUG_NOREKEY))
1647 			return SSH_ERR_NEED_REKEY;
1648 	state->p_read.blocks += (state->packlen + 4) / block_size;
1649 	state->p_read.bytes += state->packlen + 4;
1650 
1651 	/* get padlen */
1652 	padlen = sshbuf_ptr(state->incoming_packet)[4];
1653 	DBG(debug("input: padlen %d", padlen));
1654 	if (padlen < 4)	{
1655 		if ((r = sshpkt_disconnect(ssh,
1656 		    "Corrupted padlen %d on input.", padlen)) != 0 ||
1657 		    (r = ssh_packet_write_wait(ssh)) != 0)
1658 			return r;
1659 		return SSH_ERR_CONN_CORRUPT;
1660 	}
1661 
1662 	/* skip packet size + padlen, discard padding */
1663 	if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1664 	    ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1665 		goto out;
1666 
1667 	DBG(debug("input: len before de-compress %zd",
1668 	    sshbuf_len(state->incoming_packet)));
1669 	if (comp && comp->enabled) {
1670 		sshbuf_reset(state->compression_buffer);
1671 		if ((r = uncompress_buffer(ssh, state->incoming_packet,
1672 		    state->compression_buffer)) != 0)
1673 			goto out;
1674 		sshbuf_reset(state->incoming_packet);
1675 		if ((r = sshbuf_putb(state->incoming_packet,
1676 		    state->compression_buffer)) != 0)
1677 			goto out;
1678 		DBG(debug("input: len after de-compress %zd",
1679 		    sshbuf_len(state->incoming_packet)));
1680 	}
1681 	/*
1682 	 * get packet type, implies consume.
1683 	 * return length of payload (without type field)
1684 	 */
1685 	if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1686 		goto out;
1687 	if (ssh_packet_log_type(*typep))
1688 		debug3("receive packet: type %u", *typep);
1689 	if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
1690 		if ((r = sshpkt_disconnect(ssh,
1691 		    "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1692 		    (r = ssh_packet_write_wait(ssh)) != 0)
1693 			return r;
1694 		return SSH_ERR_PROTOCOL_ERROR;
1695 	}
1696 	if (state->hook_in != NULL &&
1697 	    (r = state->hook_in(ssh, state->incoming_packet, typep,
1698 	    state->hook_in_ctx)) != 0)
1699 		return r;
1700 	if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1701 		r = ssh_packet_enable_delayed_compress(ssh);
1702 	else
1703 		r = 0;
1704 #ifdef PACKET_DEBUG
1705 	fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1706 	sshbuf_dump(state->incoming_packet, stderr);
1707 #endif
1708 	/* reset for next packet */
1709 	state->packlen = 0;
1710 
1711 	/* do we need to rekey? */
1712 	if (ssh_packet_need_rekeying(ssh, 0)) {
1713 		debug3("%s: rekex triggered", __func__);
1714 		if ((r = kex_start_rekex(ssh)) != 0)
1715 			return r;
1716 	}
1717  out:
1718 	return r;
1719 }
1720 
1721 int
1722 ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1723 {
1724 	struct session_state *state = ssh->state;
1725 	u_int reason, seqnr;
1726 	int r;
1727 	u_char *msg;
1728 
1729 	for (;;) {
1730 		msg = NULL;
1731 		r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1732 		if (r != 0)
1733 			return r;
1734 		if (*typep) {
1735 			state->keep_alive_timeouts = 0;
1736 			DBG(debug("received packet type %d", *typep));
1737 		}
1738 		switch (*typep) {
1739 		case SSH2_MSG_IGNORE:
1740 			debug3("Received SSH2_MSG_IGNORE");
1741 			break;
1742 		case SSH2_MSG_DEBUG:
1743 			if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1744 			    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1745 			    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1746 				free(msg);
1747 				return r;
1748 			}
1749 			debug("Remote: %.900s", msg);
1750 			free(msg);
1751 			break;
1752 		case SSH2_MSG_DISCONNECT:
1753 			if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1754 			    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1755 				return r;
1756 			/* Ignore normal client exit notifications */
1757 			do_log2(ssh->state->server_side &&
1758 			    reason == SSH2_DISCONNECT_BY_APPLICATION ?
1759 			    SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1760 			    "Received disconnect from %s port %d:"
1761 			    "%u: %.400s", ssh_remote_ipaddr(ssh),
1762 			    ssh_remote_port(ssh), reason, msg);
1763 			free(msg);
1764 			return SSH_ERR_DISCONNECTED;
1765 		case SSH2_MSG_UNIMPLEMENTED:
1766 			if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1767 				return r;
1768 			debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1769 			    seqnr);
1770 			break;
1771 		default:
1772 			return 0;
1773 		}
1774 	}
1775 }
1776 
1777 /*
1778  * Buffers the given amount of input characters.  This is intended to be used
1779  * together with packet_read_poll.
1780  */
1781 
1782 int
1783 ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
1784 {
1785 	struct session_state *state = ssh->state;
1786 	int r;
1787 
1788 	if (state->packet_discard) {
1789 		state->keep_alive_timeouts = 0; /* ?? */
1790 		if (len >= state->packet_discard) {
1791 			if ((r = ssh_packet_stop_discard(ssh)) != 0)
1792 				return r;
1793 		}
1794 		state->packet_discard -= len;
1795 		return 0;
1796 	}
1797 	if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
1798 		return r;
1799 
1800 	return 0;
1801 }
1802 
1803 int
1804 ssh_packet_remaining(struct ssh *ssh)
1805 {
1806 	return sshbuf_len(ssh->state->incoming_packet);
1807 }
1808 
1809 /*
1810  * Sends a diagnostic message from the server to the client.  This message
1811  * can be sent at any time (but not while constructing another message). The
1812  * message is printed immediately, but only if the client is being executed
1813  * in verbose mode.  These messages are primarily intended to ease debugging
1814  * authentication problems.   The length of the formatted message must not
1815  * exceed 1024 bytes.  This will automatically call ssh_packet_write_wait.
1816  */
1817 void
1818 ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
1819 {
1820 	char buf[1024];
1821 	va_list args;
1822 	int r;
1823 
1824 	if ((ssh->compat & SSH_BUG_DEBUG))
1825 		return;
1826 
1827 	va_start(args, fmt);
1828 	vsnprintf(buf, sizeof(buf), fmt, args);
1829 	va_end(args);
1830 
1831 	debug3("sending debug message: %s", buf);
1832 
1833 	if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
1834 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
1835 	    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
1836 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1837 	    (r = sshpkt_send(ssh)) != 0 ||
1838 	    (r = ssh_packet_write_wait(ssh)) != 0)
1839 		fatal("%s: %s", __func__, ssh_err(r));
1840 }
1841 
1842 void
1843 sshpkt_fmt_connection_id(struct ssh *ssh, char *s, size_t l)
1844 {
1845 	snprintf(s, l, "%.200s%s%s port %d",
1846 	    ssh->log_preamble ? ssh->log_preamble : "",
1847 	    ssh->log_preamble ? " " : "",
1848 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1849 }
1850 
1851 /*
1852  * Pretty-print connection-terminating errors and exit.
1853  */
1854 static void
1855 sshpkt_vfatal(struct ssh *ssh, int r, const char *fmt, va_list ap)
1856 {
1857 	char *tag = NULL, remote_id[512];
1858 	int oerrno = errno;
1859 
1860 	sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1861 
1862 	switch (r) {
1863 	case SSH_ERR_CONN_CLOSED:
1864 		ssh_packet_clear_keys(ssh);
1865 		logdie("Connection closed by %s", remote_id);
1866 	case SSH_ERR_CONN_TIMEOUT:
1867 		ssh_packet_clear_keys(ssh);
1868 		logdie("Connection %s %s timed out",
1869 		    ssh->state->server_side ? "from" : "to", remote_id);
1870 	case SSH_ERR_DISCONNECTED:
1871 		ssh_packet_clear_keys(ssh);
1872 		logdie("Disconnected from %s", remote_id);
1873 	case SSH_ERR_SYSTEM_ERROR:
1874 		if (errno == ECONNRESET) {
1875 			ssh_packet_clear_keys(ssh);
1876 			logdie("Connection reset by %s", remote_id);
1877 		}
1878 		/* FALLTHROUGH */
1879 	case SSH_ERR_NO_CIPHER_ALG_MATCH:
1880 	case SSH_ERR_NO_MAC_ALG_MATCH:
1881 	case SSH_ERR_NO_COMPRESS_ALG_MATCH:
1882 	case SSH_ERR_NO_KEX_ALG_MATCH:
1883 	case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
1884 		if (ssh && ssh->kex && ssh->kex->failed_choice) {
1885 			ssh_packet_clear_keys(ssh);
1886 			errno = oerrno;
1887 			logdie("Unable to negotiate with %s: %s. "
1888 			    "Their offer: %s", remote_id, ssh_err(r),
1889 			    ssh->kex->failed_choice);
1890 		}
1891 		/* FALLTHROUGH */
1892 	default:
1893 		if (vasprintf(&tag, fmt, ap) == -1) {
1894 			ssh_packet_clear_keys(ssh);
1895 			logdie("%s: could not allocate failure message",
1896 			    __func__);
1897 		}
1898 		ssh_packet_clear_keys(ssh);
1899 		errno = oerrno;
1900 		logdie("%s%sConnection %s %s: %s",
1901 		    tag != NULL ? tag : "", tag != NULL ? ": " : "",
1902 		    ssh->state->server_side ? "from" : "to",
1903 		    remote_id, ssh_err(r));
1904 	}
1905 }
1906 
1907 void
1908 sshpkt_fatal(struct ssh *ssh, int r, const char *fmt, ...)
1909 {
1910 	va_list ap;
1911 
1912 	va_start(ap, fmt);
1913 	sshpkt_vfatal(ssh, r, fmt, ap);
1914 	/* NOTREACHED */
1915 	va_end(ap);
1916 	logdie("%s: should have exited", __func__);
1917 }
1918 
1919 /*
1920  * Logs the error plus constructs and sends a disconnect packet, closes the
1921  * connection, and exits.  This function never returns. The error message
1922  * should not contain a newline.  The length of the formatted message must
1923  * not exceed 1024 bytes.
1924  */
1925 void
1926 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
1927 {
1928 	char buf[1024], remote_id[512];
1929 	va_list args;
1930 	static int disconnecting = 0;
1931 	int r;
1932 
1933 	if (disconnecting)	/* Guard against recursive invocations. */
1934 		fatal("packet_disconnect called recursively.");
1935 	disconnecting = 1;
1936 
1937 	/*
1938 	 * Format the message.  Note that the caller must make sure the
1939 	 * message is of limited size.
1940 	 */
1941 	sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1942 	va_start(args, fmt);
1943 	vsnprintf(buf, sizeof(buf), fmt, args);
1944 	va_end(args);
1945 
1946 	/* Display the error locally */
1947 	logit("Disconnecting %s: %.100s", remote_id, buf);
1948 
1949 	/*
1950 	 * Send the disconnect message to the other side, and wait
1951 	 * for it to get sent.
1952 	 */
1953 	if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
1954 		sshpkt_fatal(ssh, r, "%s", __func__);
1955 
1956 	if ((r = ssh_packet_write_wait(ssh)) != 0)
1957 		sshpkt_fatal(ssh, r, "%s", __func__);
1958 
1959 	/* Close the connection. */
1960 	ssh_packet_close(ssh);
1961 	cleanup_exit(255);
1962 }
1963 
1964 /*
1965  * Checks if there is any buffered output, and tries to write some of
1966  * the output.
1967  */
1968 int
1969 ssh_packet_write_poll(struct ssh *ssh)
1970 {
1971 	struct session_state *state = ssh->state;
1972 	int len = sshbuf_len(state->output);
1973 	int r;
1974 
1975 	if (len > 0) {
1976 		len = write(state->connection_out,
1977 		    sshbuf_ptr(state->output), len);
1978 		if (len == -1) {
1979 			if (errno == EINTR || errno == EAGAIN ||
1980 			    errno == EWOULDBLOCK)
1981 				return 0;
1982 			return SSH_ERR_SYSTEM_ERROR;
1983 		}
1984 		if (len == 0)
1985 			return SSH_ERR_CONN_CLOSED;
1986 		if ((r = sshbuf_consume(state->output, len)) != 0)
1987 			return r;
1988 	}
1989 	return 0;
1990 }
1991 
1992 /*
1993  * Calls packet_write_poll repeatedly until all pending output data has been
1994  * written.
1995  */
1996 int
1997 ssh_packet_write_wait(struct ssh *ssh)
1998 {
1999 	fd_set *setp;
2000 	int ret, r, ms_remain = 0;
2001 	struct timeval start, timeout, *timeoutp = NULL;
2002 	struct session_state *state = ssh->state;
2003 
2004 	setp = calloc(howmany(state->connection_out + 1,
2005 	    NFDBITS), sizeof(fd_mask));
2006 	if (setp == NULL)
2007 		return SSH_ERR_ALLOC_FAIL;
2008 	if ((r = ssh_packet_write_poll(ssh)) != 0) {
2009 		free(setp);
2010 		return r;
2011 	}
2012 	while (ssh_packet_have_data_to_write(ssh)) {
2013 		memset(setp, 0, howmany(state->connection_out + 1,
2014 		    NFDBITS) * sizeof(fd_mask));
2015 		FD_SET(state->connection_out, setp);
2016 
2017 		if (state->packet_timeout_ms > 0) {
2018 			ms_remain = state->packet_timeout_ms;
2019 			timeoutp = &timeout;
2020 		}
2021 		for (;;) {
2022 			if (state->packet_timeout_ms > 0) {
2023 				ms_to_timeval(&timeout, ms_remain);
2024 				monotime_tv(&start);
2025 			}
2026 			if ((ret = select(state->connection_out + 1,
2027 			    NULL, setp, NULL, timeoutp)) >= 0)
2028 				break;
2029 			if (errno != EAGAIN && errno != EINTR &&
2030 			    errno != EWOULDBLOCK)
2031 				break;
2032 			if (state->packet_timeout_ms <= 0)
2033 				continue;
2034 			ms_subtract_diff(&start, &ms_remain);
2035 			if (ms_remain <= 0) {
2036 				ret = 0;
2037 				break;
2038 			}
2039 		}
2040 		if (ret == 0) {
2041 			free(setp);
2042 			return SSH_ERR_CONN_TIMEOUT;
2043 		}
2044 		if ((r = ssh_packet_write_poll(ssh)) != 0) {
2045 			free(setp);
2046 			return r;
2047 		}
2048 	}
2049 	free(setp);
2050 	return 0;
2051 }
2052 
2053 /* Returns true if there is buffered data to write to the connection. */
2054 
2055 int
2056 ssh_packet_have_data_to_write(struct ssh *ssh)
2057 {
2058 	return sshbuf_len(ssh->state->output) != 0;
2059 }
2060 
2061 /* Returns true if there is not too much data to write to the connection. */
2062 
2063 int
2064 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2065 {
2066 	if (ssh->state->interactive_mode)
2067 		return sshbuf_len(ssh->state->output) < 16384;
2068 	else
2069 		return sshbuf_len(ssh->state->output) < 128 * 1024;
2070 }
2071 
2072 void
2073 ssh_packet_set_tos(struct ssh *ssh, int tos)
2074 {
2075 #ifndef IP_TOS_IS_BROKEN
2076 	if (!ssh_packet_connection_is_on_socket(ssh) || tos == INT_MAX)
2077 		return;
2078 	switch (ssh_packet_connection_af(ssh)) {
2079 # ifdef IP_TOS
2080 	case AF_INET:
2081 		debug3("%s: set IP_TOS 0x%02x", __func__, tos);
2082 		if (setsockopt(ssh->state->connection_in,
2083 		    IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) == -1)
2084 			error("setsockopt IP_TOS %d: %.100s:",
2085 			    tos, strerror(errno));
2086 		break;
2087 # endif /* IP_TOS */
2088 # ifdef IPV6_TCLASS
2089 	case AF_INET6:
2090 		debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
2091 		if (setsockopt(ssh->state->connection_in,
2092 		    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) == -1)
2093 			error("setsockopt IPV6_TCLASS %d: %.100s:",
2094 			    tos, strerror(errno));
2095 		break;
2096 # endif /* IPV6_TCLASS */
2097 	}
2098 #endif /* IP_TOS_IS_BROKEN */
2099 }
2100 
2101 /* Informs that the current session is interactive.  Sets IP flags for that. */
2102 
2103 void
2104 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
2105 {
2106 	struct session_state *state = ssh->state;
2107 
2108 	if (state->set_interactive_called)
2109 		return;
2110 	state->set_interactive_called = 1;
2111 
2112 	/* Record that we are in interactive mode. */
2113 	state->interactive_mode = interactive;
2114 
2115 	/* Only set socket options if using a socket.  */
2116 	if (!ssh_packet_connection_is_on_socket(ssh))
2117 		return;
2118 	set_nodelay(state->connection_in);
2119 	ssh_packet_set_tos(ssh, interactive ? qos_interactive :
2120 	    qos_bulk);
2121 }
2122 
2123 /* Returns true if the current connection is interactive. */
2124 
2125 int
2126 ssh_packet_is_interactive(struct ssh *ssh)
2127 {
2128 	return ssh->state->interactive_mode;
2129 }
2130 
2131 int
2132 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2133 {
2134 	struct session_state *state = ssh->state;
2135 
2136 	if (state->set_maxsize_called) {
2137 		logit("packet_set_maxsize: called twice: old %d new %d",
2138 		    state->max_packet_size, s);
2139 		return -1;
2140 	}
2141 	if (s < 4 * 1024 || s > 1024 * 1024) {
2142 		logit("packet_set_maxsize: bad size %d", s);
2143 		return -1;
2144 	}
2145 	state->set_maxsize_called = 1;
2146 	debug("packet_set_maxsize: setting to %d", s);
2147 	state->max_packet_size = s;
2148 	return s;
2149 }
2150 
2151 int
2152 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2153 {
2154 	return ++ssh->state->keep_alive_timeouts;
2155 }
2156 
2157 void
2158 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2159 {
2160 	ssh->state->keep_alive_timeouts = ka;
2161 }
2162 
2163 u_int
2164 ssh_packet_get_maxsize(struct ssh *ssh)
2165 {
2166 	return ssh->state->max_packet_size;
2167 }
2168 
2169 void
2170 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, u_int32_t seconds)
2171 {
2172 	debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
2173 	    (unsigned int)seconds);
2174 	ssh->state->rekey_limit = bytes;
2175 	ssh->state->rekey_interval = seconds;
2176 }
2177 
2178 time_t
2179 ssh_packet_get_rekey_timeout(struct ssh *ssh)
2180 {
2181 	time_t seconds;
2182 
2183 	seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2184 	    monotime();
2185 	return (seconds <= 0 ? 1 : seconds);
2186 }
2187 
2188 void
2189 ssh_packet_set_server(struct ssh *ssh)
2190 {
2191 	ssh->state->server_side = 1;
2192 	ssh->kex->server = 1; /* XXX unify? */
2193 }
2194 
2195 void
2196 ssh_packet_set_authenticated(struct ssh *ssh)
2197 {
2198 	ssh->state->after_authentication = 1;
2199 }
2200 
2201 void *
2202 ssh_packet_get_input(struct ssh *ssh)
2203 {
2204 	return (void *)ssh->state->input;
2205 }
2206 
2207 void *
2208 ssh_packet_get_output(struct ssh *ssh)
2209 {
2210 	return (void *)ssh->state->output;
2211 }
2212 
2213 /* Reset after_authentication and reset compression in post-auth privsep */
2214 static int
2215 ssh_packet_set_postauth(struct ssh *ssh)
2216 {
2217 	int r;
2218 
2219 	debug("%s: called", __func__);
2220 	/* This was set in net child, but is not visible in user child */
2221 	ssh->state->after_authentication = 1;
2222 	ssh->state->rekeying = 0;
2223 	if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
2224 		return r;
2225 	return 0;
2226 }
2227 
2228 /* Packet state (de-)serialization for privsep */
2229 
2230 /* turn kex into a blob for packet state serialization */
2231 static int
2232 kex_to_blob(struct sshbuf *m, struct kex *kex)
2233 {
2234 	int r;
2235 
2236 	if ((r = sshbuf_put_string(m, kex->session_id,
2237 	    kex->session_id_len)) != 0 ||
2238 	    (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2239 	    (r = sshbuf_put_cstring(m, kex->hostkey_alg)) != 0 ||
2240 	    (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2241 	    (r = sshbuf_put_u32(m, kex->hostkey_nid)) != 0 ||
2242 	    (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2243 	    (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2244 	    (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2245 	    (r = sshbuf_put_stringb(m, kex->client_version)) != 0 ||
2246 	    (r = sshbuf_put_stringb(m, kex->server_version)) != 0 ||
2247 	    (r = sshbuf_put_u32(m, kex->flags)) != 0)
2248 		return r;
2249 	return 0;
2250 }
2251 
2252 /* turn key exchange results into a blob for packet state serialization */
2253 static int
2254 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2255 {
2256 	struct sshbuf *b;
2257 	struct sshcipher_ctx *cc;
2258 	struct sshcomp *comp;
2259 	struct sshenc *enc;
2260 	struct sshmac *mac;
2261 	struct newkeys *newkey;
2262 	int r;
2263 
2264 	if ((newkey = ssh->state->newkeys[mode]) == NULL)
2265 		return SSH_ERR_INTERNAL_ERROR;
2266 	enc = &newkey->enc;
2267 	mac = &newkey->mac;
2268 	comp = &newkey->comp;
2269 	cc = (mode == MODE_OUT) ? ssh->state->send_context :
2270 	    ssh->state->receive_context;
2271 	if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2272 		return r;
2273 	if ((b = sshbuf_new()) == NULL)
2274 		return SSH_ERR_ALLOC_FAIL;
2275 	if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2276 	    (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2277 	    (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2278 	    (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2279 	    (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2280 		goto out;
2281 	if (cipher_authlen(enc->cipher) == 0) {
2282 		if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2283 		    (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2284 		    (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2285 			goto out;
2286 	}
2287 	if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2288 	    (r = sshbuf_put_cstring(b, comp->name)) != 0)
2289 		goto out;
2290 	r = sshbuf_put_stringb(m, b);
2291  out:
2292 	sshbuf_free(b);
2293 	return r;
2294 }
2295 
2296 /* serialize packet state into a blob */
2297 int
2298 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2299 {
2300 	struct session_state *state = ssh->state;
2301 	int r;
2302 
2303 	if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2304 	    (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2305 	    (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2306 	    (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2307 	    (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2308 	    (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2309 	    (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2310 	    (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2311 	    (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2312 	    (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2313 	    (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2314 	    (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2315 	    (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0 ||
2316 	    (r = sshbuf_put_stringb(m, state->input)) != 0 ||
2317 	    (r = sshbuf_put_stringb(m, state->output)) != 0)
2318 		return r;
2319 
2320 	return 0;
2321 }
2322 
2323 /* restore key exchange results from blob for packet state de-serialization */
2324 static int
2325 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2326 {
2327 	struct sshbuf *b = NULL;
2328 	struct sshcomp *comp;
2329 	struct sshenc *enc;
2330 	struct sshmac *mac;
2331 	struct newkeys *newkey = NULL;
2332 	size_t keylen, ivlen, maclen;
2333 	int r;
2334 
2335 	if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2336 		r = SSH_ERR_ALLOC_FAIL;
2337 		goto out;
2338 	}
2339 	if ((r = sshbuf_froms(m, &b)) != 0)
2340 		goto out;
2341 #ifdef DEBUG_PK
2342 	sshbuf_dump(b, stderr);
2343 #endif
2344 	enc = &newkey->enc;
2345 	mac = &newkey->mac;
2346 	comp = &newkey->comp;
2347 
2348 	if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2349 	    (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2350 	    (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2351 	    (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2352 	    (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2353 		goto out;
2354 	if ((enc->cipher = cipher_by_name(enc->name)) == NULL) {
2355 		r = SSH_ERR_INVALID_FORMAT;
2356 		goto out;
2357 	}
2358 	if (cipher_authlen(enc->cipher) == 0) {
2359 		if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2360 			goto out;
2361 		if ((r = mac_setup(mac, mac->name)) != 0)
2362 			goto out;
2363 		if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2364 		    (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2365 			goto out;
2366 		if (maclen > mac->key_len) {
2367 			r = SSH_ERR_INVALID_FORMAT;
2368 			goto out;
2369 		}
2370 		mac->key_len = maclen;
2371 	}
2372 	if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2373 	    (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2374 		goto out;
2375 	if (sshbuf_len(b) != 0) {
2376 		r = SSH_ERR_INVALID_FORMAT;
2377 		goto out;
2378 	}
2379 	enc->key_len = keylen;
2380 	enc->iv_len = ivlen;
2381 	ssh->kex->newkeys[mode] = newkey;
2382 	newkey = NULL;
2383 	r = 0;
2384  out:
2385 	free(newkey);
2386 	sshbuf_free(b);
2387 	return r;
2388 }
2389 
2390 /* restore kex from blob for packet state de-serialization */
2391 static int
2392 kex_from_blob(struct sshbuf *m, struct kex **kexp)
2393 {
2394 	struct kex *kex;
2395 	int r;
2396 
2397 	if ((kex = kex_new()) == NULL)
2398 		return SSH_ERR_ALLOC_FAIL;
2399 	if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
2400 	    (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2401 	    (r = sshbuf_get_cstring(m, &kex->hostkey_alg, NULL)) != 0 ||
2402 	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2403 	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_nid)) != 0 ||
2404 	    (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2405 	    (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2406 	    (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2407 	    (r = sshbuf_get_stringb(m, kex->client_version)) != 0 ||
2408 	    (r = sshbuf_get_stringb(m, kex->server_version)) != 0 ||
2409 	    (r = sshbuf_get_u32(m, &kex->flags)) != 0)
2410 		goto out;
2411 	kex->server = 1;
2412 	kex->done = 1;
2413 	r = 0;
2414  out:
2415 	if (r != 0 || kexp == NULL) {
2416 		kex_free(kex);
2417 		if (kexp != NULL)
2418 			*kexp = NULL;
2419 	} else {
2420 		kex_free(*kexp);
2421 		*kexp = kex;
2422 	}
2423 	return r;
2424 }
2425 
2426 /*
2427  * Restore packet state from content of blob 'm' (de-serialization).
2428  * Note that 'm' will be partially consumed on parsing or any other errors.
2429  */
2430 int
2431 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2432 {
2433 	struct session_state *state = ssh->state;
2434 	const u_char *input, *output;
2435 	size_t ilen, olen;
2436 	int r;
2437 
2438 	if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2439 	    (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2440 	    (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2441 	    (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2442 	    (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2443 	    (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2444 	    (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2445 	    (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2446 	    (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2447 	    (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2448 	    (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2449 	    (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2450 	    (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2451 		return r;
2452 	/*
2453 	 * We set the time here so that in post-auth privsep slave we
2454 	 * count from the completion of the authentication.
2455 	 */
2456 	state->rekey_time = monotime();
2457 	/* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2458 	if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2459 	    (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2460 		return r;
2461 
2462 	if ((r = ssh_packet_set_postauth(ssh)) != 0)
2463 		return r;
2464 
2465 	sshbuf_reset(state->input);
2466 	sshbuf_reset(state->output);
2467 	if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2468 	    (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2469 	    (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2470 	    (r = sshbuf_put(state->output, output, olen)) != 0)
2471 		return r;
2472 
2473 	if (sshbuf_len(m))
2474 		return SSH_ERR_INVALID_FORMAT;
2475 	debug3("%s: done", __func__);
2476 	return 0;
2477 }
2478 
2479 /* NEW API */
2480 
2481 /* put data to the outgoing packet */
2482 
2483 int
2484 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2485 {
2486 	return sshbuf_put(ssh->state->outgoing_packet, v, len);
2487 }
2488 
2489 int
2490 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2491 {
2492 	return sshbuf_putb(ssh->state->outgoing_packet, b);
2493 }
2494 
2495 int
2496 sshpkt_put_u8(struct ssh *ssh, u_char val)
2497 {
2498 	return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2499 }
2500 
2501 int
2502 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2503 {
2504 	return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2505 }
2506 
2507 int
2508 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2509 {
2510 	return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2511 }
2512 
2513 int
2514 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2515 {
2516 	return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2517 }
2518 
2519 int
2520 sshpkt_put_cstring(struct ssh *ssh, const void *v)
2521 {
2522 	return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2523 }
2524 
2525 int
2526 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2527 {
2528 	return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2529 }
2530 
2531 int
2532 sshpkt_getb_froms(struct ssh *ssh, struct sshbuf **valp)
2533 {
2534 	return sshbuf_froms(ssh->state->incoming_packet, valp);
2535 }
2536 
2537 #ifdef WITH_OPENSSL
2538 #ifdef OPENSSL_HAS_ECC
2539 int
2540 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2541 {
2542 	return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2543 }
2544 #endif /* OPENSSL_HAS_ECC */
2545 
2546 
2547 int
2548 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2549 {
2550 	return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2551 }
2552 #endif /* WITH_OPENSSL */
2553 
2554 /* fetch data from the incoming packet */
2555 
2556 int
2557 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2558 {
2559 	return sshbuf_get(ssh->state->incoming_packet, valp, len);
2560 }
2561 
2562 int
2563 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2564 {
2565 	return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2566 }
2567 
2568 int
2569 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2570 {
2571 	return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2572 }
2573 
2574 int
2575 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2576 {
2577 	return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2578 }
2579 
2580 int
2581 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2582 {
2583 	return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2584 }
2585 
2586 int
2587 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2588 {
2589 	return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2590 }
2591 
2592 int
2593 sshpkt_peek_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2594 {
2595 	return sshbuf_peek_string_direct(ssh->state->incoming_packet, valp, lenp);
2596 }
2597 
2598 int
2599 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2600 {
2601 	return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2602 }
2603 
2604 #ifdef WITH_OPENSSL
2605 #ifdef OPENSSL_HAS_ECC
2606 int
2607 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2608 {
2609 	return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2610 }
2611 #endif /* OPENSSL_HAS_ECC */
2612 
2613 int
2614 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM **valp)
2615 {
2616 	return sshbuf_get_bignum2(ssh->state->incoming_packet, valp);
2617 }
2618 #endif /* WITH_OPENSSL */
2619 
2620 int
2621 sshpkt_get_end(struct ssh *ssh)
2622 {
2623 	if (sshbuf_len(ssh->state->incoming_packet) > 0)
2624 		return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2625 	return 0;
2626 }
2627 
2628 const u_char *
2629 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2630 {
2631 	if (lenp != NULL)
2632 		*lenp = sshbuf_len(ssh->state->incoming_packet);
2633 	return sshbuf_ptr(ssh->state->incoming_packet);
2634 }
2635 
2636 /* start a new packet */
2637 
2638 int
2639 sshpkt_start(struct ssh *ssh, u_char type)
2640 {
2641 	u_char buf[6]; /* u32 packet length, u8 pad len, u8 type */
2642 
2643 	DBG(debug("packet_start[%d]", type));
2644 	memset(buf, 0, sizeof(buf));
2645 	buf[sizeof(buf) - 1] = type;
2646 	sshbuf_reset(ssh->state->outgoing_packet);
2647 	return sshbuf_put(ssh->state->outgoing_packet, buf, sizeof(buf));
2648 }
2649 
2650 static int
2651 ssh_packet_send_mux(struct ssh *ssh)
2652 {
2653 	struct session_state *state = ssh->state;
2654 	u_char type, *cp;
2655 	size_t len;
2656 	int r;
2657 
2658 	if (ssh->kex)
2659 		return SSH_ERR_INTERNAL_ERROR;
2660 	len = sshbuf_len(state->outgoing_packet);
2661 	if (len < 6)
2662 		return SSH_ERR_INTERNAL_ERROR;
2663 	cp = sshbuf_mutable_ptr(state->outgoing_packet);
2664 	type = cp[5];
2665 	if (ssh_packet_log_type(type))
2666 		debug3("%s: type %u", __func__, type);
2667 	/* drop everything, but the connection protocol */
2668 	if (type >= SSH2_MSG_CONNECTION_MIN &&
2669 	    type <= SSH2_MSG_CONNECTION_MAX) {
2670 		POKE_U32(cp, len - 4);
2671 		if ((r = sshbuf_putb(state->output,
2672 		    state->outgoing_packet)) != 0)
2673 			return r;
2674 		/* sshbuf_dump(state->output, stderr); */
2675 	}
2676 	sshbuf_reset(state->outgoing_packet);
2677 	return 0;
2678 }
2679 
2680 /*
2681  * 9.2.  Ignored Data Message
2682  *
2683  *   byte      SSH_MSG_IGNORE
2684  *   string    data
2685  *
2686  * All implementations MUST understand (and ignore) this message at any
2687  * time (after receiving the protocol version). No implementation is
2688  * required to send them. This message can be used as an additional
2689  * protection measure against advanced traffic analysis techniques.
2690  */
2691 int
2692 sshpkt_msg_ignore(struct ssh *ssh, u_int nbytes)
2693 {
2694 	u_int32_t rnd = 0;
2695 	int r;
2696 	u_int i;
2697 
2698 	if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2699 	    (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2700 		return r;
2701 	for (i = 0; i < nbytes; i++) {
2702 		if (i % 4 == 0)
2703 			rnd = arc4random();
2704 		if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2705 			return r;
2706 		rnd >>= 8;
2707 	}
2708 	return 0;
2709 }
2710 
2711 /* send it */
2712 
2713 int
2714 sshpkt_send(struct ssh *ssh)
2715 {
2716 	if (ssh->state && ssh->state->mux)
2717 		return ssh_packet_send_mux(ssh);
2718 	return ssh_packet_send2(ssh);
2719 }
2720 
2721 int
2722 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
2723 {
2724 	char buf[1024];
2725 	va_list args;
2726 	int r;
2727 
2728 	va_start(args, fmt);
2729 	vsnprintf(buf, sizeof(buf), fmt, args);
2730 	va_end(args);
2731 
2732 	if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
2733 	    (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
2734 	    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2735 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2736 	    (r = sshpkt_send(ssh)) != 0)
2737 		return r;
2738 	return 0;
2739 }
2740 
2741 /* roundup current message to pad bytes */
2742 int
2743 sshpkt_add_padding(struct ssh *ssh, u_char pad)
2744 {
2745 	ssh->state->extra_pad = pad;
2746 	return 0;
2747 }
2748