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