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