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