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