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