xref: /freebsd/crypto/openssh/packet.c (revision d6b92ffa)
1 /* $OpenBSD: packet.c,v 1.243 2016/10/11 21:47:45 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This file contains code implementing the packet protocol and communication
7  * with the other side.  This same code is used both on client and server side.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  *
16  * SSH2 packet format added by Markus Friedl.
17  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 #include "includes.h"
41 __RCSID("$FreeBSD$");
42 
43 #include <sys/types.h>
44 #include "openbsd-compat/sys-queue.h"
45 #include <sys/socket.h>
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
48 #endif
49 
50 #include <netinet/in.h>
51 #include <netinet/ip.h>
52 #include <arpa/inet.h>
53 
54 #include <errno.h>
55 #include <netdb.h>
56 #include <stdarg.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <unistd.h>
61 #include <limits.h>
62 #include <signal.h>
63 #include <time.h>
64 
65 #include <zlib.h>
66 
67 #include "buffer.h"	/* typedefs XXX */
68 #include "key.h"	/* typedefs XXX */
69 
70 #include "xmalloc.h"
71 #include "crc32.h"
72 #include "deattack.h"
73 #include "compat.h"
74 #include "ssh1.h"
75 #include "ssh2.h"
76 #include "cipher.h"
77 #include "sshkey.h"
78 #include "kex.h"
79 #include "digest.h"
80 #include "mac.h"
81 #include "log.h"
82 #include "canohost.h"
83 #include "misc.h"
84 #include "channels.h"
85 #include "ssh.h"
86 #include "packet.h"
87 #include "ssherr.h"
88 #include "sshbuf.h"
89 #include "blacklist_client.h"
90 
91 #ifdef PACKET_DEBUG
92 #define DBG(x) x
93 #else
94 #define DBG(x)
95 #endif
96 
97 #define PACKET_MAX_SIZE (256 * 1024)
98 
99 struct packet_state {
100 	u_int32_t seqnr;
101 	u_int32_t packets;
102 	u_int64_t blocks;
103 	u_int64_t bytes;
104 };
105 
106 struct packet {
107 	TAILQ_ENTRY(packet) next;
108 	u_char type;
109 	struct sshbuf *payload;
110 };
111 
112 struct session_state {
113 	/*
114 	 * This variable contains the file descriptors used for
115 	 * communicating with the other side.  connection_in is used for
116 	 * reading; connection_out for writing.  These can be the same
117 	 * descriptor, in which case it is assumed to be a socket.
118 	 */
119 	int connection_in;
120 	int connection_out;
121 
122 	/* Protocol flags for the remote side. */
123 	u_int remote_protocol_flags;
124 
125 	/* Encryption context for receiving data.  Only used for decryption. */
126 	struct sshcipher_ctx *receive_context;
127 
128 	/* Encryption context for sending data.  Only used for encryption. */
129 	struct sshcipher_ctx *send_context;
130 
131 	/* Buffer for raw input data from the socket. */
132 	struct sshbuf *input;
133 
134 	/* Buffer for raw output data going to the socket. */
135 	struct sshbuf *output;
136 
137 	/* Buffer for the partial outgoing packet being constructed. */
138 	struct sshbuf *outgoing_packet;
139 
140 	/* Buffer for the incoming packet currently being processed. */
141 	struct sshbuf *incoming_packet;
142 
143 	/* Scratch buffer for packet compression/decompression. */
144 	struct sshbuf *compression_buffer;
145 
146 	/* Incoming/outgoing compression dictionaries */
147 	z_stream compression_in_stream;
148 	z_stream compression_out_stream;
149 	int compression_in_started;
150 	int compression_out_started;
151 	int compression_in_failures;
152 	int compression_out_failures;
153 
154 	/*
155 	 * Flag indicating whether packet compression/decompression is
156 	 * enabled.
157 	 */
158 	int packet_compression;
159 
160 	/* default maximum packet size */
161 	u_int max_packet_size;
162 
163 	/* Flag indicating whether this module has been initialized. */
164 	int initialized;
165 
166 	/* Set to true if the connection is interactive. */
167 	int interactive_mode;
168 
169 	/* Set to true if we are the server side. */
170 	int server_side;
171 
172 	/* Set to true if we are authenticated. */
173 	int after_authentication;
174 
175 	int keep_alive_timeouts;
176 
177 	/* The maximum time that we will wait to send or receive a packet */
178 	int packet_timeout_ms;
179 
180 	/* Session key information for Encryption and MAC */
181 	struct newkeys *newkeys[MODE_MAX];
182 	struct packet_state p_read, p_send;
183 
184 	/* Volume-based rekeying */
185 	u_int64_t max_blocks_in, max_blocks_out, rekey_limit;
186 
187 	/* Time-based rekeying */
188 	u_int32_t rekey_interval;	/* how often in seconds */
189 	time_t rekey_time;	/* time of last rekeying */
190 
191 	/* Session key for protocol v1 */
192 	u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
193 	u_int ssh1_keylen;
194 
195 	/* roundup current message to extra_pad bytes */
196 	u_char extra_pad;
197 
198 	/* XXX discard incoming data after MAC error */
199 	u_int packet_discard;
200 	size_t packet_discard_mac_already;
201 	struct sshmac *packet_discard_mac;
202 
203 	/* Used in packet_read_poll2() */
204 	u_int packlen;
205 
206 	/* Used in packet_send2 */
207 	int rekeying;
208 
209 	/* Used in ssh_packet_send_mux() */
210 	int mux;
211 
212 	/* Used in packet_set_interactive */
213 	int set_interactive_called;
214 
215 	/* Used in packet_set_maxsize */
216 	int set_maxsize_called;
217 
218 	/* One-off warning about weak ciphers */
219 	int cipher_warning_done;
220 
221 	/* SSH1 CRC compensation attack detector */
222 	struct deattack_ctx deattack;
223 
224 	/* Hook for fuzzing inbound packets */
225 	ssh_packet_hook_fn *hook_in;
226 	void *hook_in_ctx;
227 
228 	TAILQ_HEAD(, packet) outgoing;
229 };
230 
231 struct ssh *
232 ssh_alloc_session_state(void)
233 {
234 	struct ssh *ssh = NULL;
235 	struct session_state *state = NULL;
236 
237 	if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
238 	    (state = calloc(1, sizeof(*state))) == NULL ||
239 	    (state->input = sshbuf_new()) == NULL ||
240 	    (state->output = sshbuf_new()) == NULL ||
241 	    (state->outgoing_packet = sshbuf_new()) == NULL ||
242 	    (state->incoming_packet = sshbuf_new()) == NULL)
243 		goto fail;
244 	TAILQ_INIT(&state->outgoing);
245 	TAILQ_INIT(&ssh->private_keys);
246 	TAILQ_INIT(&ssh->public_keys);
247 	state->connection_in = -1;
248 	state->connection_out = -1;
249 	state->max_packet_size = 32768;
250 	state->packet_timeout_ms = -1;
251 	state->p_send.packets = state->p_read.packets = 0;
252 	state->initialized = 1;
253 	/*
254 	 * ssh_packet_send2() needs to queue packets until
255 	 * we've done the initial key exchange.
256 	 */
257 	state->rekeying = 1;
258 	ssh->state = state;
259 	return ssh;
260  fail:
261 	if (state) {
262 		sshbuf_free(state->input);
263 		sshbuf_free(state->output);
264 		sshbuf_free(state->incoming_packet);
265 		sshbuf_free(state->outgoing_packet);
266 		free(state);
267 	}
268 	free(ssh);
269 	return NULL;
270 }
271 
272 void
273 ssh_packet_set_input_hook(struct ssh *ssh, ssh_packet_hook_fn *hook, void *ctx)
274 {
275 	ssh->state->hook_in = hook;
276 	ssh->state->hook_in_ctx = ctx;
277 }
278 
279 /* Returns nonzero if rekeying is in progress */
280 int
281 ssh_packet_is_rekeying(struct ssh *ssh)
282 {
283 	return compat20 &&
284 	    (ssh->state->rekeying || (ssh->kex != NULL && ssh->kex->done == 0));
285 }
286 
287 /*
288  * Sets the descriptors used for communication.  Disables encryption until
289  * packet_set_encryption_key is called.
290  */
291 struct ssh *
292 ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
293 {
294 	struct session_state *state;
295 	const struct sshcipher *none = cipher_by_name("none");
296 	int r;
297 
298 	if (none == NULL) {
299 		error("%s: cannot load cipher 'none'", __func__);
300 		return NULL;
301 	}
302 	if (ssh == NULL)
303 		ssh = ssh_alloc_session_state();
304 	if (ssh == NULL) {
305 		error("%s: cound not allocate state", __func__);
306 		return NULL;
307 	}
308 	state = ssh->state;
309 	state->connection_in = fd_in;
310 	state->connection_out = fd_out;
311 	if ((r = cipher_init(&state->send_context, none,
312 	    (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
313 	    (r = cipher_init(&state->receive_context, none,
314 	    (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
315 		error("%s: cipher_init failed: %s", __func__, ssh_err(r));
316 		free(ssh); /* XXX need ssh_free_session_state? */
317 		return NULL;
318 	}
319 	state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
320 	deattack_init(&state->deattack);
321 	/*
322 	 * Cache the IP address of the remote connection for use in error
323 	 * messages that might be generated after the connection has closed.
324 	 */
325 	(void)ssh_remote_ipaddr(ssh);
326 	return ssh;
327 }
328 
329 void
330 ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
331 {
332 	struct session_state *state = ssh->state;
333 
334 	if (timeout <= 0 || count <= 0) {
335 		state->packet_timeout_ms = -1;
336 		return;
337 	}
338 	if ((INT_MAX / 1000) / count < timeout)
339 		state->packet_timeout_ms = INT_MAX;
340 	else
341 		state->packet_timeout_ms = timeout * count * 1000;
342 }
343 
344 void
345 ssh_packet_set_mux(struct ssh *ssh)
346 {
347 	ssh->state->mux = 1;
348 	ssh->state->rekeying = 0;
349 }
350 
351 int
352 ssh_packet_get_mux(struct ssh *ssh)
353 {
354 	return ssh->state->mux;
355 }
356 
357 int
358 ssh_packet_stop_discard(struct ssh *ssh)
359 {
360 	struct session_state *state = ssh->state;
361 	int r;
362 
363 	if (state->packet_discard_mac) {
364 		char buf[1024];
365 		size_t dlen = PACKET_MAX_SIZE;
366 
367 		if (dlen > state->packet_discard_mac_already)
368 			dlen -= state->packet_discard_mac_already;
369 		memset(buf, 'a', sizeof(buf));
370 		while (sshbuf_len(state->incoming_packet) < dlen)
371 			if ((r = sshbuf_put(state->incoming_packet, buf,
372 			    sizeof(buf))) != 0)
373 				return r;
374 		(void) mac_compute(state->packet_discard_mac,
375 		    state->p_read.seqnr,
376 		    sshbuf_ptr(state->incoming_packet), dlen,
377 		    NULL, 0);
378 	}
379 	logit("Finished discarding for %.200s port %d",
380 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
381 	return SSH_ERR_MAC_INVALID;
382 }
383 
384 static int
385 ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
386     struct sshmac *mac, size_t mac_already, u_int discard)
387 {
388 	struct session_state *state = ssh->state;
389 	int r;
390 
391 	if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
392 		if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
393 			return r;
394 		return SSH_ERR_MAC_INVALID;
395 	}
396 	/*
397 	 * Record number of bytes over which the mac has already
398 	 * been computed in order to minimize timing attacks.
399 	 */
400 	if (mac && mac->enabled) {
401 		state->packet_discard_mac = mac;
402 		state->packet_discard_mac_already = mac_already;
403 	}
404 	if (sshbuf_len(state->input) >= discard)
405 		return ssh_packet_stop_discard(ssh);
406 	state->packet_discard = discard - sshbuf_len(state->input);
407 	return 0;
408 }
409 
410 /* Returns 1 if remote host is connected via socket, 0 if not. */
411 
412 int
413 ssh_packet_connection_is_on_socket(struct ssh *ssh)
414 {
415 	struct session_state *state = ssh->state;
416 	struct sockaddr_storage from, to;
417 	socklen_t fromlen, tolen;
418 
419 	if (state->connection_in == -1 || state->connection_out == -1)
420 		return 0;
421 
422 	/* filedescriptors in and out are the same, so it's a socket */
423 	if (state->connection_in == state->connection_out)
424 		return 1;
425 	fromlen = sizeof(from);
426 	memset(&from, 0, sizeof(from));
427 	if (getpeername(state->connection_in, (struct sockaddr *)&from,
428 	    &fromlen) < 0)
429 		return 0;
430 	tolen = sizeof(to);
431 	memset(&to, 0, sizeof(to));
432 	if (getpeername(state->connection_out, (struct sockaddr *)&to,
433 	    &tolen) < 0)
434 		return 0;
435 	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
436 		return 0;
437 	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
438 		return 0;
439 	return 1;
440 }
441 
442 void
443 ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
444 {
445 	if (ibytes)
446 		*ibytes = ssh->state->p_read.bytes;
447 	if (obytes)
448 		*obytes = ssh->state->p_send.bytes;
449 }
450 
451 int
452 ssh_packet_connection_af(struct ssh *ssh)
453 {
454 	struct sockaddr_storage to;
455 	socklen_t tolen = sizeof(to);
456 
457 	memset(&to, 0, sizeof(to));
458 	if (getsockname(ssh->state->connection_out, (struct sockaddr *)&to,
459 	    &tolen) < 0)
460 		return 0;
461 #ifdef IPV4_IN_IPV6
462 	if (to.ss_family == AF_INET6 &&
463 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
464 		return AF_INET;
465 #endif
466 	return to.ss_family;
467 }
468 
469 /* Sets the connection into non-blocking mode. */
470 
471 void
472 ssh_packet_set_nonblocking(struct ssh *ssh)
473 {
474 	/* Set the socket into non-blocking mode. */
475 	set_nonblock(ssh->state->connection_in);
476 
477 	if (ssh->state->connection_out != ssh->state->connection_in)
478 		set_nonblock(ssh->state->connection_out);
479 }
480 
481 /* Returns the socket used for reading. */
482 
483 int
484 ssh_packet_get_connection_in(struct ssh *ssh)
485 {
486 	return ssh->state->connection_in;
487 }
488 
489 /* Returns the descriptor used for writing. */
490 
491 int
492 ssh_packet_get_connection_out(struct ssh *ssh)
493 {
494 	return ssh->state->connection_out;
495 }
496 
497 /*
498  * Returns the IP-address of the remote host as a string.  The returned
499  * string must not be freed.
500  */
501 
502 const char *
503 ssh_remote_ipaddr(struct ssh *ssh)
504 {
505 	const int sock = ssh->state->connection_in;
506 
507 	/* Check whether we have cached the ipaddr. */
508 	if (ssh->remote_ipaddr == NULL) {
509 		if (ssh_packet_connection_is_on_socket(ssh)) {
510 			ssh->remote_ipaddr = get_peer_ipaddr(sock);
511 			ssh->remote_port = get_peer_port(sock);
512 			ssh->local_ipaddr = get_local_ipaddr(sock);
513 			ssh->local_port = get_local_port(sock);
514 		} else {
515 			ssh->remote_ipaddr = strdup("UNKNOWN");
516 			ssh->remote_port = 65535;
517 			ssh->local_ipaddr = strdup("UNKNOWN");
518 			ssh->local_port = 65535;
519 		}
520 	}
521 	return ssh->remote_ipaddr;
522 }
523 
524 /* Returns the port number of the remote host. */
525 
526 int
527 ssh_remote_port(struct ssh *ssh)
528 {
529 	(void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
530 	return ssh->remote_port;
531 }
532 
533 /*
534  * Returns the IP-address of the local host as a string.  The returned
535  * string must not be freed.
536  */
537 
538 const char *
539 ssh_local_ipaddr(struct ssh *ssh)
540 {
541 	(void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
542 	return ssh->local_ipaddr;
543 }
544 
545 /* Returns the port number of the local host. */
546 
547 int
548 ssh_local_port(struct ssh *ssh)
549 {
550 	(void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
551 	return ssh->local_port;
552 }
553 
554 /* Closes the connection and clears and frees internal data structures. */
555 
556 void
557 ssh_packet_close(struct ssh *ssh)
558 {
559 	struct session_state *state = ssh->state;
560 	u_int mode;
561 
562 	if (!state->initialized)
563 		return;
564 	state->initialized = 0;
565 	if (state->connection_in == state->connection_out) {
566 		shutdown(state->connection_out, SHUT_RDWR);
567 		close(state->connection_out);
568 	} else {
569 		close(state->connection_in);
570 		close(state->connection_out);
571 	}
572 	sshbuf_free(state->input);
573 	sshbuf_free(state->output);
574 	sshbuf_free(state->outgoing_packet);
575 	sshbuf_free(state->incoming_packet);
576 	for (mode = 0; mode < MODE_MAX; mode++)
577 		kex_free_newkeys(state->newkeys[mode]);
578 	if (state->compression_buffer) {
579 		sshbuf_free(state->compression_buffer);
580 		if (state->compression_out_started) {
581 			z_streamp stream = &state->compression_out_stream;
582 			debug("compress outgoing: "
583 			    "raw data %llu, compressed %llu, factor %.2f",
584 				(unsigned long long)stream->total_in,
585 				(unsigned long long)stream->total_out,
586 				stream->total_in == 0 ? 0.0 :
587 				(double) stream->total_out / stream->total_in);
588 			if (state->compression_out_failures == 0)
589 				deflateEnd(stream);
590 		}
591 		if (state->compression_in_started) {
592 			z_streamp stream = &state->compression_out_stream;
593 			debug("compress incoming: "
594 			    "raw data %llu, compressed %llu, factor %.2f",
595 			    (unsigned long long)stream->total_out,
596 			    (unsigned long long)stream->total_in,
597 			    stream->total_out == 0 ? 0.0 :
598 			    (double) stream->total_in / stream->total_out);
599 			if (state->compression_in_failures == 0)
600 				inflateEnd(stream);
601 		}
602 	}
603 	cipher_free(state->send_context);
604 	cipher_free(state->receive_context);
605 	state->send_context = state->receive_context = NULL;
606 	free(ssh->remote_ipaddr);
607 	ssh->remote_ipaddr = NULL;
608 	free(ssh->state);
609 	ssh->state = NULL;
610 }
611 
612 /* Sets remote side protocol flags. */
613 
614 void
615 ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
616 {
617 	ssh->state->remote_protocol_flags = protocol_flags;
618 }
619 
620 /* Returns the remote protocol flags set earlier by the above function. */
621 
622 u_int
623 ssh_packet_get_protocol_flags(struct ssh *ssh)
624 {
625 	return ssh->state->remote_protocol_flags;
626 }
627 
628 /*
629  * Starts packet compression from the next packet on in both directions.
630  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
631  */
632 
633 static int
634 ssh_packet_init_compression(struct ssh *ssh)
635 {
636 	if (!ssh->state->compression_buffer &&
637 	   ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
638 		return SSH_ERR_ALLOC_FAIL;
639 	return 0;
640 }
641 
642 static int
643 start_compression_out(struct ssh *ssh, int level)
644 {
645 	if (level < 1 || level > 9)
646 		return SSH_ERR_INVALID_ARGUMENT;
647 	debug("Enabling compression at level %d.", level);
648 	if (ssh->state->compression_out_started == 1)
649 		deflateEnd(&ssh->state->compression_out_stream);
650 	switch (deflateInit(&ssh->state->compression_out_stream, level)) {
651 	case Z_OK:
652 		ssh->state->compression_out_started = 1;
653 		break;
654 	case Z_MEM_ERROR:
655 		return SSH_ERR_ALLOC_FAIL;
656 	default:
657 		return SSH_ERR_INTERNAL_ERROR;
658 	}
659 	return 0;
660 }
661 
662 static int
663 start_compression_in(struct ssh *ssh)
664 {
665 	if (ssh->state->compression_in_started == 1)
666 		inflateEnd(&ssh->state->compression_in_stream);
667 	switch (inflateInit(&ssh->state->compression_in_stream)) {
668 	case Z_OK:
669 		ssh->state->compression_in_started = 1;
670 		break;
671 	case Z_MEM_ERROR:
672 		return SSH_ERR_ALLOC_FAIL;
673 	default:
674 		return SSH_ERR_INTERNAL_ERROR;
675 	}
676 	return 0;
677 }
678 
679 int
680 ssh_packet_start_compression(struct ssh *ssh, int level)
681 {
682 	int r;
683 
684 	if (ssh->state->packet_compression && !compat20)
685 		return SSH_ERR_INTERNAL_ERROR;
686 	ssh->state->packet_compression = 1;
687 	if ((r = ssh_packet_init_compression(ssh)) != 0 ||
688 	    (r = start_compression_in(ssh)) != 0 ||
689 	    (r = start_compression_out(ssh, level)) != 0)
690 		return r;
691 	return 0;
692 }
693 
694 /* XXX remove need for separate compression buffer */
695 static int
696 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
697 {
698 	u_char buf[4096];
699 	int r, status;
700 
701 	if (ssh->state->compression_out_started != 1)
702 		return SSH_ERR_INTERNAL_ERROR;
703 
704 	/* This case is not handled below. */
705 	if (sshbuf_len(in) == 0)
706 		return 0;
707 
708 	/* Input is the contents of the input buffer. */
709 	if ((ssh->state->compression_out_stream.next_in =
710 	    sshbuf_mutable_ptr(in)) == NULL)
711 		return SSH_ERR_INTERNAL_ERROR;
712 	ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
713 
714 	/* Loop compressing until deflate() returns with avail_out != 0. */
715 	do {
716 		/* Set up fixed-size output buffer. */
717 		ssh->state->compression_out_stream.next_out = buf;
718 		ssh->state->compression_out_stream.avail_out = sizeof(buf);
719 
720 		/* Compress as much data into the buffer as possible. */
721 		status = deflate(&ssh->state->compression_out_stream,
722 		    Z_PARTIAL_FLUSH);
723 		switch (status) {
724 		case Z_MEM_ERROR:
725 			return SSH_ERR_ALLOC_FAIL;
726 		case Z_OK:
727 			/* Append compressed data to output_buffer. */
728 			if ((r = sshbuf_put(out, buf, sizeof(buf) -
729 			    ssh->state->compression_out_stream.avail_out)) != 0)
730 				return r;
731 			break;
732 		case Z_STREAM_ERROR:
733 		default:
734 			ssh->state->compression_out_failures++;
735 			return SSH_ERR_INVALID_FORMAT;
736 		}
737 	} while (ssh->state->compression_out_stream.avail_out == 0);
738 	return 0;
739 }
740 
741 static int
742 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
743 {
744 	u_char buf[4096];
745 	int r, status;
746 
747 	if (ssh->state->compression_in_started != 1)
748 		return SSH_ERR_INTERNAL_ERROR;
749 
750 	if ((ssh->state->compression_in_stream.next_in =
751 	    sshbuf_mutable_ptr(in)) == NULL)
752 		return SSH_ERR_INTERNAL_ERROR;
753 	ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
754 
755 	for (;;) {
756 		/* Set up fixed-size output buffer. */
757 		ssh->state->compression_in_stream.next_out = buf;
758 		ssh->state->compression_in_stream.avail_out = sizeof(buf);
759 
760 		status = inflate(&ssh->state->compression_in_stream,
761 		    Z_PARTIAL_FLUSH);
762 		switch (status) {
763 		case Z_OK:
764 			if ((r = sshbuf_put(out, buf, sizeof(buf) -
765 			    ssh->state->compression_in_stream.avail_out)) != 0)
766 				return r;
767 			break;
768 		case Z_BUF_ERROR:
769 			/*
770 			 * Comments in zlib.h say that we should keep calling
771 			 * inflate() until we get an error.  This appears to
772 			 * be the error that we get.
773 			 */
774 			return 0;
775 		case Z_DATA_ERROR:
776 			return SSH_ERR_INVALID_FORMAT;
777 		case Z_MEM_ERROR:
778 			return SSH_ERR_ALLOC_FAIL;
779 		case Z_STREAM_ERROR:
780 		default:
781 			ssh->state->compression_in_failures++;
782 			return SSH_ERR_INTERNAL_ERROR;
783 		}
784 	}
785 	/* NOTREACHED */
786 }
787 
788 /*
789  * Causes any further packets to be encrypted using the given key.  The same
790  * key is used for both sending and reception.  However, both directions are
791  * encrypted independently of each other.
792  */
793 
794 void
795 ssh_packet_set_encryption_key(struct ssh *ssh, const u_char *key, u_int keylen, int number)
796 {
797 #ifndef WITH_SSH1
798 	fatal("no SSH protocol 1 support");
799 #else /* WITH_SSH1 */
800 	struct session_state *state = ssh->state;
801 	const struct sshcipher *cipher = cipher_by_number(number);
802 	int r;
803 	const char *wmsg;
804 
805 	if (cipher == NULL)
806 		fatal("%s: unknown cipher number %d", __func__, number);
807 	if (keylen < 20)
808 		fatal("%s: keylen too small: %d", __func__, keylen);
809 	if (keylen > SSH_SESSION_KEY_LENGTH)
810 		fatal("%s: keylen too big: %d", __func__, keylen);
811 	memcpy(state->ssh1_key, key, keylen);
812 	state->ssh1_keylen = keylen;
813 	if ((r = cipher_init(&state->send_context, cipher, key, keylen,
814 	    NULL, 0, CIPHER_ENCRYPT)) != 0 ||
815 	    (r = cipher_init(&state->receive_context, cipher, key, keylen,
816 	    NULL, 0, CIPHER_DECRYPT) != 0))
817 		fatal("%s: cipher_init failed: %s", __func__, ssh_err(r));
818 	if (!state->cipher_warning_done &&
819 	    ((wmsg = cipher_warning_message(state->send_context)) != NULL ||
820 	    (wmsg = cipher_warning_message(state->send_context)) != NULL)) {
821 		error("Warning: %s", wmsg);
822 		state->cipher_warning_done = 1;
823 	}
824 #endif /* WITH_SSH1 */
825 }
826 
827 /*
828  * Finalizes and sends the packet.  If the encryption key has been set,
829  * encrypts the packet before sending.
830  */
831 
832 int
833 ssh_packet_send1(struct ssh *ssh)
834 {
835 	struct session_state *state = ssh->state;
836 	u_char buf[8], *cp;
837 	int r, padding, len;
838 	u_int checksum;
839 
840 	/*
841 	 * If using packet compression, compress the payload of the outgoing
842 	 * packet.
843 	 */
844 	if (state->packet_compression) {
845 		sshbuf_reset(state->compression_buffer);
846 		/* Skip padding. */
847 		if ((r = sshbuf_consume(state->outgoing_packet, 8)) != 0)
848 			goto out;
849 		/* padding */
850 		if ((r = sshbuf_put(state->compression_buffer,
851 		    "\0\0\0\0\0\0\0\0", 8)) != 0)
852 			goto out;
853 		if ((r = compress_buffer(ssh, state->outgoing_packet,
854 		    state->compression_buffer)) != 0)
855 			goto out;
856 		sshbuf_reset(state->outgoing_packet);
857                 if ((r = sshbuf_putb(state->outgoing_packet,
858                     state->compression_buffer)) != 0)
859 			goto out;
860 	}
861 	/* Compute packet length without padding (add checksum, remove padding). */
862 	len = sshbuf_len(state->outgoing_packet) + 4 - 8;
863 
864 	/* Insert padding. Initialized to zero in packet_start1() */
865 	padding = 8 - len % 8;
866 	if (!cipher_ctx_is_plaintext(state->send_context)) {
867 		cp = sshbuf_mutable_ptr(state->outgoing_packet);
868 		if (cp == NULL) {
869 			r = SSH_ERR_INTERNAL_ERROR;
870 			goto out;
871 		}
872 		arc4random_buf(cp + 8 - padding, padding);
873 	}
874 	if ((r = sshbuf_consume(state->outgoing_packet, 8 - padding)) != 0)
875 		goto out;
876 
877 	/* Add check bytes. */
878 	checksum = ssh_crc32(sshbuf_ptr(state->outgoing_packet),
879 	    sshbuf_len(state->outgoing_packet));
880 	POKE_U32(buf, checksum);
881 	if ((r = sshbuf_put(state->outgoing_packet, buf, 4)) != 0)
882 		goto out;
883 
884 #ifdef PACKET_DEBUG
885 	fprintf(stderr, "packet_send plain: ");
886 	sshbuf_dump(state->outgoing_packet, stderr);
887 #endif
888 
889 	/* Append to output. */
890 	POKE_U32(buf, len);
891 	if ((r = sshbuf_put(state->output, buf, 4)) != 0)
892 		goto out;
893 	if ((r = sshbuf_reserve(state->output,
894 	    sshbuf_len(state->outgoing_packet), &cp)) != 0)
895 		goto out;
896 	if ((r = cipher_crypt(state->send_context, 0, cp,
897 	    sshbuf_ptr(state->outgoing_packet),
898 	    sshbuf_len(state->outgoing_packet), 0, 0)) != 0)
899 		goto out;
900 
901 #ifdef PACKET_DEBUG
902 	fprintf(stderr, "encrypted: ");
903 	sshbuf_dump(state->output, stderr);
904 #endif
905 	state->p_send.packets++;
906 	state->p_send.bytes += len +
907 	    sshbuf_len(state->outgoing_packet);
908 	sshbuf_reset(state->outgoing_packet);
909 
910 	/*
911 	 * Note that the packet is now only buffered in output.  It won't be
912 	 * actually sent until ssh_packet_write_wait or ssh_packet_write_poll
913 	 * is called.
914 	 */
915 	r = 0;
916  out:
917 	return r;
918 }
919 
920 int
921 ssh_set_newkeys(struct ssh *ssh, int mode)
922 {
923 	struct session_state *state = ssh->state;
924 	struct sshenc *enc;
925 	struct sshmac *mac;
926 	struct sshcomp *comp;
927 	struct sshcipher_ctx **ccp;
928 	struct packet_state *ps;
929 	u_int64_t *max_blocks;
930 	const char *wmsg, *dir;
931 	int r, crypt_type;
932 
933 	debug2("set_newkeys: mode %d", mode);
934 
935 	if (mode == MODE_OUT) {
936 		dir = "output";
937 		ccp = &state->send_context;
938 		crypt_type = CIPHER_ENCRYPT;
939 		ps = &state->p_send;
940 		max_blocks = &state->max_blocks_out;
941 	} else {
942 		dir = "input";
943 		ccp = &state->receive_context;
944 		crypt_type = CIPHER_DECRYPT;
945 		ps = &state->p_read;
946 		max_blocks = &state->max_blocks_in;
947 	}
948 	if (state->newkeys[mode] != NULL) {
949 		debug("%s: rekeying after %llu %s blocks"
950 		    " (%llu bytes total)", __func__,
951 		    (unsigned long long)ps->blocks, dir,
952 		    (unsigned long long)ps->bytes);
953 		cipher_free(*ccp);
954 		*ccp = NULL;
955 		enc  = &state->newkeys[mode]->enc;
956 		mac  = &state->newkeys[mode]->mac;
957 		comp = &state->newkeys[mode]->comp;
958 		mac_clear(mac);
959 		explicit_bzero(enc->iv,  enc->iv_len);
960 		explicit_bzero(enc->key, enc->key_len);
961 		explicit_bzero(mac->key, mac->key_len);
962 		free(enc->name);
963 		free(enc->iv);
964 		free(enc->key);
965 		free(mac->name);
966 		free(mac->key);
967 		free(comp->name);
968 		free(state->newkeys[mode]);
969 	}
970 	/* note that both bytes and the seqnr are not reset */
971 	ps->packets = ps->blocks = 0;
972 	/* move newkeys from kex to state */
973 	if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
974 		return SSH_ERR_INTERNAL_ERROR;
975 	ssh->kex->newkeys[mode] = NULL;
976 	enc  = &state->newkeys[mode]->enc;
977 	mac  = &state->newkeys[mode]->mac;
978 	comp = &state->newkeys[mode]->comp;
979 	if (cipher_authlen(enc->cipher) == 0) {
980 		if ((r = mac_init(mac)) != 0)
981 			return r;
982 	}
983 	mac->enabled = 1;
984 	DBG(debug("cipher_init_context: %d", mode));
985 	if ((r = cipher_init(ccp, enc->cipher, enc->key, enc->key_len,
986 	    enc->iv, enc->iv_len, crypt_type)) != 0)
987 		return r;
988 	if (!state->cipher_warning_done &&
989 	    (wmsg = cipher_warning_message(*ccp)) != NULL) {
990 		error("Warning: %s", wmsg);
991 		state->cipher_warning_done = 1;
992 	}
993 	/* Deleting the keys does not gain extra security */
994 	/* explicit_bzero(enc->iv,  enc->block_size);
995 	   explicit_bzero(enc->key, enc->key_len);
996 	   explicit_bzero(mac->key, mac->key_len); */
997 	if ((comp->type == COMP_ZLIB ||
998 	    (comp->type == COMP_DELAYED &&
999 	     state->after_authentication)) && comp->enabled == 0) {
1000 		if ((r = ssh_packet_init_compression(ssh)) < 0)
1001 			return r;
1002 		if (mode == MODE_OUT) {
1003 			if ((r = start_compression_out(ssh, 6)) != 0)
1004 				return r;
1005 		} else {
1006 			if ((r = start_compression_in(ssh)) != 0)
1007 				return r;
1008 		}
1009 		comp->enabled = 1;
1010 	}
1011 	/*
1012 	 * The 2^(blocksize*2) limit is too expensive for 3DES,
1013 	 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
1014 	 */
1015 	if (enc->block_size >= 16)
1016 		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
1017 	else
1018 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1019 	if (state->rekey_limit)
1020 		*max_blocks = MINIMUM(*max_blocks,
1021 		    state->rekey_limit / enc->block_size);
1022 	debug("rekey after %llu blocks", (unsigned long long)*max_blocks);
1023 	return 0;
1024 }
1025 
1026 #define MAX_PACKETS	(1U<<31)
1027 static int
1028 ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
1029 {
1030 	struct session_state *state = ssh->state;
1031 	u_int32_t out_blocks;
1032 
1033 	/* XXX client can't cope with rekeying pre-auth */
1034 	if (!state->after_authentication)
1035 		return 0;
1036 
1037 	/* Haven't keyed yet or KEX in progress. */
1038 	if (ssh->kex == NULL || ssh_packet_is_rekeying(ssh))
1039 		return 0;
1040 
1041 	/* Peer can't rekey */
1042 	if (ssh->compat & SSH_BUG_NOREKEY)
1043 		return 0;
1044 
1045 	/*
1046 	 * Permit one packet in or out per rekey - this allows us to
1047 	 * make progress when rekey limits are very small.
1048 	 */
1049 	if (state->p_send.packets == 0 && state->p_read.packets == 0)
1050 		return 0;
1051 
1052 	/* Time-based rekeying */
1053 	if (state->rekey_interval != 0 &&
1054 	    state->rekey_time + state->rekey_interval <= monotime())
1055 		return 1;
1056 
1057 	/* Always rekey when MAX_PACKETS sent in either direction */
1058 	if (state->p_send.packets > MAX_PACKETS ||
1059 	    state->p_read.packets > MAX_PACKETS)
1060 		return 1;
1061 
1062 	/* Rekey after (cipher-specific) maxiumum blocks */
1063 	out_blocks = ROUNDUP(outbound_packet_len,
1064 	    state->newkeys[MODE_OUT]->enc.block_size);
1065 	return (state->max_blocks_out &&
1066 	    (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
1067 	    (state->max_blocks_in &&
1068 	    (state->p_read.blocks > state->max_blocks_in));
1069 }
1070 
1071 /*
1072  * Delayed compression for SSH2 is enabled after authentication:
1073  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1074  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1075  */
1076 static int
1077 ssh_packet_enable_delayed_compress(struct ssh *ssh)
1078 {
1079 	struct session_state *state = ssh->state;
1080 	struct sshcomp *comp = NULL;
1081 	int r, mode;
1082 
1083 	/*
1084 	 * Remember that we are past the authentication step, so rekeying
1085 	 * with COMP_DELAYED will turn on compression immediately.
1086 	 */
1087 	state->after_authentication = 1;
1088 	for (mode = 0; mode < MODE_MAX; mode++) {
1089 		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1090 		if (state->newkeys[mode] == NULL)
1091 			continue;
1092 		comp = &state->newkeys[mode]->comp;
1093 		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1094 			if ((r = ssh_packet_init_compression(ssh)) != 0)
1095 				return r;
1096 			if (mode == MODE_OUT) {
1097 				if ((r = start_compression_out(ssh, 6)) != 0)
1098 					return r;
1099 			} else {
1100 				if ((r = start_compression_in(ssh)) != 0)
1101 					return r;
1102 			}
1103 			comp->enabled = 1;
1104 		}
1105 	}
1106 	return 0;
1107 }
1108 
1109 /* Used to mute debug logging for noisy packet types */
1110 int
1111 ssh_packet_log_type(u_char type)
1112 {
1113 	switch (type) {
1114 	case SSH2_MSG_CHANNEL_DATA:
1115 	case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1116 	case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1117 		return 0;
1118 	default:
1119 		return 1;
1120 	}
1121 }
1122 
1123 /*
1124  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1125  */
1126 int
1127 ssh_packet_send2_wrapped(struct ssh *ssh)
1128 {
1129 	struct session_state *state = ssh->state;
1130 	u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1131 	u_char tmp, padlen, pad = 0;
1132 	u_int authlen = 0, aadlen = 0;
1133 	u_int len;
1134 	struct sshenc *enc   = NULL;
1135 	struct sshmac *mac   = NULL;
1136 	struct sshcomp *comp = NULL;
1137 	int r, block_size;
1138 
1139 	if (state->newkeys[MODE_OUT] != NULL) {
1140 		enc  = &state->newkeys[MODE_OUT]->enc;
1141 		mac  = &state->newkeys[MODE_OUT]->mac;
1142 		comp = &state->newkeys[MODE_OUT]->comp;
1143 		/* disable mac for authenticated encryption */
1144 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
1145 			mac = NULL;
1146 	}
1147 	block_size = enc ? enc->block_size : 8;
1148 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1149 
1150 	type = (sshbuf_ptr(state->outgoing_packet))[5];
1151 	if (ssh_packet_log_type(type))
1152 		debug3("send packet: type %u", type);
1153 #ifdef PACKET_DEBUG
1154 	fprintf(stderr, "plain:     ");
1155 	sshbuf_dump(state->outgoing_packet, stderr);
1156 #endif
1157 
1158 	if (comp && comp->enabled) {
1159 		len = sshbuf_len(state->outgoing_packet);
1160 		/* skip header, compress only payload */
1161 		if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1162 			goto out;
1163 		sshbuf_reset(state->compression_buffer);
1164 		if ((r = compress_buffer(ssh, state->outgoing_packet,
1165 		    state->compression_buffer)) != 0)
1166 			goto out;
1167 		sshbuf_reset(state->outgoing_packet);
1168 		if ((r = sshbuf_put(state->outgoing_packet,
1169 		    "\0\0\0\0\0", 5)) != 0 ||
1170 		    (r = sshbuf_putb(state->outgoing_packet,
1171 		    state->compression_buffer)) != 0)
1172 			goto out;
1173 		DBG(debug("compression: raw %d compressed %zd", len,
1174 		    sshbuf_len(state->outgoing_packet)));
1175 	}
1176 
1177 	/* sizeof (packet_len + pad_len + payload) */
1178 	len = sshbuf_len(state->outgoing_packet);
1179 
1180 	/*
1181 	 * calc size of padding, alloc space, get random data,
1182 	 * minimum padding is 4 bytes
1183 	 */
1184 	len -= aadlen; /* packet length is not encrypted for EtM modes */
1185 	padlen = block_size - (len % block_size);
1186 	if (padlen < 4)
1187 		padlen += block_size;
1188 	if (state->extra_pad) {
1189 		tmp = state->extra_pad;
1190 		state->extra_pad =
1191 		    ROUNDUP(state->extra_pad, block_size);
1192 		/* check if roundup overflowed */
1193 		if (state->extra_pad < tmp)
1194 			return SSH_ERR_INVALID_ARGUMENT;
1195 		tmp = (len + padlen) % state->extra_pad;
1196 		/* Check whether pad calculation below will underflow */
1197 		if (tmp > state->extra_pad)
1198 			return SSH_ERR_INVALID_ARGUMENT;
1199 		pad = state->extra_pad - tmp;
1200 		DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
1201 		    __func__, pad, len, padlen, state->extra_pad));
1202 		tmp = padlen;
1203 		padlen += pad;
1204 		/* Check whether padlen calculation overflowed */
1205 		if (padlen < tmp)
1206 			return SSH_ERR_INVALID_ARGUMENT; /* overflow */
1207 		state->extra_pad = 0;
1208 	}
1209 	if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1210 		goto out;
1211 	if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
1212 		/* random padding */
1213 		arc4random_buf(cp, padlen);
1214 	} else {
1215 		/* clear padding */
1216 		explicit_bzero(cp, padlen);
1217 	}
1218 	/* sizeof (packet_len + pad_len + payload + padding) */
1219 	len = sshbuf_len(state->outgoing_packet);
1220 	cp = sshbuf_mutable_ptr(state->outgoing_packet);
1221 	if (cp == NULL) {
1222 		r = SSH_ERR_INTERNAL_ERROR;
1223 		goto out;
1224 	}
1225 	/* packet_length includes payload, padding and padding length field */
1226 	POKE_U32(cp, len - 4);
1227 	cp[4] = padlen;
1228 	DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1229 	    len, padlen, aadlen));
1230 
1231 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
1232 	if (mac && mac->enabled && !mac->etm) {
1233 		if ((r = mac_compute(mac, state->p_send.seqnr,
1234 		    sshbuf_ptr(state->outgoing_packet), len,
1235 		    macbuf, sizeof(macbuf))) != 0)
1236 			goto out;
1237 		DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1238 	}
1239 	/* encrypt packet and append to output buffer. */
1240 	if ((r = sshbuf_reserve(state->output,
1241 	    sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1242 		goto out;
1243 	if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
1244 	    sshbuf_ptr(state->outgoing_packet),
1245 	    len - aadlen, aadlen, authlen)) != 0)
1246 		goto out;
1247 	/* append unencrypted MAC */
1248 	if (mac && mac->enabled) {
1249 		if (mac->etm) {
1250 			/* EtM: compute mac over aadlen + cipher text */
1251 			if ((r = mac_compute(mac, state->p_send.seqnr,
1252 			    cp, len, macbuf, sizeof(macbuf))) != 0)
1253 				goto out;
1254 			DBG(debug("done calc MAC(EtM) out #%d",
1255 			    state->p_send.seqnr));
1256 		}
1257 		if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1258 			goto out;
1259 	}
1260 #ifdef PACKET_DEBUG
1261 	fprintf(stderr, "encrypted: ");
1262 	sshbuf_dump(state->output, stderr);
1263 #endif
1264 	/* increment sequence number for outgoing packets */
1265 	if (++state->p_send.seqnr == 0)
1266 		logit("outgoing seqnr wraps around");
1267 	if (++state->p_send.packets == 0)
1268 		if (!(ssh->compat & SSH_BUG_NOREKEY))
1269 			return SSH_ERR_NEED_REKEY;
1270 	state->p_send.blocks += len / block_size;
1271 	state->p_send.bytes += len;
1272 	sshbuf_reset(state->outgoing_packet);
1273 
1274 	if (type == SSH2_MSG_NEWKEYS)
1275 		r = ssh_set_newkeys(ssh, MODE_OUT);
1276 	else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1277 		r = ssh_packet_enable_delayed_compress(ssh);
1278 	else
1279 		r = 0;
1280  out:
1281 	return r;
1282 }
1283 
1284 /* returns non-zero if the specified packet type is usec by KEX */
1285 static int
1286 ssh_packet_type_is_kex(u_char type)
1287 {
1288 	return
1289 	    type >= SSH2_MSG_TRANSPORT_MIN &&
1290 	    type <= SSH2_MSG_TRANSPORT_MAX &&
1291 	    type != SSH2_MSG_SERVICE_REQUEST &&
1292 	    type != SSH2_MSG_SERVICE_ACCEPT &&
1293 	    type != SSH2_MSG_EXT_INFO;
1294 }
1295 
1296 int
1297 ssh_packet_send2(struct ssh *ssh)
1298 {
1299 	struct session_state *state = ssh->state;
1300 	struct packet *p;
1301 	u_char type;
1302 	int r, need_rekey;
1303 
1304 	if (sshbuf_len(state->outgoing_packet) < 6)
1305 		return SSH_ERR_INTERNAL_ERROR;
1306 	type = sshbuf_ptr(state->outgoing_packet)[5];
1307 	need_rekey = !ssh_packet_type_is_kex(type) &&
1308 	    ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1309 
1310 	/*
1311 	 * During rekeying we can only send key exchange messages.
1312 	 * Queue everything else.
1313 	 */
1314 	if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
1315 		if (need_rekey)
1316 			debug3("%s: rekex triggered", __func__);
1317 		debug("enqueue packet: %u", type);
1318 		p = calloc(1, sizeof(*p));
1319 		if (p == NULL)
1320 			return SSH_ERR_ALLOC_FAIL;
1321 		p->type = type;
1322 		p->payload = state->outgoing_packet;
1323 		TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1324 		state->outgoing_packet = sshbuf_new();
1325 		if (state->outgoing_packet == NULL)
1326 			return SSH_ERR_ALLOC_FAIL;
1327 		if (need_rekey) {
1328 			/*
1329 			 * This packet triggered a rekey, so send the
1330 			 * KEXINIT now.
1331 			 * NB. reenters this function via kex_start_rekex().
1332 			 */
1333 			return kex_start_rekex(ssh);
1334 		}
1335 		return 0;
1336 	}
1337 
1338 	/* rekeying starts with sending KEXINIT */
1339 	if (type == SSH2_MSG_KEXINIT)
1340 		state->rekeying = 1;
1341 
1342 	if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1343 		return 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 		}
1371 	}
1372 	return 0;
1373 }
1374 
1375 /*
1376  * Waits until a packet has been received, and returns its type.  Note that
1377  * no other data is processed until this returns, so this function should not
1378  * be used during the interactive session.
1379  */
1380 
1381 int
1382 ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1383 {
1384 	struct session_state *state = ssh->state;
1385 	int len, r, ms_remain;
1386 	fd_set *setp;
1387 	char buf[8192];
1388 	struct timeval timeout, start, *timeoutp = NULL;
1389 
1390 	DBG(debug("packet_read()"));
1391 
1392 	setp = calloc(howmany(state->connection_in + 1,
1393 	    NFDBITS), sizeof(fd_mask));
1394 	if (setp == NULL)
1395 		return SSH_ERR_ALLOC_FAIL;
1396 
1397 	/*
1398 	 * Since we are blocking, ensure that all written packets have
1399 	 * been sent.
1400 	 */
1401 	if ((r = ssh_packet_write_wait(ssh)) != 0)
1402 		goto out;
1403 
1404 	/* Stay in the loop until we have received a complete packet. */
1405 	for (;;) {
1406 		/* Try to read a packet from the buffer. */
1407 		r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
1408 		if (r != 0)
1409 			break;
1410 		if (!compat20 && (
1411 		    *typep == SSH_SMSG_SUCCESS
1412 		    || *typep == SSH_SMSG_FAILURE
1413 		    || *typep == SSH_CMSG_EOF
1414 		    || *typep == SSH_CMSG_EXIT_CONFIRMATION))
1415 			if ((r = sshpkt_get_end(ssh)) != 0)
1416 				break;
1417 		/* If we got a packet, return it. */
1418 		if (*typep != SSH_MSG_NONE)
1419 			break;
1420 		/*
1421 		 * Otherwise, wait for some data to arrive, add it to the
1422 		 * buffer, and try again.
1423 		 */
1424 		memset(setp, 0, howmany(state->connection_in + 1,
1425 		    NFDBITS) * sizeof(fd_mask));
1426 		FD_SET(state->connection_in, setp);
1427 
1428 		if (state->packet_timeout_ms > 0) {
1429 			ms_remain = state->packet_timeout_ms;
1430 			timeoutp = &timeout;
1431 		}
1432 		/* Wait for some data to arrive. */
1433 		for (;;) {
1434 			if (state->packet_timeout_ms != -1) {
1435 				ms_to_timeval(&timeout, ms_remain);
1436 				gettimeofday(&start, NULL);
1437 			}
1438 			if ((r = select(state->connection_in + 1, setp,
1439 			    NULL, NULL, timeoutp)) >= 0)
1440 				break;
1441 			if (errno != EAGAIN && errno != EINTR &&
1442 			    errno != EWOULDBLOCK)
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 				logit("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 			BLACKLIST_NOTIFY(BLACKLIST_AUTH_FAIL, "ssh");
2108 			logdie("Unable to negotiate with %.200s port %d: %s. "
2109 			    "Their offer: %s", ssh_remote_ipaddr(ssh),
2110 			    ssh_remote_port(ssh), ssh_err(r),
2111 			    ssh->kex->failed_choice);
2112 		}
2113 		/* FALLTHROUGH */
2114 	default:
2115 		logdie("%s%sConnection %s %.200s port %d: %s",
2116 		    tag != NULL ? tag : "", tag != NULL ? ": " : "",
2117 		    ssh->state->server_side ? "from" : "to",
2118 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), ssh_err(r));
2119 	}
2120 }
2121 
2122 /*
2123  * Logs the error plus constructs and sends a disconnect packet, closes the
2124  * connection, and exits.  This function never returns. The error message
2125  * should not contain a newline.  The length of the formatted message must
2126  * not exceed 1024 bytes.
2127  */
2128 void
2129 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
2130 {
2131 	char buf[1024];
2132 	va_list args;
2133 	static int disconnecting = 0;
2134 	int r;
2135 
2136 	if (disconnecting)	/* Guard against recursive invocations. */
2137 		fatal("packet_disconnect called recursively.");
2138 	disconnecting = 1;
2139 
2140 	/*
2141 	 * Format the message.  Note that the caller must make sure the
2142 	 * message is of limited size.
2143 	 */
2144 	va_start(args, fmt);
2145 	vsnprintf(buf, sizeof(buf), fmt, args);
2146 	va_end(args);
2147 
2148 	/* Display the error locally */
2149 	logit("Disconnecting: %.100s", buf);
2150 
2151 	/*
2152 	 * Send the disconnect message to the other side, and wait
2153 	 * for it to get sent.
2154 	 */
2155 	if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
2156 		sshpkt_fatal(ssh, __func__, r);
2157 
2158 	if ((r = ssh_packet_write_wait(ssh)) != 0)
2159 		sshpkt_fatal(ssh, __func__, r);
2160 
2161 	/* Close the connection. */
2162 	ssh_packet_close(ssh);
2163 	cleanup_exit(255);
2164 }
2165 
2166 /*
2167  * Checks if there is any buffered output, and tries to write some of
2168  * the output.
2169  */
2170 int
2171 ssh_packet_write_poll(struct ssh *ssh)
2172 {
2173 	struct session_state *state = ssh->state;
2174 	int len = sshbuf_len(state->output);
2175 	int r;
2176 
2177 	if (len > 0) {
2178 		len = write(state->connection_out,
2179 		    sshbuf_ptr(state->output), len);
2180 		if (len == -1) {
2181 			if (errno == EINTR || errno == EAGAIN ||
2182 			    errno == EWOULDBLOCK)
2183 				return 0;
2184 			return SSH_ERR_SYSTEM_ERROR;
2185 		}
2186 		if (len == 0)
2187 			return SSH_ERR_CONN_CLOSED;
2188 		if ((r = sshbuf_consume(state->output, len)) != 0)
2189 			return r;
2190 	}
2191 	return 0;
2192 }
2193 
2194 /*
2195  * Calls packet_write_poll repeatedly until all pending output data has been
2196  * written.
2197  */
2198 int
2199 ssh_packet_write_wait(struct ssh *ssh)
2200 {
2201 	fd_set *setp;
2202 	int ret, r, ms_remain = 0;
2203 	struct timeval start, timeout, *timeoutp = NULL;
2204 	struct session_state *state = ssh->state;
2205 
2206 	setp = calloc(howmany(state->connection_out + 1,
2207 	    NFDBITS), sizeof(fd_mask));
2208 	if (setp == NULL)
2209 		return SSH_ERR_ALLOC_FAIL;
2210 	if ((r = ssh_packet_write_poll(ssh)) != 0) {
2211 		free(setp);
2212 		return r;
2213 	}
2214 	while (ssh_packet_have_data_to_write(ssh)) {
2215 		memset(setp, 0, howmany(state->connection_out + 1,
2216 		    NFDBITS) * sizeof(fd_mask));
2217 		FD_SET(state->connection_out, setp);
2218 
2219 		if (state->packet_timeout_ms > 0) {
2220 			ms_remain = state->packet_timeout_ms;
2221 			timeoutp = &timeout;
2222 		}
2223 		for (;;) {
2224 			if (state->packet_timeout_ms != -1) {
2225 				ms_to_timeval(&timeout, ms_remain);
2226 				gettimeofday(&start, NULL);
2227 			}
2228 			if ((ret = select(state->connection_out + 1,
2229 			    NULL, setp, NULL, timeoutp)) >= 0)
2230 				break;
2231 			if (errno != EAGAIN && errno != EINTR &&
2232 			    errno != EWOULDBLOCK)
2233 				break;
2234 			if (state->packet_timeout_ms == -1)
2235 				continue;
2236 			ms_subtract_diff(&start, &ms_remain);
2237 			if (ms_remain <= 0) {
2238 				ret = 0;
2239 				break;
2240 			}
2241 		}
2242 		if (ret == 0) {
2243 			free(setp);
2244 			return SSH_ERR_CONN_TIMEOUT;
2245 		}
2246 		if ((r = ssh_packet_write_poll(ssh)) != 0) {
2247 			free(setp);
2248 			return r;
2249 		}
2250 	}
2251 	free(setp);
2252 	return 0;
2253 }
2254 
2255 /* Returns true if there is buffered data to write to the connection. */
2256 
2257 int
2258 ssh_packet_have_data_to_write(struct ssh *ssh)
2259 {
2260 	return sshbuf_len(ssh->state->output) != 0;
2261 }
2262 
2263 /* Returns true if there is not too much data to write to the connection. */
2264 
2265 int
2266 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2267 {
2268 	if (ssh->state->interactive_mode)
2269 		return sshbuf_len(ssh->state->output) < 16384;
2270 	else
2271 		return sshbuf_len(ssh->state->output) < 128 * 1024;
2272 }
2273 
2274 void
2275 ssh_packet_set_tos(struct ssh *ssh, int tos)
2276 {
2277 #ifndef IP_TOS_IS_BROKEN
2278 	if (!ssh_packet_connection_is_on_socket(ssh))
2279 		return;
2280 	switch (ssh_packet_connection_af(ssh)) {
2281 # ifdef IP_TOS
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 # endif /* IP_TOS */
2290 # ifdef IPV6_TCLASS
2291 	case AF_INET6:
2292 		debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
2293 		if (setsockopt(ssh->state->connection_in,
2294 		    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
2295 			error("setsockopt IPV6_TCLASS %d: %.100s:",
2296 			    tos, strerror(errno));
2297 		break;
2298 # endif /* IPV6_TCLASS */
2299 	}
2300 #endif /* IP_TOS_IS_BROKEN */
2301 }
2302 
2303 /* Informs that the current session is interactive.  Sets IP flags for that. */
2304 
2305 void
2306 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
2307 {
2308 	struct session_state *state = ssh->state;
2309 
2310 	if (state->set_interactive_called)
2311 		return;
2312 	state->set_interactive_called = 1;
2313 
2314 	/* Record that we are in interactive mode. */
2315 	state->interactive_mode = interactive;
2316 
2317 	/* Only set socket options if using a socket.  */
2318 	if (!ssh_packet_connection_is_on_socket(ssh))
2319 		return;
2320 	set_nodelay(state->connection_in);
2321 	ssh_packet_set_tos(ssh, interactive ? qos_interactive :
2322 	    qos_bulk);
2323 }
2324 
2325 /* Returns true if the current connection is interactive. */
2326 
2327 int
2328 ssh_packet_is_interactive(struct ssh *ssh)
2329 {
2330 	return ssh->state->interactive_mode;
2331 }
2332 
2333 int
2334 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2335 {
2336 	struct session_state *state = ssh->state;
2337 
2338 	if (state->set_maxsize_called) {
2339 		logit("packet_set_maxsize: called twice: old %d new %d",
2340 		    state->max_packet_size, s);
2341 		return -1;
2342 	}
2343 	if (s < 4 * 1024 || s > 1024 * 1024) {
2344 		logit("packet_set_maxsize: bad size %d", s);
2345 		return -1;
2346 	}
2347 	state->set_maxsize_called = 1;
2348 	debug("packet_set_maxsize: setting to %d", s);
2349 	state->max_packet_size = s;
2350 	return s;
2351 }
2352 
2353 int
2354 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2355 {
2356 	return ++ssh->state->keep_alive_timeouts;
2357 }
2358 
2359 void
2360 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2361 {
2362 	ssh->state->keep_alive_timeouts = ka;
2363 }
2364 
2365 u_int
2366 ssh_packet_get_maxsize(struct ssh *ssh)
2367 {
2368 	return ssh->state->max_packet_size;
2369 }
2370 
2371 /*
2372  * 9.2.  Ignored Data Message
2373  *
2374  *   byte      SSH_MSG_IGNORE
2375  *   string    data
2376  *
2377  * All implementations MUST understand (and ignore) this message at any
2378  * time (after receiving the protocol version). No implementation is
2379  * required to send them. This message can be used as an additional
2380  * protection measure against advanced traffic analysis techniques.
2381  */
2382 void
2383 ssh_packet_send_ignore(struct ssh *ssh, int nbytes)
2384 {
2385 	u_int32_t rnd = 0;
2386 	int r, i;
2387 
2388 	if ((r = sshpkt_start(ssh, compat20 ?
2389 	    SSH2_MSG_IGNORE : SSH_MSG_IGNORE)) != 0 ||
2390 	    (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2391 		fatal("%s: %s", __func__, ssh_err(r));
2392 	for (i = 0; i < nbytes; i++) {
2393 		if (i % 4 == 0)
2394 			rnd = arc4random();
2395 		if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2396 			fatal("%s: %s", __func__, ssh_err(r));
2397 		rnd >>= 8;
2398 	}
2399 }
2400 
2401 void
2402 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, time_t seconds)
2403 {
2404 	debug3("rekey after %llu bytes, %d seconds", (unsigned long long)bytes,
2405 	    (int)seconds);
2406 	ssh->state->rekey_limit = bytes;
2407 	ssh->state->rekey_interval = seconds;
2408 }
2409 
2410 time_t
2411 ssh_packet_get_rekey_timeout(struct ssh *ssh)
2412 {
2413 	time_t seconds;
2414 
2415 	seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2416 	    monotime();
2417 	return (seconds <= 0 ? 1 : seconds);
2418 }
2419 
2420 void
2421 ssh_packet_set_server(struct ssh *ssh)
2422 {
2423 	ssh->state->server_side = 1;
2424 }
2425 
2426 void
2427 ssh_packet_set_authenticated(struct ssh *ssh)
2428 {
2429 	ssh->state->after_authentication = 1;
2430 }
2431 
2432 void *
2433 ssh_packet_get_input(struct ssh *ssh)
2434 {
2435 	return (void *)ssh->state->input;
2436 }
2437 
2438 void *
2439 ssh_packet_get_output(struct ssh *ssh)
2440 {
2441 	return (void *)ssh->state->output;
2442 }
2443 
2444 /* Reset after_authentication and reset compression in post-auth privsep */
2445 static int
2446 ssh_packet_set_postauth(struct ssh *ssh)
2447 {
2448 	int r;
2449 
2450 	debug("%s: called", __func__);
2451 	/* This was set in net child, but is not visible in user child */
2452 	ssh->state->after_authentication = 1;
2453 	ssh->state->rekeying = 0;
2454 	if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
2455 		return r;
2456 	return 0;
2457 }
2458 
2459 /* Packet state (de-)serialization for privsep */
2460 
2461 /* turn kex into a blob for packet state serialization */
2462 static int
2463 kex_to_blob(struct sshbuf *m, struct kex *kex)
2464 {
2465 	int r;
2466 
2467 	if ((r = sshbuf_put_string(m, kex->session_id,
2468 	    kex->session_id_len)) != 0 ||
2469 	    (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2470 	    (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2471 	    (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2472 	    (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2473 	    (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2474 	    (r = sshbuf_put_u32(m, kex->flags)) != 0 ||
2475 	    (r = sshbuf_put_cstring(m, kex->client_version_string)) != 0 ||
2476 	    (r = sshbuf_put_cstring(m, kex->server_version_string)) != 0)
2477 		return r;
2478 	return 0;
2479 }
2480 
2481 /* turn key exchange results into a blob for packet state serialization */
2482 static int
2483 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2484 {
2485 	struct sshbuf *b;
2486 	struct sshcipher_ctx *cc;
2487 	struct sshcomp *comp;
2488 	struct sshenc *enc;
2489 	struct sshmac *mac;
2490 	struct newkeys *newkey;
2491 	int r;
2492 
2493 	if ((newkey = ssh->state->newkeys[mode]) == NULL)
2494 		return SSH_ERR_INTERNAL_ERROR;
2495 	enc = &newkey->enc;
2496 	mac = &newkey->mac;
2497 	comp = &newkey->comp;
2498 	cc = (mode == MODE_OUT) ? ssh->state->send_context :
2499 	    ssh->state->receive_context;
2500 	if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2501 		return r;
2502 	if ((b = sshbuf_new()) == NULL)
2503 		return SSH_ERR_ALLOC_FAIL;
2504 	/* The cipher struct is constant and shared, you export pointer */
2505 	if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2506 	    (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
2507 	    (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2508 	    (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2509 	    (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2510 	    (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2511 		goto out;
2512 	if (cipher_authlen(enc->cipher) == 0) {
2513 		if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2514 		    (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2515 		    (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2516 			goto out;
2517 	}
2518 	if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2519 	    (r = sshbuf_put_cstring(b, comp->name)) != 0)
2520 		goto out;
2521 	r = sshbuf_put_stringb(m, b);
2522  out:
2523 	sshbuf_free(b);
2524 	return r;
2525 }
2526 
2527 /* serialize packet state into a blob */
2528 int
2529 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2530 {
2531 	struct session_state *state = ssh->state;
2532 	u_char *p;
2533 	size_t slen, rlen;
2534 	int r, ssh1cipher;
2535 
2536 	if (!compat20) {
2537 		ssh1cipher = cipher_ctx_get_number(state->receive_context);
2538 		slen = cipher_get_keyiv_len(state->send_context);
2539 		rlen = cipher_get_keyiv_len(state->receive_context);
2540 		if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
2541 		    (r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
2542 		    (r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
2543 		    (r = sshbuf_put_u32(m, slen)) != 0 ||
2544 		    (r = sshbuf_reserve(m, slen, &p)) != 0 ||
2545 		    (r = cipher_get_keyiv(state->send_context, p, slen)) != 0 ||
2546 		    (r = sshbuf_put_u32(m, rlen)) != 0 ||
2547 		    (r = sshbuf_reserve(m, rlen, &p)) != 0 ||
2548 		    (r = cipher_get_keyiv(state->receive_context, p, rlen)) != 0)
2549 			return r;
2550 	} else {
2551 		if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2552 		    (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2553 		    (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2554 		    (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2555 		    (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2556 		    (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2557 		    (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2558 		    (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2559 		    (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2560 		    (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2561 		    (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2562 		    (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2563 		    (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
2564 			return r;
2565 	}
2566 
2567 	slen = cipher_get_keycontext(state->send_context, NULL);
2568 	rlen = cipher_get_keycontext(state->receive_context, NULL);
2569 	if ((r = sshbuf_put_u32(m, slen)) != 0 ||
2570 	    (r = sshbuf_reserve(m, slen, &p)) != 0)
2571 		return r;
2572 	if (cipher_get_keycontext(state->send_context, p) != (int)slen)
2573 		return SSH_ERR_INTERNAL_ERROR;
2574 	if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
2575 	    (r = sshbuf_reserve(m, rlen, &p)) != 0)
2576 		return r;
2577 	if (cipher_get_keycontext(state->receive_context, p) != (int)rlen)
2578 		return SSH_ERR_INTERNAL_ERROR;
2579 	if ((r = sshbuf_put_stringb(m, state->input)) != 0 ||
2580 	    (r = sshbuf_put_stringb(m, state->output)) != 0)
2581 		return r;
2582 
2583 	return 0;
2584 }
2585 
2586 /* restore key exchange results from blob for packet state de-serialization */
2587 static int
2588 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2589 {
2590 	struct sshbuf *b = NULL;
2591 	struct sshcomp *comp;
2592 	struct sshenc *enc;
2593 	struct sshmac *mac;
2594 	struct newkeys *newkey = NULL;
2595 	size_t keylen, ivlen, maclen;
2596 	int r;
2597 
2598 	if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2599 		r = SSH_ERR_ALLOC_FAIL;
2600 		goto out;
2601 	}
2602 	if ((r = sshbuf_froms(m, &b)) != 0)
2603 		goto out;
2604 #ifdef DEBUG_PK
2605 	sshbuf_dump(b, stderr);
2606 #endif
2607 	enc = &newkey->enc;
2608 	mac = &newkey->mac;
2609 	comp = &newkey->comp;
2610 
2611 	if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2612 	    (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
2613 	    (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2614 	    (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2615 	    (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2616 	    (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2617 		goto out;
2618 	if (cipher_authlen(enc->cipher) == 0) {
2619 		if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2620 			goto out;
2621 		if ((r = mac_setup(mac, mac->name)) != 0)
2622 			goto out;
2623 		if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2624 		    (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2625 			goto out;
2626 		if (maclen > mac->key_len) {
2627 			r = SSH_ERR_INVALID_FORMAT;
2628 			goto out;
2629 		}
2630 		mac->key_len = maclen;
2631 	}
2632 	if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2633 	    (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2634 		goto out;
2635 	if (enc->name == NULL ||
2636 	    cipher_by_name(enc->name) != enc->cipher) {
2637 		r = SSH_ERR_INVALID_FORMAT;
2638 		goto out;
2639 	}
2640 	if (sshbuf_len(b) != 0) {
2641 		r = SSH_ERR_INVALID_FORMAT;
2642 		goto out;
2643 	}
2644 	enc->key_len = keylen;
2645 	enc->iv_len = ivlen;
2646 	ssh->kex->newkeys[mode] = newkey;
2647 	newkey = NULL;
2648 	r = 0;
2649  out:
2650 	free(newkey);
2651 	sshbuf_free(b);
2652 	return r;
2653 }
2654 
2655 /* restore kex from blob for packet state de-serialization */
2656 static int
2657 kex_from_blob(struct sshbuf *m, struct kex **kexp)
2658 {
2659 	struct kex *kex;
2660 	int r;
2661 
2662 	if ((kex = calloc(1, sizeof(struct kex))) == NULL ||
2663 	    (kex->my = sshbuf_new()) == NULL ||
2664 	    (kex->peer = sshbuf_new()) == NULL) {
2665 		r = SSH_ERR_ALLOC_FAIL;
2666 		goto out;
2667 	}
2668 	if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
2669 	    (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2670 	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2671 	    (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2672 	    (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2673 	    (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2674 	    (r = sshbuf_get_u32(m, &kex->flags)) != 0 ||
2675 	    (r = sshbuf_get_cstring(m, &kex->client_version_string, NULL)) != 0 ||
2676 	    (r = sshbuf_get_cstring(m, &kex->server_version_string, NULL)) != 0)
2677 		goto out;
2678 	kex->server = 1;
2679 	kex->done = 1;
2680 	r = 0;
2681  out:
2682 	if (r != 0 || kexp == NULL) {
2683 		if (kex != NULL) {
2684 			sshbuf_free(kex->my);
2685 			sshbuf_free(kex->peer);
2686 			free(kex);
2687 		}
2688 		if (kexp != NULL)
2689 			*kexp = NULL;
2690 	} else {
2691 		*kexp = kex;
2692 	}
2693 	return r;
2694 }
2695 
2696 /*
2697  * Restore packet state from content of blob 'm' (de-serialization).
2698  * Note that 'm' will be partially consumed on parsing or any other errors.
2699  */
2700 int
2701 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2702 {
2703 	struct session_state *state = ssh->state;
2704 	const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output;
2705 	size_t ssh1keylen, rlen, slen, ilen, olen;
2706 	int r;
2707 	u_int ssh1cipher = 0;
2708 
2709 	if (!compat20) {
2710 		if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 ||
2711 		    (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 ||
2712 		    (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 ||
2713 		    (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 ||
2714 		    (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0)
2715 			return r;
2716 		if (ssh1cipher > INT_MAX)
2717 			return SSH_ERR_KEY_UNKNOWN_CIPHER;
2718 		ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen,
2719 		    (int)ssh1cipher);
2720 		if (cipher_get_keyiv_len(state->send_context) != (int)slen ||
2721 		    cipher_get_keyiv_len(state->receive_context) != (int)rlen)
2722 			return SSH_ERR_INVALID_FORMAT;
2723 		if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 ||
2724 		    (r = cipher_set_keyiv(state->receive_context, ivin)) != 0)
2725 			return r;
2726 	} else {
2727 		if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2728 		    (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2729 		    (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2730 		    (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2731 		    (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2732 		    (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2733 		    (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2734 		    (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2735 		    (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2736 		    (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2737 		    (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2738 		    (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2739 		    (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2740 			return r;
2741 		/*
2742 		 * We set the time here so that in post-auth privsep slave we
2743 		 * count from the completion of the authentication.
2744 		 */
2745 		state->rekey_time = monotime();
2746 		/* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2747 		if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2748 		    (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2749 			return r;
2750 	}
2751 	if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 ||
2752 	    (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0)
2753 		return r;
2754 	if (cipher_get_keycontext(state->send_context, NULL) != (int)slen ||
2755 	    cipher_get_keycontext(state->receive_context, NULL) != (int)rlen)
2756 		return SSH_ERR_INVALID_FORMAT;
2757 	cipher_set_keycontext(state->send_context, keyout);
2758 	cipher_set_keycontext(state->receive_context, keyin);
2759 
2760 	if ((r = ssh_packet_set_postauth(ssh)) != 0)
2761 		return r;
2762 
2763 	sshbuf_reset(state->input);
2764 	sshbuf_reset(state->output);
2765 	if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2766 	    (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2767 	    (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2768 	    (r = sshbuf_put(state->output, output, olen)) != 0)
2769 		return r;
2770 
2771 	if (sshbuf_len(m))
2772 		return SSH_ERR_INVALID_FORMAT;
2773 	debug3("%s: done", __func__);
2774 	return 0;
2775 }
2776 
2777 /* NEW API */
2778 
2779 /* put data to the outgoing packet */
2780 
2781 int
2782 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2783 {
2784 	return sshbuf_put(ssh->state->outgoing_packet, v, len);
2785 }
2786 
2787 int
2788 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2789 {
2790 	return sshbuf_putb(ssh->state->outgoing_packet, b);
2791 }
2792 
2793 int
2794 sshpkt_put_u8(struct ssh *ssh, u_char val)
2795 {
2796 	return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2797 }
2798 
2799 int
2800 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2801 {
2802 	return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2803 }
2804 
2805 int
2806 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2807 {
2808 	return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2809 }
2810 
2811 int
2812 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2813 {
2814 	return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2815 }
2816 
2817 int
2818 sshpkt_put_cstring(struct ssh *ssh, const void *v)
2819 {
2820 	return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2821 }
2822 
2823 int
2824 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2825 {
2826 	return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2827 }
2828 
2829 #ifdef WITH_OPENSSL
2830 #ifdef OPENSSL_HAS_ECC
2831 int
2832 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2833 {
2834 	return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2835 }
2836 #endif /* OPENSSL_HAS_ECC */
2837 
2838 #ifdef WITH_SSH1
2839 int
2840 sshpkt_put_bignum1(struct ssh *ssh, const BIGNUM *v)
2841 {
2842 	return sshbuf_put_bignum1(ssh->state->outgoing_packet, v);
2843 }
2844 #endif /* WITH_SSH1 */
2845 
2846 int
2847 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2848 {
2849 	return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2850 }
2851 #endif /* WITH_OPENSSL */
2852 
2853 /* fetch data from the incoming packet */
2854 
2855 int
2856 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2857 {
2858 	return sshbuf_get(ssh->state->incoming_packet, valp, len);
2859 }
2860 
2861 int
2862 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2863 {
2864 	return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2865 }
2866 
2867 int
2868 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2869 {
2870 	return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2871 }
2872 
2873 int
2874 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2875 {
2876 	return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2877 }
2878 
2879 int
2880 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2881 {
2882 	return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2883 }
2884 
2885 int
2886 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2887 {
2888 	return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2889 }
2890 
2891 int
2892 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2893 {
2894 	return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2895 }
2896 
2897 #ifdef WITH_OPENSSL
2898 #ifdef OPENSSL_HAS_ECC
2899 int
2900 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2901 {
2902 	return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2903 }
2904 #endif /* OPENSSL_HAS_ECC */
2905 
2906 #ifdef WITH_SSH1
2907 int
2908 sshpkt_get_bignum1(struct ssh *ssh, BIGNUM *v)
2909 {
2910 	return sshbuf_get_bignum1(ssh->state->incoming_packet, v);
2911 }
2912 #endif /* WITH_SSH1 */
2913 
2914 int
2915 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM *v)
2916 {
2917 	return sshbuf_get_bignum2(ssh->state->incoming_packet, v);
2918 }
2919 #endif /* WITH_OPENSSL */
2920 
2921 int
2922 sshpkt_get_end(struct ssh *ssh)
2923 {
2924 	if (sshbuf_len(ssh->state->incoming_packet) > 0)
2925 		return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2926 	return 0;
2927 }
2928 
2929 const u_char *
2930 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2931 {
2932 	if (lenp != NULL)
2933 		*lenp = sshbuf_len(ssh->state->incoming_packet);
2934 	return sshbuf_ptr(ssh->state->incoming_packet);
2935 }
2936 
2937 /* start a new packet */
2938 
2939 int
2940 sshpkt_start(struct ssh *ssh, u_char type)
2941 {
2942 	u_char buf[9];
2943 	int len;
2944 
2945 	DBG(debug("packet_start[%d]", type));
2946 	len = compat20 ? 6 : 9;
2947 	memset(buf, 0, len - 1);
2948 	buf[len - 1] = type;
2949 	sshbuf_reset(ssh->state->outgoing_packet);
2950 	return sshbuf_put(ssh->state->outgoing_packet, buf, len);
2951 }
2952 
2953 static int
2954 ssh_packet_send_mux(struct ssh *ssh)
2955 {
2956 	struct session_state *state = ssh->state;
2957 	u_char type, *cp;
2958 	size_t len;
2959 	int r;
2960 
2961 	if (ssh->kex)
2962 		return SSH_ERR_INTERNAL_ERROR;
2963 	len = sshbuf_len(state->outgoing_packet);
2964 	if (len < 6)
2965 		return SSH_ERR_INTERNAL_ERROR;
2966 	cp = sshbuf_mutable_ptr(state->outgoing_packet);
2967 	type = cp[5];
2968 	if (ssh_packet_log_type(type))
2969 		debug3("%s: type %u", __func__, type);
2970 	/* drop everything, but the connection protocol */
2971 	if (type >= SSH2_MSG_CONNECTION_MIN &&
2972 	    type <= SSH2_MSG_CONNECTION_MAX) {
2973 		POKE_U32(cp, len - 4);
2974 		if ((r = sshbuf_putb(state->output,
2975 		    state->outgoing_packet)) != 0)
2976 			return r;
2977 		/* sshbuf_dump(state->output, stderr); */
2978 	}
2979 	sshbuf_reset(state->outgoing_packet);
2980 	return 0;
2981 }
2982 
2983 /* send it */
2984 
2985 int
2986 sshpkt_send(struct ssh *ssh)
2987 {
2988 	if (ssh->state && ssh->state->mux)
2989 		return ssh_packet_send_mux(ssh);
2990 	if (compat20)
2991 		return ssh_packet_send2(ssh);
2992 	else
2993 		return ssh_packet_send1(ssh);
2994 }
2995 
2996 int
2997 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
2998 {
2999 	char buf[1024];
3000 	va_list args;
3001 	int r;
3002 
3003 	va_start(args, fmt);
3004 	vsnprintf(buf, sizeof(buf), fmt, args);
3005 	va_end(args);
3006 
3007 	if (compat20) {
3008 		if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
3009 		    (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
3010 		    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
3011 		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
3012 		    (r = sshpkt_send(ssh)) != 0)
3013 			return r;
3014 	} else {
3015 		if ((r = sshpkt_start(ssh, SSH_MSG_DISCONNECT)) != 0 ||
3016 		    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
3017 		    (r = sshpkt_send(ssh)) != 0)
3018 			return r;
3019 	}
3020 	return 0;
3021 }
3022 
3023 /* roundup current message to pad bytes */
3024 int
3025 sshpkt_add_padding(struct ssh *ssh, u_char pad)
3026 {
3027 	ssh->state->extra_pad = pad;
3028 	return 0;
3029 }
3030