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