xref: /freebsd/crypto/openssh/packet.c (revision 53b70c86)
1 /* $OpenBSD: packet.c,v 1.301 2021/07/16 09:00:23 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_PARTIAL_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("set_newkeys: 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_context: %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 	fd_set *setp;
1331 	char buf[8192];
1332 	struct timeval timeout, start, *timeoutp = NULL;
1333 
1334 	DBG(debug("packet_read()"));
1335 
1336 	setp = calloc(howmany(state->connection_in + 1,
1337 	    NFDBITS), sizeof(fd_mask));
1338 	if (setp == NULL)
1339 		return SSH_ERR_ALLOC_FAIL;
1340 
1341 	/*
1342 	 * Since we are blocking, ensure that all written packets have
1343 	 * been sent.
1344 	 */
1345 	if ((r = ssh_packet_write_wait(ssh)) != 0)
1346 		goto out;
1347 
1348 	/* Stay in the loop until we have received a complete packet. */
1349 	for (;;) {
1350 		/* Try to read a packet from the buffer. */
1351 		r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
1352 		if (r != 0)
1353 			break;
1354 		/* If we got a packet, return it. */
1355 		if (*typep != SSH_MSG_NONE)
1356 			break;
1357 		/*
1358 		 * Otherwise, wait for some data to arrive, add it to the
1359 		 * buffer, and try again.
1360 		 */
1361 		memset(setp, 0, howmany(state->connection_in + 1,
1362 		    NFDBITS) * sizeof(fd_mask));
1363 		FD_SET(state->connection_in, setp);
1364 
1365 		if (state->packet_timeout_ms > 0) {
1366 			ms_remain = state->packet_timeout_ms;
1367 			timeoutp = &timeout;
1368 		}
1369 		/* Wait for some data to arrive. */
1370 		for (;;) {
1371 			if (state->packet_timeout_ms > 0) {
1372 				ms_to_timeval(&timeout, ms_remain);
1373 				monotime_tv(&start);
1374 			}
1375 			if ((r = select(state->connection_in + 1, setp,
1376 			    NULL, NULL, timeoutp)) >= 0)
1377 				break;
1378 			if (errno != EAGAIN && errno != EINTR &&
1379 			    errno != EWOULDBLOCK) {
1380 				r = SSH_ERR_SYSTEM_ERROR;
1381 				goto out;
1382 			}
1383 			if (state->packet_timeout_ms <= 0)
1384 				continue;
1385 			ms_subtract_diff(&start, &ms_remain);
1386 			if (ms_remain <= 0) {
1387 				r = 0;
1388 				break;
1389 			}
1390 		}
1391 		if (r == 0) {
1392 			r = SSH_ERR_CONN_TIMEOUT;
1393 			goto out;
1394 		}
1395 		/* Read data from the socket. */
1396 		len = read(state->connection_in, buf, sizeof(buf));
1397 		if (len == 0) {
1398 			r = SSH_ERR_CONN_CLOSED;
1399 			goto out;
1400 		}
1401 		if (len == -1) {
1402 			r = SSH_ERR_SYSTEM_ERROR;
1403 			goto out;
1404 		}
1405 
1406 		/* Append it to the buffer. */
1407 		if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1408 			goto out;
1409 	}
1410  out:
1411 	free(setp);
1412 	return r;
1413 }
1414 
1415 int
1416 ssh_packet_read(struct ssh *ssh)
1417 {
1418 	u_char type;
1419 	int r;
1420 
1421 	if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1422 		fatal_fr(r, "read");
1423 	return type;
1424 }
1425 
1426 /*
1427  * Waits until a packet has been received, verifies that its type matches
1428  * that given, and gives a fatal error and exits if there is a mismatch.
1429  */
1430 
1431 int
1432 ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
1433 {
1434 	int r;
1435 	u_char type;
1436 
1437 	if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1438 		return r;
1439 	if (type != expected_type) {
1440 		if ((r = sshpkt_disconnect(ssh,
1441 		    "Protocol error: expected packet type %d, got %d",
1442 		    expected_type, type)) != 0)
1443 			return r;
1444 		return SSH_ERR_PROTOCOL_ERROR;
1445 	}
1446 	return 0;
1447 }
1448 
1449 static int
1450 ssh_packet_read_poll2_mux(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1451 {
1452 	struct session_state *state = ssh->state;
1453 	const u_char *cp;
1454 	size_t need;
1455 	int r;
1456 
1457 	if (ssh->kex)
1458 		return SSH_ERR_INTERNAL_ERROR;
1459 	*typep = SSH_MSG_NONE;
1460 	cp = sshbuf_ptr(state->input);
1461 	if (state->packlen == 0) {
1462 		if (sshbuf_len(state->input) < 4 + 1)
1463 			return 0; /* packet is incomplete */
1464 		state->packlen = PEEK_U32(cp);
1465 		if (state->packlen < 4 + 1 ||
1466 		    state->packlen > PACKET_MAX_SIZE)
1467 			return SSH_ERR_MESSAGE_INCOMPLETE;
1468 	}
1469 	need = state->packlen + 4;
1470 	if (sshbuf_len(state->input) < need)
1471 		return 0; /* packet is incomplete */
1472 	sshbuf_reset(state->incoming_packet);
1473 	if ((r = sshbuf_put(state->incoming_packet, cp + 4,
1474 	    state->packlen)) != 0 ||
1475 	    (r = sshbuf_consume(state->input, need)) != 0 ||
1476 	    (r = sshbuf_get_u8(state->incoming_packet, NULL)) != 0 ||
1477 	    (r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1478 		return r;
1479 	if (ssh_packet_log_type(*typep))
1480 		debug3_f("type %u", *typep);
1481 	/* sshbuf_dump(state->incoming_packet, stderr); */
1482 	/* reset for next packet */
1483 	state->packlen = 0;
1484 	return r;
1485 }
1486 
1487 int
1488 ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1489 {
1490 	struct session_state *state = ssh->state;
1491 	u_int padlen, need;
1492 	u_char *cp;
1493 	u_int maclen, aadlen = 0, authlen = 0, block_size;
1494 	struct sshenc *enc   = NULL;
1495 	struct sshmac *mac   = NULL;
1496 	struct sshcomp *comp = NULL;
1497 	int r;
1498 
1499 	if (state->mux)
1500 		return ssh_packet_read_poll2_mux(ssh, typep, seqnr_p);
1501 
1502 	*typep = SSH_MSG_NONE;
1503 
1504 	if (state->packet_discard)
1505 		return 0;
1506 
1507 	if (state->newkeys[MODE_IN] != NULL) {
1508 		enc  = &state->newkeys[MODE_IN]->enc;
1509 		mac  = &state->newkeys[MODE_IN]->mac;
1510 		comp = &state->newkeys[MODE_IN]->comp;
1511 		/* disable mac for authenticated encryption */
1512 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
1513 			mac = NULL;
1514 	}
1515 	maclen = mac && mac->enabled ? mac->mac_len : 0;
1516 	block_size = enc ? enc->block_size : 8;
1517 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1518 
1519 	if (aadlen && state->packlen == 0) {
1520 		if (cipher_get_length(state->receive_context,
1521 		    &state->packlen, state->p_read.seqnr,
1522 		    sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
1523 			return 0;
1524 		if (state->packlen < 1 + 4 ||
1525 		    state->packlen > PACKET_MAX_SIZE) {
1526 #ifdef PACKET_DEBUG
1527 			sshbuf_dump(state->input, stderr);
1528 #endif
1529 			logit("Bad packet length %u.", state->packlen);
1530 			if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1531 				return r;
1532 			return SSH_ERR_CONN_CORRUPT;
1533 		}
1534 		sshbuf_reset(state->incoming_packet);
1535 	} else if (state->packlen == 0) {
1536 		/*
1537 		 * check if input size is less than the cipher block size,
1538 		 * decrypt first block and extract length of incoming packet
1539 		 */
1540 		if (sshbuf_len(state->input) < block_size)
1541 			return 0;
1542 		sshbuf_reset(state->incoming_packet);
1543 		if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1544 		    &cp)) != 0)
1545 			goto out;
1546 		if ((r = cipher_crypt(state->receive_context,
1547 		    state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1548 		    block_size, 0, 0)) != 0)
1549 			goto out;
1550 		state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1551 		if (state->packlen < 1 + 4 ||
1552 		    state->packlen > PACKET_MAX_SIZE) {
1553 #ifdef PACKET_DEBUG
1554 			fprintf(stderr, "input: \n");
1555 			sshbuf_dump(state->input, stderr);
1556 			fprintf(stderr, "incoming_packet: \n");
1557 			sshbuf_dump(state->incoming_packet, stderr);
1558 #endif
1559 			logit("Bad packet length %u.", state->packlen);
1560 			return ssh_packet_start_discard(ssh, enc, mac, 0,
1561 			    PACKET_MAX_SIZE);
1562 		}
1563 		if ((r = sshbuf_consume(state->input, block_size)) != 0)
1564 			goto out;
1565 	}
1566 	DBG(debug("input: packet len %u", state->packlen+4));
1567 
1568 	if (aadlen) {
1569 		/* only the payload is encrypted */
1570 		need = state->packlen;
1571 	} else {
1572 		/*
1573 		 * the payload size and the payload are encrypted, but we
1574 		 * have a partial packet of block_size bytes
1575 		 */
1576 		need = 4 + state->packlen - block_size;
1577 	}
1578 	DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1579 	    " aadlen %d", block_size, need, maclen, authlen, aadlen));
1580 	if (need % block_size != 0) {
1581 		logit("padding error: need %d block %d mod %d",
1582 		    need, block_size, need % block_size);
1583 		return ssh_packet_start_discard(ssh, enc, mac, 0,
1584 		    PACKET_MAX_SIZE - block_size);
1585 	}
1586 	/*
1587 	 * check if the entire packet has been received and
1588 	 * decrypt into incoming_packet:
1589 	 * 'aadlen' bytes are unencrypted, but authenticated.
1590 	 * 'need' bytes are encrypted, followed by either
1591 	 * 'authlen' bytes of authentication tag or
1592 	 * 'maclen' bytes of message authentication code.
1593 	 */
1594 	if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1595 		return 0; /* packet is incomplete */
1596 #ifdef PACKET_DEBUG
1597 	fprintf(stderr, "read_poll enc/full: ");
1598 	sshbuf_dump(state->input, stderr);
1599 #endif
1600 	/* EtM: check mac over encrypted input */
1601 	if (mac && mac->enabled && mac->etm) {
1602 		if ((r = mac_check(mac, state->p_read.seqnr,
1603 		    sshbuf_ptr(state->input), aadlen + need,
1604 		    sshbuf_ptr(state->input) + aadlen + need + authlen,
1605 		    maclen)) != 0) {
1606 			if (r == SSH_ERR_MAC_INVALID)
1607 				logit("Corrupted MAC on input.");
1608 			goto out;
1609 		}
1610 	}
1611 	if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1612 	    &cp)) != 0)
1613 		goto out;
1614 	if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
1615 	    sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1616 		goto out;
1617 	if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1618 		goto out;
1619 	if (mac && mac->enabled) {
1620 		/* Not EtM: check MAC over cleartext */
1621 		if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
1622 		    sshbuf_ptr(state->incoming_packet),
1623 		    sshbuf_len(state->incoming_packet),
1624 		    sshbuf_ptr(state->input), maclen)) != 0) {
1625 			if (r != SSH_ERR_MAC_INVALID)
1626 				goto out;
1627 			logit("Corrupted MAC on input.");
1628 			if (need + block_size > PACKET_MAX_SIZE)
1629 				return SSH_ERR_INTERNAL_ERROR;
1630 			return ssh_packet_start_discard(ssh, enc, mac,
1631 			    sshbuf_len(state->incoming_packet),
1632 			    PACKET_MAX_SIZE - need - block_size);
1633 		}
1634 		/* Remove MAC from input buffer */
1635 		DBG(debug("MAC #%d ok", state->p_read.seqnr));
1636 		if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1637 			goto out;
1638 	}
1639 	if (seqnr_p != NULL)
1640 		*seqnr_p = state->p_read.seqnr;
1641 	if (++state->p_read.seqnr == 0)
1642 		logit("incoming seqnr wraps around");
1643 	if (++state->p_read.packets == 0)
1644 		if (!(ssh->compat & SSH_BUG_NOREKEY))
1645 			return SSH_ERR_NEED_REKEY;
1646 	state->p_read.blocks += (state->packlen + 4) / block_size;
1647 	state->p_read.bytes += state->packlen + 4;
1648 
1649 	/* get padlen */
1650 	padlen = sshbuf_ptr(state->incoming_packet)[4];
1651 	DBG(debug("input: padlen %d", padlen));
1652 	if (padlen < 4)	{
1653 		if ((r = sshpkt_disconnect(ssh,
1654 		    "Corrupted padlen %d on input.", padlen)) != 0 ||
1655 		    (r = ssh_packet_write_wait(ssh)) != 0)
1656 			return r;
1657 		return SSH_ERR_CONN_CORRUPT;
1658 	}
1659 
1660 	/* skip packet size + padlen, discard padding */
1661 	if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1662 	    ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1663 		goto out;
1664 
1665 	DBG(debug("input: len before de-compress %zd",
1666 	    sshbuf_len(state->incoming_packet)));
1667 	if (comp && comp->enabled) {
1668 		sshbuf_reset(state->compression_buffer);
1669 		if ((r = uncompress_buffer(ssh, state->incoming_packet,
1670 		    state->compression_buffer)) != 0)
1671 			goto out;
1672 		sshbuf_reset(state->incoming_packet);
1673 		if ((r = sshbuf_putb(state->incoming_packet,
1674 		    state->compression_buffer)) != 0)
1675 			goto out;
1676 		DBG(debug("input: len after de-compress %zd",
1677 		    sshbuf_len(state->incoming_packet)));
1678 	}
1679 	/*
1680 	 * get packet type, implies consume.
1681 	 * return length of payload (without type field)
1682 	 */
1683 	if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1684 		goto out;
1685 	if (ssh_packet_log_type(*typep))
1686 		debug3("receive packet: type %u", *typep);
1687 	if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
1688 		if ((r = sshpkt_disconnect(ssh,
1689 		    "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1690 		    (r = ssh_packet_write_wait(ssh)) != 0)
1691 			return r;
1692 		return SSH_ERR_PROTOCOL_ERROR;
1693 	}
1694 	if (state->hook_in != NULL &&
1695 	    (r = state->hook_in(ssh, state->incoming_packet, typep,
1696 	    state->hook_in_ctx)) != 0)
1697 		return r;
1698 	if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1699 		r = ssh_packet_enable_delayed_compress(ssh);
1700 	else
1701 		r = 0;
1702 #ifdef PACKET_DEBUG
1703 	fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1704 	sshbuf_dump(state->incoming_packet, stderr);
1705 #endif
1706 	/* reset for next packet */
1707 	state->packlen = 0;
1708 
1709 	if ((r = ssh_packet_check_rekey(ssh)) != 0)
1710 		return r;
1711  out:
1712 	return r;
1713 }
1714 
1715 int
1716 ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1717 {
1718 	struct session_state *state = ssh->state;
1719 	u_int reason, seqnr;
1720 	int r;
1721 	u_char *msg;
1722 
1723 	for (;;) {
1724 		msg = NULL;
1725 		r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1726 		if (r != 0)
1727 			return r;
1728 		if (*typep) {
1729 			state->keep_alive_timeouts = 0;
1730 			DBG(debug("received packet type %d", *typep));
1731 		}
1732 		switch (*typep) {
1733 		case SSH2_MSG_IGNORE:
1734 			debug3("Received SSH2_MSG_IGNORE");
1735 			break;
1736 		case SSH2_MSG_DEBUG:
1737 			if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1738 			    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1739 			    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1740 				free(msg);
1741 				return r;
1742 			}
1743 			debug("Remote: %.900s", msg);
1744 			free(msg);
1745 			break;
1746 		case SSH2_MSG_DISCONNECT:
1747 			if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1748 			    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1749 				return r;
1750 			/* Ignore normal client exit notifications */
1751 			do_log2(ssh->state->server_side &&
1752 			    reason == SSH2_DISCONNECT_BY_APPLICATION ?
1753 			    SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1754 			    "Received disconnect from %s port %d:"
1755 			    "%u: %.400s", ssh_remote_ipaddr(ssh),
1756 			    ssh_remote_port(ssh), reason, msg);
1757 			free(msg);
1758 			return SSH_ERR_DISCONNECTED;
1759 		case SSH2_MSG_UNIMPLEMENTED:
1760 			if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1761 				return r;
1762 			debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1763 			    seqnr);
1764 			break;
1765 		default:
1766 			return 0;
1767 		}
1768 	}
1769 }
1770 
1771 /*
1772  * Buffers the given amount of input characters.  This is intended to be used
1773  * together with packet_read_poll.
1774  */
1775 
1776 int
1777 ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
1778 {
1779 	struct session_state *state = ssh->state;
1780 	int r;
1781 
1782 	if (state->packet_discard) {
1783 		state->keep_alive_timeouts = 0; /* ?? */
1784 		if (len >= state->packet_discard) {
1785 			if ((r = ssh_packet_stop_discard(ssh)) != 0)
1786 				return r;
1787 		}
1788 		state->packet_discard -= len;
1789 		return 0;
1790 	}
1791 	if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
1792 		return r;
1793 
1794 	return 0;
1795 }
1796 
1797 int
1798 ssh_packet_remaining(struct ssh *ssh)
1799 {
1800 	return sshbuf_len(ssh->state->incoming_packet);
1801 }
1802 
1803 /*
1804  * Sends a diagnostic message from the server to the client.  This message
1805  * can be sent at any time (but not while constructing another message). The
1806  * message is printed immediately, but only if the client is being executed
1807  * in verbose mode.  These messages are primarily intended to ease debugging
1808  * authentication problems.   The length of the formatted message must not
1809  * exceed 1024 bytes.  This will automatically call ssh_packet_write_wait.
1810  */
1811 void
1812 ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
1813 {
1814 	char buf[1024];
1815 	va_list args;
1816 	int r;
1817 
1818 	if ((ssh->compat & SSH_BUG_DEBUG))
1819 		return;
1820 
1821 	va_start(args, fmt);
1822 	vsnprintf(buf, sizeof(buf), fmt, args);
1823 	va_end(args);
1824 
1825 	debug3("sending debug message: %s", buf);
1826 
1827 	if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
1828 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
1829 	    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
1830 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1831 	    (r = sshpkt_send(ssh)) != 0 ||
1832 	    (r = ssh_packet_write_wait(ssh)) != 0)
1833 		fatal_fr(r, "send DEBUG");
1834 }
1835 
1836 void
1837 sshpkt_fmt_connection_id(struct ssh *ssh, char *s, size_t l)
1838 {
1839 	snprintf(s, l, "%.200s%s%s port %d",
1840 	    ssh->log_preamble ? ssh->log_preamble : "",
1841 	    ssh->log_preamble ? " " : "",
1842 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1843 }
1844 
1845 /*
1846  * Pretty-print connection-terminating errors and exit.
1847  */
1848 static void
1849 sshpkt_vfatal(struct ssh *ssh, int r, const char *fmt, va_list ap)
1850 {
1851 	char *tag = NULL, remote_id[512];
1852 	int oerrno = errno;
1853 
1854 	sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1855 
1856 	switch (r) {
1857 	case SSH_ERR_CONN_CLOSED:
1858 		ssh_packet_clear_keys(ssh);
1859 		logdie("Connection closed by %s", remote_id);
1860 	case SSH_ERR_CONN_TIMEOUT:
1861 		ssh_packet_clear_keys(ssh);
1862 		logdie("Connection %s %s timed out",
1863 		    ssh->state->server_side ? "from" : "to", remote_id);
1864 	case SSH_ERR_DISCONNECTED:
1865 		ssh_packet_clear_keys(ssh);
1866 		logdie("Disconnected from %s", remote_id);
1867 	case SSH_ERR_SYSTEM_ERROR:
1868 		if (errno == ECONNRESET) {
1869 			ssh_packet_clear_keys(ssh);
1870 			logdie("Connection reset by %s", remote_id);
1871 		}
1872 		/* FALLTHROUGH */
1873 	case SSH_ERR_NO_CIPHER_ALG_MATCH:
1874 	case SSH_ERR_NO_MAC_ALG_MATCH:
1875 	case SSH_ERR_NO_COMPRESS_ALG_MATCH:
1876 	case SSH_ERR_NO_KEX_ALG_MATCH:
1877 	case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
1878 		if (ssh && ssh->kex && ssh->kex->failed_choice) {
1879 			BLACKLIST_NOTIFY(ssh, BLACKLIST_AUTH_FAIL, "ssh");
1880 			ssh_packet_clear_keys(ssh);
1881 			errno = oerrno;
1882 			logdie("Unable to negotiate with %s: %s. "
1883 			    "Their offer: %s", remote_id, ssh_err(r),
1884 			    ssh->kex->failed_choice);
1885 		}
1886 		/* FALLTHROUGH */
1887 	default:
1888 		if (vasprintf(&tag, fmt, ap) == -1) {
1889 			ssh_packet_clear_keys(ssh);
1890 			logdie_f("could not allocate failure message");
1891 		}
1892 		ssh_packet_clear_keys(ssh);
1893 		errno = oerrno;
1894 		logdie_r(r, "%s%sConnection %s %s",
1895 		    tag != NULL ? tag : "", tag != NULL ? ": " : "",
1896 		    ssh->state->server_side ? "from" : "to", remote_id);
1897 	}
1898 }
1899 
1900 void
1901 sshpkt_fatal(struct ssh *ssh, int r, const char *fmt, ...)
1902 {
1903 	va_list ap;
1904 
1905 	va_start(ap, fmt);
1906 	sshpkt_vfatal(ssh, r, fmt, ap);
1907 	/* NOTREACHED */
1908 	va_end(ap);
1909 	logdie_f("should have exited");
1910 }
1911 
1912 /*
1913  * Logs the error plus constructs and sends a disconnect packet, closes the
1914  * connection, and exits.  This function never returns. The error message
1915  * should not contain a newline.  The length of the formatted message must
1916  * not exceed 1024 bytes.
1917  */
1918 void
1919 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
1920 {
1921 	char buf[1024], remote_id[512];
1922 	va_list args;
1923 	static int disconnecting = 0;
1924 	int r;
1925 
1926 	if (disconnecting)	/* Guard against recursive invocations. */
1927 		fatal("packet_disconnect called recursively.");
1928 	disconnecting = 1;
1929 
1930 	/*
1931 	 * Format the message.  Note that the caller must make sure the
1932 	 * message is of limited size.
1933 	 */
1934 	sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1935 	va_start(args, fmt);
1936 	vsnprintf(buf, sizeof(buf), fmt, args);
1937 	va_end(args);
1938 
1939 	/* Display the error locally */
1940 	logit("Disconnecting %s: %.100s", remote_id, buf);
1941 
1942 	/*
1943 	 * Send the disconnect message to the other side, and wait
1944 	 * for it to get sent.
1945 	 */
1946 	if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
1947 		sshpkt_fatal(ssh, r, "%s", __func__);
1948 
1949 	if ((r = ssh_packet_write_wait(ssh)) != 0)
1950 		sshpkt_fatal(ssh, r, "%s", __func__);
1951 
1952 	/* Close the connection. */
1953 	ssh_packet_close(ssh);
1954 	cleanup_exit(255);
1955 }
1956 
1957 /*
1958  * Checks if there is any buffered output, and tries to write some of
1959  * the output.
1960  */
1961 int
1962 ssh_packet_write_poll(struct ssh *ssh)
1963 {
1964 	struct session_state *state = ssh->state;
1965 	int len = sshbuf_len(state->output);
1966 	int r;
1967 
1968 	if (len > 0) {
1969 		len = write(state->connection_out,
1970 		    sshbuf_ptr(state->output), len);
1971 		if (len == -1) {
1972 			if (errno == EINTR || errno == EAGAIN ||
1973 			    errno == EWOULDBLOCK)
1974 				return 0;
1975 			return SSH_ERR_SYSTEM_ERROR;
1976 		}
1977 		if (len == 0)
1978 			return SSH_ERR_CONN_CLOSED;
1979 		if ((r = sshbuf_consume(state->output, len)) != 0)
1980 			return r;
1981 	}
1982 	return 0;
1983 }
1984 
1985 /*
1986  * Calls packet_write_poll repeatedly until all pending output data has been
1987  * written.
1988  */
1989 int
1990 ssh_packet_write_wait(struct ssh *ssh)
1991 {
1992 	fd_set *setp;
1993 	int ret, r, ms_remain = 0;
1994 	struct timeval start, timeout, *timeoutp = NULL;
1995 	struct session_state *state = ssh->state;
1996 
1997 	setp = calloc(howmany(state->connection_out + 1,
1998 	    NFDBITS), sizeof(fd_mask));
1999 	if (setp == NULL)
2000 		return SSH_ERR_ALLOC_FAIL;
2001 	if ((r = ssh_packet_write_poll(ssh)) != 0) {
2002 		free(setp);
2003 		return r;
2004 	}
2005 	while (ssh_packet_have_data_to_write(ssh)) {
2006 		memset(setp, 0, howmany(state->connection_out + 1,
2007 		    NFDBITS) * sizeof(fd_mask));
2008 		FD_SET(state->connection_out, setp);
2009 
2010 		if (state->packet_timeout_ms > 0) {
2011 			ms_remain = state->packet_timeout_ms;
2012 			timeoutp = &timeout;
2013 		}
2014 		for (;;) {
2015 			if (state->packet_timeout_ms > 0) {
2016 				ms_to_timeval(&timeout, ms_remain);
2017 				monotime_tv(&start);
2018 			}
2019 			if ((ret = select(state->connection_out + 1,
2020 			    NULL, setp, NULL, timeoutp)) >= 0)
2021 				break;
2022 			if (errno != EAGAIN && errno != EINTR &&
2023 			    errno != EWOULDBLOCK)
2024 				break;
2025 			if (state->packet_timeout_ms <= 0)
2026 				continue;
2027 			ms_subtract_diff(&start, &ms_remain);
2028 			if (ms_remain <= 0) {
2029 				ret = 0;
2030 				break;
2031 			}
2032 		}
2033 		if (ret == 0) {
2034 			free(setp);
2035 			return SSH_ERR_CONN_TIMEOUT;
2036 		}
2037 		if ((r = ssh_packet_write_poll(ssh)) != 0) {
2038 			free(setp);
2039 			return r;
2040 		}
2041 	}
2042 	free(setp);
2043 	return 0;
2044 }
2045 
2046 /* Returns true if there is buffered data to write to the connection. */
2047 
2048 int
2049 ssh_packet_have_data_to_write(struct ssh *ssh)
2050 {
2051 	return sshbuf_len(ssh->state->output) != 0;
2052 }
2053 
2054 /* Returns true if there is not too much data to write to the connection. */
2055 
2056 int
2057 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2058 {
2059 	if (ssh->state->interactive_mode)
2060 		return sshbuf_len(ssh->state->output) < 16384;
2061 	else
2062 		return sshbuf_len(ssh->state->output) < 128 * 1024;
2063 }
2064 
2065 void
2066 ssh_packet_set_tos(struct ssh *ssh, int tos)
2067 {
2068 	if (!ssh_packet_connection_is_on_socket(ssh) || tos == INT_MAX)
2069 		return;
2070 	set_sock_tos(ssh->state->connection_in, tos);
2071 }
2072 
2073 /* Informs that the current session is interactive.  Sets IP flags for that. */
2074 
2075 void
2076 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
2077 {
2078 	struct session_state *state = ssh->state;
2079 
2080 	if (state->set_interactive_called)
2081 		return;
2082 	state->set_interactive_called = 1;
2083 
2084 	/* Record that we are in interactive mode. */
2085 	state->interactive_mode = interactive;
2086 
2087 	/* Only set socket options if using a socket.  */
2088 	if (!ssh_packet_connection_is_on_socket(ssh))
2089 		return;
2090 	set_nodelay(state->connection_in);
2091 	ssh_packet_set_tos(ssh, interactive ? qos_interactive : qos_bulk);
2092 }
2093 
2094 /* Returns true if the current connection is interactive. */
2095 
2096 int
2097 ssh_packet_is_interactive(struct ssh *ssh)
2098 {
2099 	return ssh->state->interactive_mode;
2100 }
2101 
2102 int
2103 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2104 {
2105 	struct session_state *state = ssh->state;
2106 
2107 	if (state->set_maxsize_called) {
2108 		logit("packet_set_maxsize: called twice: old %d new %d",
2109 		    state->max_packet_size, s);
2110 		return -1;
2111 	}
2112 	if (s < 4 * 1024 || s > 1024 * 1024) {
2113 		logit("packet_set_maxsize: bad size %d", s);
2114 		return -1;
2115 	}
2116 	state->set_maxsize_called = 1;
2117 	debug("packet_set_maxsize: setting to %d", s);
2118 	state->max_packet_size = s;
2119 	return s;
2120 }
2121 
2122 int
2123 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2124 {
2125 	return ++ssh->state->keep_alive_timeouts;
2126 }
2127 
2128 void
2129 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2130 {
2131 	ssh->state->keep_alive_timeouts = ka;
2132 }
2133 
2134 u_int
2135 ssh_packet_get_maxsize(struct ssh *ssh)
2136 {
2137 	return ssh->state->max_packet_size;
2138 }
2139 
2140 void
2141 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, u_int32_t seconds)
2142 {
2143 	debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
2144 	    (unsigned int)seconds);
2145 	ssh->state->rekey_limit = bytes;
2146 	ssh->state->rekey_interval = seconds;
2147 }
2148 
2149 time_t
2150 ssh_packet_get_rekey_timeout(struct ssh *ssh)
2151 {
2152 	time_t seconds;
2153 
2154 	seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2155 	    monotime();
2156 	return (seconds <= 0 ? 1 : seconds);
2157 }
2158 
2159 void
2160 ssh_packet_set_server(struct ssh *ssh)
2161 {
2162 	ssh->state->server_side = 1;
2163 	ssh->kex->server = 1; /* XXX unify? */
2164 }
2165 
2166 void
2167 ssh_packet_set_authenticated(struct ssh *ssh)
2168 {
2169 	ssh->state->after_authentication = 1;
2170 }
2171 
2172 void *
2173 ssh_packet_get_input(struct ssh *ssh)
2174 {
2175 	return (void *)ssh->state->input;
2176 }
2177 
2178 void *
2179 ssh_packet_get_output(struct ssh *ssh)
2180 {
2181 	return (void *)ssh->state->output;
2182 }
2183 
2184 /* Reset after_authentication and reset compression in post-auth privsep */
2185 static int
2186 ssh_packet_set_postauth(struct ssh *ssh)
2187 {
2188 	int r;
2189 
2190 	debug_f("called");
2191 	/* This was set in net child, but is not visible in user child */
2192 	ssh->state->after_authentication = 1;
2193 	ssh->state->rekeying = 0;
2194 	if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
2195 		return r;
2196 	return 0;
2197 }
2198 
2199 /* Packet state (de-)serialization for privsep */
2200 
2201 /* turn kex into a blob for packet state serialization */
2202 static int
2203 kex_to_blob(struct sshbuf *m, struct kex *kex)
2204 {
2205 	int r;
2206 
2207 	if ((r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2208 	    (r = sshbuf_put_cstring(m, kex->hostkey_alg)) != 0 ||
2209 	    (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2210 	    (r = sshbuf_put_u32(m, kex->hostkey_nid)) != 0 ||
2211 	    (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2212 	    (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2213 	    (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2214 	    (r = sshbuf_put_stringb(m, kex->client_version)) != 0 ||
2215 	    (r = sshbuf_put_stringb(m, kex->server_version)) != 0 ||
2216 	    (r = sshbuf_put_stringb(m, kex->session_id)) != 0 ||
2217 	    (r = sshbuf_put_u32(m, kex->flags)) != 0)
2218 		return r;
2219 	return 0;
2220 }
2221 
2222 /* turn key exchange results into a blob for packet state serialization */
2223 static int
2224 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2225 {
2226 	struct sshbuf *b;
2227 	struct sshcipher_ctx *cc;
2228 	struct sshcomp *comp;
2229 	struct sshenc *enc;
2230 	struct sshmac *mac;
2231 	struct newkeys *newkey;
2232 	int r;
2233 
2234 	if ((newkey = ssh->state->newkeys[mode]) == NULL)
2235 		return SSH_ERR_INTERNAL_ERROR;
2236 	enc = &newkey->enc;
2237 	mac = &newkey->mac;
2238 	comp = &newkey->comp;
2239 	cc = (mode == MODE_OUT) ? ssh->state->send_context :
2240 	    ssh->state->receive_context;
2241 	if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2242 		return r;
2243 	if ((b = sshbuf_new()) == NULL)
2244 		return SSH_ERR_ALLOC_FAIL;
2245 	if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2246 	    (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2247 	    (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2248 	    (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2249 	    (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2250 		goto out;
2251 	if (cipher_authlen(enc->cipher) == 0) {
2252 		if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2253 		    (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2254 		    (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2255 			goto out;
2256 	}
2257 	if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2258 	    (r = sshbuf_put_cstring(b, comp->name)) != 0)
2259 		goto out;
2260 	r = sshbuf_put_stringb(m, b);
2261  out:
2262 	sshbuf_free(b);
2263 	return r;
2264 }
2265 
2266 /* serialize packet state into a blob */
2267 int
2268 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2269 {
2270 	struct session_state *state = ssh->state;
2271 	int r;
2272 
2273 	if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2274 	    (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2275 	    (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2276 	    (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2277 	    (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2278 	    (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2279 	    (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2280 	    (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2281 	    (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2282 	    (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2283 	    (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2284 	    (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2285 	    (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0 ||
2286 	    (r = sshbuf_put_stringb(m, state->input)) != 0 ||
2287 	    (r = sshbuf_put_stringb(m, state->output)) != 0)
2288 		return r;
2289 
2290 	return 0;
2291 }
2292 
2293 /* restore key exchange results from blob for packet state de-serialization */
2294 static int
2295 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2296 {
2297 	struct sshbuf *b = NULL;
2298 	struct sshcomp *comp;
2299 	struct sshenc *enc;
2300 	struct sshmac *mac;
2301 	struct newkeys *newkey = NULL;
2302 	size_t keylen, ivlen, maclen;
2303 	int r;
2304 
2305 	if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2306 		r = SSH_ERR_ALLOC_FAIL;
2307 		goto out;
2308 	}
2309 	if ((r = sshbuf_froms(m, &b)) != 0)
2310 		goto out;
2311 #ifdef DEBUG_PK
2312 	sshbuf_dump(b, stderr);
2313 #endif
2314 	enc = &newkey->enc;
2315 	mac = &newkey->mac;
2316 	comp = &newkey->comp;
2317 
2318 	if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2319 	    (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2320 	    (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2321 	    (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2322 	    (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2323 		goto out;
2324 	if ((enc->cipher = cipher_by_name(enc->name)) == NULL) {
2325 		r = SSH_ERR_INVALID_FORMAT;
2326 		goto out;
2327 	}
2328 	if (cipher_authlen(enc->cipher) == 0) {
2329 		if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2330 			goto out;
2331 		if ((r = mac_setup(mac, mac->name)) != 0)
2332 			goto out;
2333 		if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2334 		    (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2335 			goto out;
2336 		if (maclen > mac->key_len) {
2337 			r = SSH_ERR_INVALID_FORMAT;
2338 			goto out;
2339 		}
2340 		mac->key_len = maclen;
2341 	}
2342 	if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2343 	    (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2344 		goto out;
2345 	if (sshbuf_len(b) != 0) {
2346 		r = SSH_ERR_INVALID_FORMAT;
2347 		goto out;
2348 	}
2349 	enc->key_len = keylen;
2350 	enc->iv_len = ivlen;
2351 	ssh->kex->newkeys[mode] = newkey;
2352 	newkey = NULL;
2353 	r = 0;
2354  out:
2355 	free(newkey);
2356 	sshbuf_free(b);
2357 	return r;
2358 }
2359 
2360 /* restore kex from blob for packet state de-serialization */
2361 static int
2362 kex_from_blob(struct sshbuf *m, struct kex **kexp)
2363 {
2364 	struct kex *kex;
2365 	int r;
2366 
2367 	if ((kex = kex_new()) == NULL)
2368 		return SSH_ERR_ALLOC_FAIL;
2369 	if ((r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2370 	    (r = sshbuf_get_cstring(m, &kex->hostkey_alg, NULL)) != 0 ||
2371 	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2372 	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_nid)) != 0 ||
2373 	    (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2374 	    (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2375 	    (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2376 	    (r = sshbuf_get_stringb(m, kex->client_version)) != 0 ||
2377 	    (r = sshbuf_get_stringb(m, kex->server_version)) != 0 ||
2378 	    (r = sshbuf_get_stringb(m, kex->session_id)) != 0 ||
2379 	    (r = sshbuf_get_u32(m, &kex->flags)) != 0)
2380 		goto out;
2381 	kex->server = 1;
2382 	kex->done = 1;
2383 	r = 0;
2384  out:
2385 	if (r != 0 || kexp == NULL) {
2386 		kex_free(kex);
2387 		if (kexp != NULL)
2388 			*kexp = NULL;
2389 	} else {
2390 		kex_free(*kexp);
2391 		*kexp = kex;
2392 	}
2393 	return r;
2394 }
2395 
2396 /*
2397  * Restore packet state from content of blob 'm' (de-serialization).
2398  * Note that 'm' will be partially consumed on parsing or any other errors.
2399  */
2400 int
2401 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2402 {
2403 	struct session_state *state = ssh->state;
2404 	const u_char *input, *output;
2405 	size_t ilen, olen;
2406 	int r;
2407 
2408 	if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2409 	    (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2410 	    (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2411 	    (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2412 	    (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2413 	    (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2414 	    (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2415 	    (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2416 	    (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2417 	    (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2418 	    (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2419 	    (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2420 	    (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2421 		return r;
2422 	/*
2423 	 * We set the time here so that in post-auth privsep child we
2424 	 * count from the completion of the authentication.
2425 	 */
2426 	state->rekey_time = monotime();
2427 	/* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2428 	if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2429 	    (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2430 		return r;
2431 
2432 	if ((r = ssh_packet_set_postauth(ssh)) != 0)
2433 		return r;
2434 
2435 	sshbuf_reset(state->input);
2436 	sshbuf_reset(state->output);
2437 	if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2438 	    (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2439 	    (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2440 	    (r = sshbuf_put(state->output, output, olen)) != 0)
2441 		return r;
2442 
2443 	if (sshbuf_len(m))
2444 		return SSH_ERR_INVALID_FORMAT;
2445 	debug3_f("done");
2446 	return 0;
2447 }
2448 
2449 /* NEW API */
2450 
2451 /* put data to the outgoing packet */
2452 
2453 int
2454 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2455 {
2456 	return sshbuf_put(ssh->state->outgoing_packet, v, len);
2457 }
2458 
2459 int
2460 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2461 {
2462 	return sshbuf_putb(ssh->state->outgoing_packet, b);
2463 }
2464 
2465 int
2466 sshpkt_put_u8(struct ssh *ssh, u_char val)
2467 {
2468 	return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2469 }
2470 
2471 int
2472 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2473 {
2474 	return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2475 }
2476 
2477 int
2478 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2479 {
2480 	return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2481 }
2482 
2483 int
2484 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2485 {
2486 	return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2487 }
2488 
2489 int
2490 sshpkt_put_cstring(struct ssh *ssh, const void *v)
2491 {
2492 	return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2493 }
2494 
2495 int
2496 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2497 {
2498 	return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2499 }
2500 
2501 int
2502 sshpkt_getb_froms(struct ssh *ssh, struct sshbuf **valp)
2503 {
2504 	return sshbuf_froms(ssh->state->incoming_packet, valp);
2505 }
2506 
2507 #ifdef WITH_OPENSSL
2508 #ifdef OPENSSL_HAS_ECC
2509 int
2510 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2511 {
2512 	return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2513 }
2514 #endif /* OPENSSL_HAS_ECC */
2515 
2516 
2517 int
2518 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2519 {
2520 	return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2521 }
2522 #endif /* WITH_OPENSSL */
2523 
2524 /* fetch data from the incoming packet */
2525 
2526 int
2527 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2528 {
2529 	return sshbuf_get(ssh->state->incoming_packet, valp, len);
2530 }
2531 
2532 int
2533 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2534 {
2535 	return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2536 }
2537 
2538 int
2539 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2540 {
2541 	return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2542 }
2543 
2544 int
2545 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2546 {
2547 	return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2548 }
2549 
2550 int
2551 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2552 {
2553 	return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2554 }
2555 
2556 int
2557 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2558 {
2559 	return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2560 }
2561 
2562 int
2563 sshpkt_peek_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2564 {
2565 	return sshbuf_peek_string_direct(ssh->state->incoming_packet, valp, lenp);
2566 }
2567 
2568 int
2569 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2570 {
2571 	return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2572 }
2573 
2574 #ifdef WITH_OPENSSL
2575 #ifdef OPENSSL_HAS_ECC
2576 int
2577 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2578 {
2579 	return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2580 }
2581 #endif /* OPENSSL_HAS_ECC */
2582 
2583 int
2584 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM **valp)
2585 {
2586 	return sshbuf_get_bignum2(ssh->state->incoming_packet, valp);
2587 }
2588 #endif /* WITH_OPENSSL */
2589 
2590 int
2591 sshpkt_get_end(struct ssh *ssh)
2592 {
2593 	if (sshbuf_len(ssh->state->incoming_packet) > 0)
2594 		return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2595 	return 0;
2596 }
2597 
2598 const u_char *
2599 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2600 {
2601 	if (lenp != NULL)
2602 		*lenp = sshbuf_len(ssh->state->incoming_packet);
2603 	return sshbuf_ptr(ssh->state->incoming_packet);
2604 }
2605 
2606 /* start a new packet */
2607 
2608 int
2609 sshpkt_start(struct ssh *ssh, u_char type)
2610 {
2611 	u_char buf[6]; /* u32 packet length, u8 pad len, u8 type */
2612 
2613 	DBG(debug("packet_start[%d]", type));
2614 	memset(buf, 0, sizeof(buf));
2615 	buf[sizeof(buf) - 1] = type;
2616 	sshbuf_reset(ssh->state->outgoing_packet);
2617 	return sshbuf_put(ssh->state->outgoing_packet, buf, sizeof(buf));
2618 }
2619 
2620 static int
2621 ssh_packet_send_mux(struct ssh *ssh)
2622 {
2623 	struct session_state *state = ssh->state;
2624 	u_char type, *cp;
2625 	size_t len;
2626 	int r;
2627 
2628 	if (ssh->kex)
2629 		return SSH_ERR_INTERNAL_ERROR;
2630 	len = sshbuf_len(state->outgoing_packet);
2631 	if (len < 6)
2632 		return SSH_ERR_INTERNAL_ERROR;
2633 	cp = sshbuf_mutable_ptr(state->outgoing_packet);
2634 	type = cp[5];
2635 	if (ssh_packet_log_type(type))
2636 		debug3_f("type %u", type);
2637 	/* drop everything, but the connection protocol */
2638 	if (type >= SSH2_MSG_CONNECTION_MIN &&
2639 	    type <= SSH2_MSG_CONNECTION_MAX) {
2640 		POKE_U32(cp, len - 4);
2641 		if ((r = sshbuf_putb(state->output,
2642 		    state->outgoing_packet)) != 0)
2643 			return r;
2644 		/* sshbuf_dump(state->output, stderr); */
2645 	}
2646 	sshbuf_reset(state->outgoing_packet);
2647 	return 0;
2648 }
2649 
2650 /*
2651  * 9.2.  Ignored Data Message
2652  *
2653  *   byte      SSH_MSG_IGNORE
2654  *   string    data
2655  *
2656  * All implementations MUST understand (and ignore) this message at any
2657  * time (after receiving the protocol version). No implementation is
2658  * required to send them. This message can be used as an additional
2659  * protection measure against advanced traffic analysis techniques.
2660  */
2661 int
2662 sshpkt_msg_ignore(struct ssh *ssh, u_int nbytes)
2663 {
2664 	u_int32_t rnd = 0;
2665 	int r;
2666 	u_int i;
2667 
2668 	if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2669 	    (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2670 		return r;
2671 	for (i = 0; i < nbytes; i++) {
2672 		if (i % 4 == 0)
2673 			rnd = arc4random();
2674 		if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2675 			return r;
2676 		rnd >>= 8;
2677 	}
2678 	return 0;
2679 }
2680 
2681 /* send it */
2682 
2683 int
2684 sshpkt_send(struct ssh *ssh)
2685 {
2686 	if (ssh->state && ssh->state->mux)
2687 		return ssh_packet_send_mux(ssh);
2688 	return ssh_packet_send2(ssh);
2689 }
2690 
2691 int
2692 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
2693 {
2694 	char buf[1024];
2695 	va_list args;
2696 	int r;
2697 
2698 	va_start(args, fmt);
2699 	vsnprintf(buf, sizeof(buf), fmt, args);
2700 	va_end(args);
2701 
2702 	if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
2703 	    (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
2704 	    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2705 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2706 	    (r = sshpkt_send(ssh)) != 0)
2707 		return r;
2708 	return 0;
2709 }
2710 
2711 /* roundup current message to pad bytes */
2712 int
2713 sshpkt_add_padding(struct ssh *ssh, u_char pad)
2714 {
2715 	ssh->state->extra_pad = pad;
2716 	return 0;
2717 }
2718