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