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