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