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