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