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