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