xref: /openbsd-src/usr.bin/ssh/packet.c (revision 5ad04d351680822078003e2b066cfc9680d6157d)
1 /* $OpenBSD: packet.c,v 1.196 2014/05/03 17:20:34 markus Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This file contains code implementing the packet protocol and communication
7  * with the other side.  This same code is used both on client and server side.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  *
16  * SSH2 packet format added by Markus Friedl.
17  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 #include <sys/types.h>
41 #include <sys/queue.h>
42 #include <sys/socket.h>
43 #include <sys/time.h>
44 #include <sys/param.h>
45 
46 #include <netinet/in_systm.h>
47 #include <netinet/in.h>
48 #include <netinet/ip.h>
49 
50 #include <errno.h>
51 #include <stdarg.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 #include <signal.h>
57 #include <time.h>
58 
59 #include "xmalloc.h"
60 #include "buffer.h"
61 #include "packet.h"
62 #include "crc32.h"
63 #include "compress.h"
64 #include "deattack.h"
65 #include "channels.h"
66 #include "compat.h"
67 #include "ssh1.h"
68 #include "ssh2.h"
69 #include "cipher.h"
70 #include "key.h"
71 #include "kex.h"
72 #include "mac.h"
73 #include "log.h"
74 #include "canohost.h"
75 #include "misc.h"
76 #include "ssh.h"
77 #include "roaming.h"
78 
79 #ifdef PACKET_DEBUG
80 #define DBG(x) x
81 #else
82 #define DBG(x)
83 #endif
84 
85 #define PACKET_MAX_SIZE (256 * 1024)
86 
87 struct packet_state {
88 	u_int32_t seqnr;
89 	u_int32_t packets;
90 	u_int64_t blocks;
91 	u_int64_t bytes;
92 };
93 
94 struct packet {
95 	TAILQ_ENTRY(packet) next;
96 	u_char type;
97 	Buffer payload;
98 };
99 
100 struct session_state {
101 	/*
102 	 * This variable contains the file descriptors used for
103 	 * communicating with the other side.  connection_in is used for
104 	 * reading; connection_out for writing.  These can be the same
105 	 * descriptor, in which case it is assumed to be a socket.
106 	 */
107 	int connection_in;
108 	int connection_out;
109 
110 	/* Protocol flags for the remote side. */
111 	u_int remote_protocol_flags;
112 
113 	/* Encryption context for receiving data.  Only used for decryption. */
114 	CipherContext receive_context;
115 
116 	/* Encryption context for sending data.  Only used for encryption. */
117 	CipherContext send_context;
118 
119 	/* Buffer for raw input data from the socket. */
120 	Buffer input;
121 
122 	/* Buffer for raw output data going to the socket. */
123 	Buffer output;
124 
125 	/* Buffer for the partial outgoing packet being constructed. */
126 	Buffer outgoing_packet;
127 
128 	/* Buffer for the incoming packet currently being processed. */
129 	Buffer incoming_packet;
130 
131 	/* Scratch buffer for packet compression/decompression. */
132 	Buffer compression_buffer;
133 	int compression_buffer_ready;
134 
135 	/*
136 	 * Flag indicating whether packet compression/decompression is
137 	 * enabled.
138 	 */
139 	int packet_compression;
140 
141 	/* default maximum packet size */
142 	u_int max_packet_size;
143 
144 	/* Flag indicating whether this module has been initialized. */
145 	int initialized;
146 
147 	/* Set to true if the connection is interactive. */
148 	int interactive_mode;
149 
150 	/* Set to true if we are the server side. */
151 	int server_side;
152 
153 	/* Set to true if we are authenticated. */
154 	int after_authentication;
155 
156 	int keep_alive_timeouts;
157 
158 	/* The maximum time that we will wait to send or receive a packet */
159 	int packet_timeout_ms;
160 
161 	/* Session key information for Encryption and MAC */
162 	Newkeys *newkeys[MODE_MAX];
163 	struct packet_state p_read, p_send;
164 
165 	/* Volume-based rekeying */
166 	u_int64_t max_blocks_in, max_blocks_out;
167 	u_int32_t rekey_limit;
168 
169 	/* Time-based rekeying */
170 	time_t rekey_interval;	/* how often in seconds */
171 	time_t rekey_time;	/* time of last rekeying */
172 
173 	/* Session key for protocol v1 */
174 	u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
175 	u_int ssh1_keylen;
176 
177 	/* roundup current message to extra_pad bytes */
178 	u_char extra_pad;
179 
180 	/* XXX discard incoming data after MAC error */
181 	u_int packet_discard;
182 	Mac *packet_discard_mac;
183 
184 	/* Used in packet_read_poll2() */
185 	u_int packlen;
186 
187 	/* Used in packet_send2 */
188 	int rekeying;
189 
190 	/* Used in packet_set_interactive */
191 	int set_interactive_called;
192 
193 	/* Used in packet_set_maxsize */
194 	int set_maxsize_called;
195 
196 	TAILQ_HEAD(, packet) outgoing;
197 };
198 
199 static struct session_state *active_state, *backup_state;
200 
201 static struct session_state *
202 alloc_session_state(void)
203 {
204 	struct session_state *s = xcalloc(1, sizeof(*s));
205 
206 	s->connection_in = -1;
207 	s->connection_out = -1;
208 	s->max_packet_size = 32768;
209 	s->packet_timeout_ms = -1;
210 	return s;
211 }
212 
213 /*
214  * Sets the descriptors used for communication.  Disables encryption until
215  * packet_set_encryption_key is called.
216  */
217 void
218 packet_set_connection(int fd_in, int fd_out)
219 {
220 	const Cipher *none = cipher_by_name("none");
221 
222 	if (none == NULL)
223 		fatal("packet_set_connection: cannot load cipher 'none'");
224 	if (active_state == NULL)
225 		active_state = alloc_session_state();
226 	active_state->connection_in = fd_in;
227 	active_state->connection_out = fd_out;
228 	cipher_init(&active_state->send_context, none, (const u_char *)"",
229 	    0, NULL, 0, CIPHER_ENCRYPT);
230 	cipher_init(&active_state->receive_context, none, (const u_char *)"",
231 	    0, NULL, 0, CIPHER_DECRYPT);
232 	active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
233 	if (!active_state->initialized) {
234 		active_state->initialized = 1;
235 		buffer_init(&active_state->input);
236 		buffer_init(&active_state->output);
237 		buffer_init(&active_state->outgoing_packet);
238 		buffer_init(&active_state->incoming_packet);
239 		TAILQ_INIT(&active_state->outgoing);
240 		active_state->p_send.packets = active_state->p_read.packets = 0;
241 	}
242 }
243 
244 void
245 packet_set_timeout(int timeout, int count)
246 {
247 	if (timeout <= 0 || count <= 0) {
248 		active_state->packet_timeout_ms = -1;
249 		return;
250 	}
251 	if ((INT_MAX / 1000) / count < timeout)
252 		active_state->packet_timeout_ms = INT_MAX;
253 	else
254 		active_state->packet_timeout_ms = timeout * count * 1000;
255 }
256 
257 static void
258 packet_stop_discard(void)
259 {
260 	if (active_state->packet_discard_mac) {
261 		char buf[1024];
262 
263 		memset(buf, 'a', sizeof(buf));
264 		while (buffer_len(&active_state->incoming_packet) <
265 		    PACKET_MAX_SIZE)
266 			buffer_append(&active_state->incoming_packet, buf,
267 			    sizeof(buf));
268 		(void) mac_compute(active_state->packet_discard_mac,
269 		    active_state->p_read.seqnr,
270 		    buffer_ptr(&active_state->incoming_packet),
271 		    PACKET_MAX_SIZE);
272 	}
273 	logit("Finished discarding for %.200s", get_remote_ipaddr());
274 	cleanup_exit(255);
275 }
276 
277 static void
278 packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
279 {
280 	if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm))
281 		packet_disconnect("Packet corrupt");
282 	if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
283 		active_state->packet_discard_mac = mac;
284 	if (buffer_len(&active_state->input) >= discard)
285 		packet_stop_discard();
286 	active_state->packet_discard = discard -
287 	    buffer_len(&active_state->input);
288 }
289 
290 /* Returns 1 if remote host is connected via socket, 0 if not. */
291 
292 int
293 packet_connection_is_on_socket(void)
294 {
295 	struct sockaddr_storage from, to;
296 	socklen_t fromlen, tolen;
297 
298 	/* filedescriptors in and out are the same, so it's a socket */
299 	if (active_state->connection_in == active_state->connection_out)
300 		return 1;
301 	fromlen = sizeof(from);
302 	memset(&from, 0, sizeof(from));
303 	if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
304 	    &fromlen) < 0)
305 		return 0;
306 	tolen = sizeof(to);
307 	memset(&to, 0, sizeof(to));
308 	if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
309 	    &tolen) < 0)
310 		return 0;
311 	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
312 		return 0;
313 	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
314 		return 0;
315 	return 1;
316 }
317 
318 /*
319  * Exports an IV from the CipherContext required to export the key
320  * state back from the unprivileged child to the privileged parent
321  * process.
322  */
323 
324 void
325 packet_get_keyiv(int mode, u_char *iv, u_int len)
326 {
327 	CipherContext *cc;
328 
329 	if (mode == MODE_OUT)
330 		cc = &active_state->send_context;
331 	else
332 		cc = &active_state->receive_context;
333 
334 	cipher_get_keyiv(cc, iv, len);
335 }
336 
337 int
338 packet_get_keycontext(int mode, u_char *dat)
339 {
340 	CipherContext *cc;
341 
342 	if (mode == MODE_OUT)
343 		cc = &active_state->send_context;
344 	else
345 		cc = &active_state->receive_context;
346 
347 	return (cipher_get_keycontext(cc, dat));
348 }
349 
350 void
351 packet_set_keycontext(int mode, u_char *dat)
352 {
353 	CipherContext *cc;
354 
355 	if (mode == MODE_OUT)
356 		cc = &active_state->send_context;
357 	else
358 		cc = &active_state->receive_context;
359 
360 	cipher_set_keycontext(cc, dat);
361 }
362 
363 int
364 packet_get_keyiv_len(int mode)
365 {
366 	CipherContext *cc;
367 
368 	if (mode == MODE_OUT)
369 		cc = &active_state->send_context;
370 	else
371 		cc = &active_state->receive_context;
372 
373 	return (cipher_get_keyiv_len(cc));
374 }
375 
376 void
377 packet_set_iv(int mode, u_char *dat)
378 {
379 	CipherContext *cc;
380 
381 	if (mode == MODE_OUT)
382 		cc = &active_state->send_context;
383 	else
384 		cc = &active_state->receive_context;
385 
386 	cipher_set_keyiv(cc, dat);
387 }
388 
389 int
390 packet_get_ssh1_cipher(void)
391 {
392 	return (cipher_get_number(active_state->receive_context.cipher));
393 }
394 
395 void
396 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks,
397     u_int32_t *packets, u_int64_t *bytes)
398 {
399 	struct packet_state *state;
400 
401 	state = (mode == MODE_IN) ?
402 	    &active_state->p_read : &active_state->p_send;
403 	if (seqnr)
404 		*seqnr = state->seqnr;
405 	if (blocks)
406 		*blocks = state->blocks;
407 	if (packets)
408 		*packets = state->packets;
409 	if (bytes)
410 		*bytes = state->bytes;
411 }
412 
413 void
414 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
415     u_int64_t bytes)
416 {
417 	struct packet_state *state;
418 
419 	state = (mode == MODE_IN) ?
420 	    &active_state->p_read : &active_state->p_send;
421 	state->seqnr = seqnr;
422 	state->blocks = blocks;
423 	state->packets = packets;
424 	state->bytes = bytes;
425 }
426 
427 static int
428 packet_connection_af(void)
429 {
430 	struct sockaddr_storage to;
431 	socklen_t tolen = sizeof(to);
432 
433 	memset(&to, 0, sizeof(to));
434 	if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
435 	    &tolen) < 0)
436 		return 0;
437 	return to.ss_family;
438 }
439 
440 /* Sets the connection into non-blocking mode. */
441 
442 void
443 packet_set_nonblocking(void)
444 {
445 	/* Set the socket into non-blocking mode. */
446 	set_nonblock(active_state->connection_in);
447 
448 	if (active_state->connection_out != active_state->connection_in)
449 		set_nonblock(active_state->connection_out);
450 }
451 
452 /* Returns the socket used for reading. */
453 
454 int
455 packet_get_connection_in(void)
456 {
457 	return active_state->connection_in;
458 }
459 
460 /* Returns the descriptor used for writing. */
461 
462 int
463 packet_get_connection_out(void)
464 {
465 	return active_state->connection_out;
466 }
467 
468 /* Closes the connection and clears and frees internal data structures. */
469 
470 void
471 packet_close(void)
472 {
473 	if (!active_state->initialized)
474 		return;
475 	active_state->initialized = 0;
476 	if (active_state->connection_in == active_state->connection_out) {
477 		shutdown(active_state->connection_out, SHUT_RDWR);
478 		close(active_state->connection_out);
479 	} else {
480 		close(active_state->connection_in);
481 		close(active_state->connection_out);
482 	}
483 	buffer_free(&active_state->input);
484 	buffer_free(&active_state->output);
485 	buffer_free(&active_state->outgoing_packet);
486 	buffer_free(&active_state->incoming_packet);
487 	if (active_state->compression_buffer_ready) {
488 		buffer_free(&active_state->compression_buffer);
489 		buffer_compress_uninit();
490 	}
491 	cipher_cleanup(&active_state->send_context);
492 	cipher_cleanup(&active_state->receive_context);
493 }
494 
495 /* Sets remote side protocol flags. */
496 
497 void
498 packet_set_protocol_flags(u_int protocol_flags)
499 {
500 	active_state->remote_protocol_flags = protocol_flags;
501 }
502 
503 /* Returns the remote protocol flags set earlier by the above function. */
504 
505 u_int
506 packet_get_protocol_flags(void)
507 {
508 	return active_state->remote_protocol_flags;
509 }
510 
511 /*
512  * Starts packet compression from the next packet on in both directions.
513  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
514  */
515 
516 static void
517 packet_init_compression(void)
518 {
519 	if (active_state->compression_buffer_ready == 1)
520 		return;
521 	active_state->compression_buffer_ready = 1;
522 	buffer_init(&active_state->compression_buffer);
523 }
524 
525 void
526 packet_start_compression(int level)
527 {
528 	if (active_state->packet_compression && !compat20)
529 		fatal("Compression already enabled.");
530 	active_state->packet_compression = 1;
531 	packet_init_compression();
532 	buffer_compress_init_send(level);
533 	buffer_compress_init_recv();
534 }
535 
536 /*
537  * Causes any further packets to be encrypted using the given key.  The same
538  * key is used for both sending and reception.  However, both directions are
539  * encrypted independently of each other.
540  */
541 
542 void
543 packet_set_encryption_key(const u_char *key, u_int keylen, int number)
544 {
545 	const Cipher *cipher = cipher_by_number(number);
546 
547 	if (cipher == NULL)
548 		fatal("packet_set_encryption_key: unknown cipher number %d", number);
549 	if (keylen < 20)
550 		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
551 	if (keylen > SSH_SESSION_KEY_LENGTH)
552 		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
553 	memcpy(active_state->ssh1_key, key, keylen);
554 	active_state->ssh1_keylen = keylen;
555 	cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
556 	    0, CIPHER_ENCRYPT);
557 	cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
558 	    0, CIPHER_DECRYPT);
559 }
560 
561 u_int
562 packet_get_encryption_key(u_char *key)
563 {
564 	if (key == NULL)
565 		return (active_state->ssh1_keylen);
566 	memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
567 	return (active_state->ssh1_keylen);
568 }
569 
570 /* Start constructing a packet to send. */
571 void
572 packet_start(u_char type)
573 {
574 	u_char buf[9];
575 	int len;
576 
577 	DBG(debug("packet_start[%d]", type));
578 	len = compat20 ? 6 : 9;
579 	memset(buf, 0, len - 1);
580 	buf[len - 1] = type;
581 	buffer_clear(&active_state->outgoing_packet);
582 	buffer_append(&active_state->outgoing_packet, buf, len);
583 }
584 
585 /* Append payload. */
586 void
587 packet_put_char(int value)
588 {
589 	char ch = value;
590 
591 	buffer_append(&active_state->outgoing_packet, &ch, 1);
592 }
593 
594 void
595 packet_put_int(u_int value)
596 {
597 	buffer_put_int(&active_state->outgoing_packet, value);
598 }
599 
600 void
601 packet_put_int64(u_int64_t value)
602 {
603 	buffer_put_int64(&active_state->outgoing_packet, value);
604 }
605 
606 void
607 packet_put_string(const void *buf, u_int len)
608 {
609 	buffer_put_string(&active_state->outgoing_packet, buf, len);
610 }
611 
612 void
613 packet_put_cstring(const char *str)
614 {
615 	buffer_put_cstring(&active_state->outgoing_packet, str);
616 }
617 
618 void
619 packet_put_raw(const void *buf, u_int len)
620 {
621 	buffer_append(&active_state->outgoing_packet, buf, len);
622 }
623 
624 #ifdef WITH_OPENSSL
625 void
626 packet_put_bignum(BIGNUM * value)
627 {
628 	buffer_put_bignum(&active_state->outgoing_packet, value);
629 }
630 
631 void
632 packet_put_bignum2(BIGNUM * value)
633 {
634 	buffer_put_bignum2(&active_state->outgoing_packet, value);
635 }
636 
637 void
638 packet_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
639 {
640 	buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
641 }
642 #endif
643 
644 /*
645  * Finalizes and sends the packet.  If the encryption key has been set,
646  * encrypts the packet before sending.
647  */
648 
649 static void
650 packet_send1(void)
651 {
652 	u_char buf[8], *cp;
653 	int i, padding, len;
654 	u_int checksum;
655 	u_int32_t rnd = 0;
656 
657 	/*
658 	 * If using packet compression, compress the payload of the outgoing
659 	 * packet.
660 	 */
661 	if (active_state->packet_compression) {
662 		buffer_clear(&active_state->compression_buffer);
663 		/* Skip padding. */
664 		buffer_consume(&active_state->outgoing_packet, 8);
665 		/* padding */
666 		buffer_append(&active_state->compression_buffer,
667 		    "\0\0\0\0\0\0\0\0", 8);
668 		buffer_compress(&active_state->outgoing_packet,
669 		    &active_state->compression_buffer);
670 		buffer_clear(&active_state->outgoing_packet);
671 		buffer_append(&active_state->outgoing_packet,
672 		    buffer_ptr(&active_state->compression_buffer),
673 		    buffer_len(&active_state->compression_buffer));
674 	}
675 	/* Compute packet length without padding (add checksum, remove padding). */
676 	len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
677 
678 	/* Insert padding. Initialized to zero in packet_start1() */
679 	padding = 8 - len % 8;
680 	if (!active_state->send_context.plaintext) {
681 		cp = buffer_ptr(&active_state->outgoing_packet);
682 		for (i = 0; i < padding; i++) {
683 			if (i % 4 == 0)
684 				rnd = arc4random();
685 			cp[7 - i] = rnd & 0xff;
686 			rnd >>= 8;
687 		}
688 	}
689 	buffer_consume(&active_state->outgoing_packet, 8 - padding);
690 
691 	/* Add check bytes. */
692 	checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
693 	    buffer_len(&active_state->outgoing_packet));
694 	put_u32(buf, checksum);
695 	buffer_append(&active_state->outgoing_packet, buf, 4);
696 
697 #ifdef PACKET_DEBUG
698 	fprintf(stderr, "packet_send plain: ");
699 	buffer_dump(&active_state->outgoing_packet);
700 #endif
701 
702 	/* Append to output. */
703 	put_u32(buf, len);
704 	buffer_append(&active_state->output, buf, 4);
705 	cp = buffer_append_space(&active_state->output,
706 	    buffer_len(&active_state->outgoing_packet));
707 	if (cipher_crypt(&active_state->send_context, 0, cp,
708 	    buffer_ptr(&active_state->outgoing_packet),
709 	    buffer_len(&active_state->outgoing_packet), 0, 0) != 0)
710 		fatal("%s: cipher_crypt failed", __func__);
711 
712 #ifdef PACKET_DEBUG
713 	fprintf(stderr, "encrypted: ");
714 	buffer_dump(&active_state->output);
715 #endif
716 	active_state->p_send.packets++;
717 	active_state->p_send.bytes += len +
718 	    buffer_len(&active_state->outgoing_packet);
719 	buffer_clear(&active_state->outgoing_packet);
720 
721 	/*
722 	 * Note that the packet is now only buffered in output.  It won't be
723 	 * actually sent until packet_write_wait or packet_write_poll is
724 	 * called.
725 	 */
726 }
727 
728 void
729 set_newkeys(int mode)
730 {
731 	Enc *enc;
732 	Mac *mac;
733 	Comp *comp;
734 	CipherContext *cc;
735 	u_int64_t *max_blocks;
736 	int crypt_type;
737 
738 	debug2("set_newkeys: mode %d", mode);
739 
740 	if (mode == MODE_OUT) {
741 		cc = &active_state->send_context;
742 		crypt_type = CIPHER_ENCRYPT;
743 		active_state->p_send.packets = active_state->p_send.blocks = 0;
744 		max_blocks = &active_state->max_blocks_out;
745 	} else {
746 		cc = &active_state->receive_context;
747 		crypt_type = CIPHER_DECRYPT;
748 		active_state->p_read.packets = active_state->p_read.blocks = 0;
749 		max_blocks = &active_state->max_blocks_in;
750 	}
751 	if (active_state->newkeys[mode] != NULL) {
752 		debug("set_newkeys: rekeying");
753 		cipher_cleanup(cc);
754 		enc  = &active_state->newkeys[mode]->enc;
755 		mac  = &active_state->newkeys[mode]->mac;
756 		comp = &active_state->newkeys[mode]->comp;
757 		mac_clear(mac);
758 		explicit_bzero(enc->iv,  enc->iv_len);
759 		explicit_bzero(enc->key, enc->key_len);
760 		explicit_bzero(mac->key, mac->key_len);
761 		free(enc->name);
762 		free(enc->iv);
763 		free(enc->key);
764 		free(mac->name);
765 		free(mac->key);
766 		free(comp->name);
767 		free(active_state->newkeys[mode]);
768 	}
769 	active_state->newkeys[mode] = kex_get_newkeys(mode);
770 	if (active_state->newkeys[mode] == NULL)
771 		fatal("newkeys: no keys for mode %d", mode);
772 	enc  = &active_state->newkeys[mode]->enc;
773 	mac  = &active_state->newkeys[mode]->mac;
774 	comp = &active_state->newkeys[mode]->comp;
775 	if (cipher_authlen(enc->cipher) == 0 && mac_init(mac) == 0)
776 		mac->enabled = 1;
777 	DBG(debug("cipher_init_context: %d", mode));
778 	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
779 	    enc->iv, enc->iv_len, crypt_type);
780 	/* Deleting the keys does not gain extra security */
781 	/* explicit_bzero(enc->iv,  enc->block_size);
782 	   explicit_bzero(enc->key, enc->key_len);
783 	   explicit_bzero(mac->key, mac->key_len); */
784 	if ((comp->type == COMP_ZLIB ||
785 	    (comp->type == COMP_DELAYED &&
786 	     active_state->after_authentication)) && comp->enabled == 0) {
787 		packet_init_compression();
788 		if (mode == MODE_OUT)
789 			buffer_compress_init_send(6);
790 		else
791 			buffer_compress_init_recv();
792 		comp->enabled = 1;
793 	}
794 	/*
795 	 * The 2^(blocksize*2) limit is too expensive for 3DES,
796 	 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
797 	 */
798 	if (enc->block_size >= 16)
799 		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
800 	else
801 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
802 	if (active_state->rekey_limit)
803 		*max_blocks = MIN(*max_blocks,
804 		    active_state->rekey_limit / enc->block_size);
805 }
806 
807 /*
808  * Delayed compression for SSH2 is enabled after authentication:
809  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
810  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
811  */
812 static void
813 packet_enable_delayed_compress(void)
814 {
815 	Comp *comp = NULL;
816 	int mode;
817 
818 	/*
819 	 * Remember that we are past the authentication step, so rekeying
820 	 * with COMP_DELAYED will turn on compression immediately.
821 	 */
822 	active_state->after_authentication = 1;
823 	for (mode = 0; mode < MODE_MAX; mode++) {
824 		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
825 		if (active_state->newkeys[mode] == NULL)
826 			continue;
827 		comp = &active_state->newkeys[mode]->comp;
828 		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
829 			packet_init_compression();
830 			if (mode == MODE_OUT)
831 				buffer_compress_init_send(6);
832 			else
833 				buffer_compress_init_recv();
834 			comp->enabled = 1;
835 		}
836 	}
837 }
838 
839 /*
840  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
841  */
842 static void
843 packet_send2_wrapped(void)
844 {
845 	u_char type, *cp, *macbuf = NULL;
846 	u_char padlen, pad = 0;
847 	u_int i, len, authlen = 0, aadlen = 0;
848 	u_int32_t rnd = 0;
849 	Enc *enc   = NULL;
850 	Mac *mac   = NULL;
851 	Comp *comp = NULL;
852 	int block_size;
853 
854 	if (active_state->newkeys[MODE_OUT] != NULL) {
855 		enc  = &active_state->newkeys[MODE_OUT]->enc;
856 		mac  = &active_state->newkeys[MODE_OUT]->mac;
857 		comp = &active_state->newkeys[MODE_OUT]->comp;
858 		/* disable mac for authenticated encryption */
859 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
860 			mac = NULL;
861 	}
862 	block_size = enc ? enc->block_size : 8;
863 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
864 
865 	cp = buffer_ptr(&active_state->outgoing_packet);
866 	type = cp[5];
867 
868 #ifdef PACKET_DEBUG
869 	fprintf(stderr, "plain:     ");
870 	buffer_dump(&active_state->outgoing_packet);
871 #endif
872 
873 	if (comp && comp->enabled) {
874 		len = buffer_len(&active_state->outgoing_packet);
875 		/* skip header, compress only payload */
876 		buffer_consume(&active_state->outgoing_packet, 5);
877 		buffer_clear(&active_state->compression_buffer);
878 		buffer_compress(&active_state->outgoing_packet,
879 		    &active_state->compression_buffer);
880 		buffer_clear(&active_state->outgoing_packet);
881 		buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
882 		buffer_append(&active_state->outgoing_packet,
883 		    buffer_ptr(&active_state->compression_buffer),
884 		    buffer_len(&active_state->compression_buffer));
885 		DBG(debug("compression: raw %d compressed %d", len,
886 		    buffer_len(&active_state->outgoing_packet)));
887 	}
888 
889 	/* sizeof (packet_len + pad_len + payload) */
890 	len = buffer_len(&active_state->outgoing_packet);
891 
892 	/*
893 	 * calc size of padding, alloc space, get random data,
894 	 * minimum padding is 4 bytes
895 	 */
896 	len -= aadlen; /* packet length is not encrypted for EtM modes */
897 	padlen = block_size - (len % block_size);
898 	if (padlen < 4)
899 		padlen += block_size;
900 	if (active_state->extra_pad) {
901 		/* will wrap if extra_pad+padlen > 255 */
902 		active_state->extra_pad =
903 		    roundup(active_state->extra_pad, block_size);
904 		pad = active_state->extra_pad -
905 		    ((len + padlen) % active_state->extra_pad);
906 		DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
907 		    __func__, pad, len, padlen, active_state->extra_pad));
908 		padlen += pad;
909 		active_state->extra_pad = 0;
910 	}
911 	cp = buffer_append_space(&active_state->outgoing_packet, padlen);
912 	if (enc && !active_state->send_context.plaintext) {
913 		/* random padding */
914 		for (i = 0; i < padlen; i++) {
915 			if (i % 4 == 0)
916 				rnd = arc4random();
917 			cp[i] = rnd & 0xff;
918 			rnd >>= 8;
919 		}
920 	} else {
921 		/* clear padding */
922 		explicit_bzero(cp, padlen);
923 	}
924 	/* sizeof (packet_len + pad_len + payload + padding) */
925 	len = buffer_len(&active_state->outgoing_packet);
926 	cp = buffer_ptr(&active_state->outgoing_packet);
927 	/* packet_length includes payload, padding and padding length field */
928 	put_u32(cp, len - 4);
929 	cp[4] = padlen;
930 	DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
931 	    len, padlen, aadlen));
932 
933 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
934 	if (mac && mac->enabled && !mac->etm) {
935 		macbuf = mac_compute(mac, active_state->p_send.seqnr,
936 		    buffer_ptr(&active_state->outgoing_packet), len);
937 		DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
938 	}
939 	/* encrypt packet and append to output buffer. */
940 	cp = buffer_append_space(&active_state->output, len + authlen);
941 	if (cipher_crypt(&active_state->send_context, active_state->p_send.seqnr,
942 	    cp, buffer_ptr(&active_state->outgoing_packet),
943 	    len - aadlen, aadlen, authlen) != 0)
944 		fatal("%s: cipher_crypt failed", __func__);
945 	/* append unencrypted MAC */
946 	if (mac && mac->enabled) {
947 		if (mac->etm) {
948 			/* EtM: compute mac over aadlen + cipher text */
949 			macbuf = mac_compute(mac,
950 			    active_state->p_send.seqnr, cp, len);
951 			DBG(debug("done calc MAC(EtM) out #%d",
952 			    active_state->p_send.seqnr));
953 		}
954 		buffer_append(&active_state->output, macbuf, mac->mac_len);
955 	}
956 #ifdef PACKET_DEBUG
957 	fprintf(stderr, "encrypted: ");
958 	buffer_dump(&active_state->output);
959 #endif
960 	/* increment sequence number for outgoing packets */
961 	if (++active_state->p_send.seqnr == 0)
962 		logit("outgoing seqnr wraps around");
963 	if (++active_state->p_send.packets == 0)
964 		if (!(datafellows & SSH_BUG_NOREKEY))
965 			fatal("XXX too many packets with same key");
966 	active_state->p_send.blocks += len / block_size;
967 	active_state->p_send.bytes += len;
968 	buffer_clear(&active_state->outgoing_packet);
969 
970 	if (type == SSH2_MSG_NEWKEYS)
971 		set_newkeys(MODE_OUT);
972 	else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
973 		packet_enable_delayed_compress();
974 }
975 
976 static void
977 packet_send2(void)
978 {
979 	struct packet *p;
980 	u_char type, *cp;
981 
982 	cp = buffer_ptr(&active_state->outgoing_packet);
983 	type = cp[5];
984 
985 	/* during rekeying we can only send key exchange messages */
986 	if (active_state->rekeying) {
987 		if ((type < SSH2_MSG_TRANSPORT_MIN) ||
988 		    (type > SSH2_MSG_TRANSPORT_MAX) ||
989 		    (type == SSH2_MSG_SERVICE_REQUEST) ||
990 		    (type == SSH2_MSG_SERVICE_ACCEPT)) {
991 			debug("enqueue packet: %u", type);
992 			p = xcalloc(1, sizeof(*p));
993 			p->type = type;
994 			memcpy(&p->payload, &active_state->outgoing_packet,
995 			    sizeof(Buffer));
996 			buffer_init(&active_state->outgoing_packet);
997 			TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
998 			return;
999 		}
1000 	}
1001 
1002 	/* rekeying starts with sending KEXINIT */
1003 	if (type == SSH2_MSG_KEXINIT)
1004 		active_state->rekeying = 1;
1005 
1006 	packet_send2_wrapped();
1007 
1008 	/* after a NEWKEYS message we can send the complete queue */
1009 	if (type == SSH2_MSG_NEWKEYS) {
1010 		active_state->rekeying = 0;
1011 		active_state->rekey_time = monotime();
1012 		while ((p = TAILQ_FIRST(&active_state->outgoing))) {
1013 			type = p->type;
1014 			debug("dequeue packet: %u", type);
1015 			buffer_free(&active_state->outgoing_packet);
1016 			memcpy(&active_state->outgoing_packet, &p->payload,
1017 			    sizeof(Buffer));
1018 			TAILQ_REMOVE(&active_state->outgoing, p, next);
1019 			free(p);
1020 			packet_send2_wrapped();
1021 		}
1022 	}
1023 }
1024 
1025 void
1026 packet_send(void)
1027 {
1028 	if (compat20)
1029 		packet_send2();
1030 	else
1031 		packet_send1();
1032 	DBG(debug("packet_send done"));
1033 }
1034 
1035 /*
1036  * Waits until a packet has been received, and returns its type.  Note that
1037  * no other data is processed until this returns, so this function should not
1038  * be used during the interactive session.
1039  */
1040 
1041 int
1042 packet_read_seqnr(u_int32_t *seqnr_p)
1043 {
1044 	int type, len, ret, cont, ms_remain = 0;
1045 	fd_set *setp;
1046 	char buf[8192];
1047 	struct timeval timeout, start, *timeoutp = NULL;
1048 
1049 	DBG(debug("packet_read()"));
1050 
1051 	setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1052 	    NFDBITS), sizeof(fd_mask));
1053 
1054 	/* Since we are blocking, ensure that all written packets have been sent. */
1055 	packet_write_wait();
1056 
1057 	/* Stay in the loop until we have received a complete packet. */
1058 	for (;;) {
1059 		/* Try to read a packet from the buffer. */
1060 		type = packet_read_poll_seqnr(seqnr_p);
1061 		if (!compat20 && (
1062 		    type == SSH_SMSG_SUCCESS
1063 		    || type == SSH_SMSG_FAILURE
1064 		    || type == SSH_CMSG_EOF
1065 		    || type == SSH_CMSG_EXIT_CONFIRMATION))
1066 			packet_check_eom();
1067 		/* If we got a packet, return it. */
1068 		if (type != SSH_MSG_NONE) {
1069 			free(setp);
1070 			return type;
1071 		}
1072 		/*
1073 		 * Otherwise, wait for some data to arrive, add it to the
1074 		 * buffer, and try again.
1075 		 */
1076 		memset(setp, 0, howmany(active_state->connection_in + 1,
1077 		    NFDBITS) * sizeof(fd_mask));
1078 		FD_SET(active_state->connection_in, setp);
1079 
1080 		if (active_state->packet_timeout_ms > 0) {
1081 			ms_remain = active_state->packet_timeout_ms;
1082 			timeoutp = &timeout;
1083 		}
1084 		/* Wait for some data to arrive. */
1085 		for (;;) {
1086 			if (active_state->packet_timeout_ms != -1) {
1087 				ms_to_timeval(&timeout, ms_remain);
1088 				gettimeofday(&start, NULL);
1089 			}
1090 			if ((ret = select(active_state->connection_in + 1, setp,
1091 			    NULL, NULL, timeoutp)) >= 0)
1092 				break;
1093 			if (errno != EAGAIN && errno != EINTR)
1094 				break;
1095 			if (active_state->packet_timeout_ms == -1)
1096 				continue;
1097 			ms_subtract_diff(&start, &ms_remain);
1098 			if (ms_remain <= 0) {
1099 				ret = 0;
1100 				break;
1101 			}
1102 		}
1103 		if (ret == 0) {
1104 			logit("Connection to %.200s timed out while "
1105 			    "waiting to read", get_remote_ipaddr());
1106 			cleanup_exit(255);
1107 		}
1108 		/* Read data from the socket. */
1109 		do {
1110 			cont = 0;
1111 			len = roaming_read(active_state->connection_in, buf,
1112 			    sizeof(buf), &cont);
1113 		} while (len == 0 && cont);
1114 		if (len == 0) {
1115 			logit("Connection closed by %.200s", get_remote_ipaddr());
1116 			cleanup_exit(255);
1117 		}
1118 		if (len < 0)
1119 			fatal("Read from socket failed: %.100s", strerror(errno));
1120 		/* Append it to the buffer. */
1121 		packet_process_incoming(buf, len);
1122 	}
1123 	/* NOTREACHED */
1124 }
1125 
1126 int
1127 packet_read(void)
1128 {
1129 	return packet_read_seqnr(NULL);
1130 }
1131 
1132 /*
1133  * Waits until a packet has been received, verifies that its type matches
1134  * that given, and gives a fatal error and exits if there is a mismatch.
1135  */
1136 
1137 void
1138 packet_read_expect(int expected_type)
1139 {
1140 	int type;
1141 
1142 	type = packet_read();
1143 	if (type != expected_type)
1144 		packet_disconnect("Protocol error: expected packet type %d, got %d",
1145 		    expected_type, type);
1146 }
1147 
1148 /* Checks if a full packet is available in the data received so far via
1149  * packet_process_incoming.  If so, reads the packet; otherwise returns
1150  * SSH_MSG_NONE.  This does not wait for data from the connection.
1151  *
1152  * SSH_MSG_DISCONNECT is handled specially here.  Also,
1153  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1154  * to higher levels.
1155  */
1156 
1157 static int
1158 packet_read_poll1(void)
1159 {
1160 	u_int len, padded_len;
1161 	u_char *cp, type;
1162 	u_int checksum, stored_checksum;
1163 
1164 	/* Check if input size is less than minimum packet size. */
1165 	if (buffer_len(&active_state->input) < 4 + 8)
1166 		return SSH_MSG_NONE;
1167 	/* Get length of incoming packet. */
1168 	cp = buffer_ptr(&active_state->input);
1169 	len = get_u32(cp);
1170 	if (len < 1 + 2 + 2 || len > 256 * 1024)
1171 		packet_disconnect("Bad packet length %u.", len);
1172 	padded_len = (len + 8) & ~7;
1173 
1174 	/* Check if the packet has been entirely received. */
1175 	if (buffer_len(&active_state->input) < 4 + padded_len)
1176 		return SSH_MSG_NONE;
1177 
1178 	/* The entire packet is in buffer. */
1179 
1180 	/* Consume packet length. */
1181 	buffer_consume(&active_state->input, 4);
1182 
1183 	/*
1184 	 * Cryptographic attack detector for ssh
1185 	 * (C)1998 CORE-SDI, Buenos Aires Argentina
1186 	 * Ariel Futoransky(futo@core-sdi.com)
1187 	 */
1188 	if (!active_state->receive_context.plaintext) {
1189 		switch (detect_attack(buffer_ptr(&active_state->input),
1190 		    padded_len)) {
1191 		case DEATTACK_DETECTED:
1192 			packet_disconnect("crc32 compensation attack: "
1193 			    "network attack detected");
1194 		case DEATTACK_DOS_DETECTED:
1195 			packet_disconnect("deattack denial of "
1196 			    "service detected");
1197 		}
1198 	}
1199 
1200 	/* Decrypt data to incoming_packet. */
1201 	buffer_clear(&active_state->incoming_packet);
1202 	cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1203 	if (cipher_crypt(&active_state->receive_context, 0, cp,
1204 	    buffer_ptr(&active_state->input), padded_len, 0, 0) != 0)
1205 		fatal("%s: cipher_crypt failed", __func__);
1206 
1207 	buffer_consume(&active_state->input, padded_len);
1208 
1209 #ifdef PACKET_DEBUG
1210 	fprintf(stderr, "read_poll plain: ");
1211 	buffer_dump(&active_state->incoming_packet);
1212 #endif
1213 
1214 	/* Compute packet checksum. */
1215 	checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1216 	    buffer_len(&active_state->incoming_packet) - 4);
1217 
1218 	/* Skip padding. */
1219 	buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1220 
1221 	/* Test check bytes. */
1222 	if (len != buffer_len(&active_state->incoming_packet))
1223 		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1224 		    len, buffer_len(&active_state->incoming_packet));
1225 
1226 	cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1227 	stored_checksum = get_u32(cp);
1228 	if (checksum != stored_checksum)
1229 		packet_disconnect("Corrupted check bytes on input.");
1230 	buffer_consume_end(&active_state->incoming_packet, 4);
1231 
1232 	if (active_state->packet_compression) {
1233 		buffer_clear(&active_state->compression_buffer);
1234 		buffer_uncompress(&active_state->incoming_packet,
1235 		    &active_state->compression_buffer);
1236 		buffer_clear(&active_state->incoming_packet);
1237 		buffer_append(&active_state->incoming_packet,
1238 		    buffer_ptr(&active_state->compression_buffer),
1239 		    buffer_len(&active_state->compression_buffer));
1240 	}
1241 	active_state->p_read.packets++;
1242 	active_state->p_read.bytes += padded_len + 4;
1243 	type = buffer_get_char(&active_state->incoming_packet);
1244 	if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1245 		packet_disconnect("Invalid ssh1 packet type: %d", type);
1246 	return type;
1247 }
1248 
1249 static int
1250 packet_read_poll2(u_int32_t *seqnr_p)
1251 {
1252 	u_int padlen, need;
1253 	u_char *macbuf = NULL, *cp, type;
1254 	u_int maclen, authlen = 0, aadlen = 0, block_size;
1255 	Enc *enc   = NULL;
1256 	Mac *mac   = NULL;
1257 	Comp *comp = NULL;
1258 
1259 	if (active_state->packet_discard)
1260 		return SSH_MSG_NONE;
1261 
1262 	if (active_state->newkeys[MODE_IN] != NULL) {
1263 		enc  = &active_state->newkeys[MODE_IN]->enc;
1264 		mac  = &active_state->newkeys[MODE_IN]->mac;
1265 		comp = &active_state->newkeys[MODE_IN]->comp;
1266 		/* disable mac for authenticated encryption */
1267 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
1268 			mac = NULL;
1269 	}
1270 	maclen = mac && mac->enabled ? mac->mac_len : 0;
1271 	block_size = enc ? enc->block_size : 8;
1272 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1273 
1274 	if (aadlen && active_state->packlen == 0) {
1275 		if (cipher_get_length(&active_state->receive_context,
1276 		    &active_state->packlen,
1277 		    active_state->p_read.seqnr,
1278 		    buffer_ptr(&active_state->input),
1279 		    buffer_len(&active_state->input)) != 0)
1280 			return SSH_MSG_NONE;
1281 		if (active_state->packlen < 1 + 4 ||
1282 		    active_state->packlen > PACKET_MAX_SIZE) {
1283 #ifdef PACKET_DEBUG
1284 			buffer_dump(&active_state->input);
1285 #endif
1286 			logit("Bad packet length %u.", active_state->packlen);
1287 			packet_disconnect("Packet corrupt");
1288 		}
1289 		buffer_clear(&active_state->incoming_packet);
1290 	} else if (active_state->packlen == 0) {
1291 		/*
1292 		 * check if input size is less than the cipher block size,
1293 		 * decrypt first block and extract length of incoming packet
1294 		 */
1295 		if (buffer_len(&active_state->input) < block_size)
1296 			return SSH_MSG_NONE;
1297 		buffer_clear(&active_state->incoming_packet);
1298 		cp = buffer_append_space(&active_state->incoming_packet,
1299 		    block_size);
1300 		if (cipher_crypt(&active_state->receive_context,
1301 		    active_state->p_read.seqnr, cp,
1302 		    buffer_ptr(&active_state->input), block_size, 0, 0) != 0)
1303 			fatal("Decryption integrity check failed");
1304 		cp = buffer_ptr(&active_state->incoming_packet);
1305 		active_state->packlen = get_u32(cp);
1306 		if (active_state->packlen < 1 + 4 ||
1307 		    active_state->packlen > PACKET_MAX_SIZE) {
1308 #ifdef PACKET_DEBUG
1309 			buffer_dump(&active_state->incoming_packet);
1310 #endif
1311 			logit("Bad packet length %u.", active_state->packlen);
1312 			packet_start_discard(enc, mac, active_state->packlen,
1313 			    PACKET_MAX_SIZE);
1314 			return SSH_MSG_NONE;
1315 		}
1316 		buffer_consume(&active_state->input, block_size);
1317 	}
1318 	DBG(debug("input: packet len %u", active_state->packlen+4));
1319 	if (aadlen) {
1320 		/* only the payload is encrypted */
1321 		need = active_state->packlen;
1322 	} else {
1323 		/*
1324 		 * the payload size and the payload are encrypted, but we
1325 		 * have a partial packet of block_size bytes
1326 		 */
1327 		need = 4 + active_state->packlen - block_size;
1328 	}
1329 	DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1330 	    " aadlen %d", block_size, need, maclen, authlen, aadlen));
1331 	if (need % block_size != 0) {
1332 		logit("padding error: need %d block %d mod %d",
1333 		    need, block_size, need % block_size);
1334 		packet_start_discard(enc, mac, active_state->packlen,
1335 		    PACKET_MAX_SIZE - block_size);
1336 		return SSH_MSG_NONE;
1337 	}
1338 	/*
1339 	 * check if the entire packet has been received and
1340 	 * decrypt into incoming_packet:
1341 	 * 'aadlen' bytes are unencrypted, but authenticated.
1342 	 * 'need' bytes are encrypted, followed by either
1343 	 * 'authlen' bytes of authentication tag or
1344 	 * 'maclen' bytes of message authentication code.
1345 	 */
1346 	if (buffer_len(&active_state->input) < aadlen + need + authlen + maclen)
1347 		return SSH_MSG_NONE;
1348 #ifdef PACKET_DEBUG
1349 	fprintf(stderr, "read_poll enc/full: ");
1350 	buffer_dump(&active_state->input);
1351 #endif
1352 	/* EtM: compute mac over encrypted input */
1353 	if (mac && mac->enabled && mac->etm)
1354 		macbuf = mac_compute(mac, active_state->p_read.seqnr,
1355 		    buffer_ptr(&active_state->input), aadlen + need);
1356 	cp = buffer_append_space(&active_state->incoming_packet, aadlen + need);
1357 	if (cipher_crypt(&active_state->receive_context,
1358 	    active_state->p_read.seqnr, cp,
1359 	    buffer_ptr(&active_state->input), need, aadlen, authlen) != 0)
1360 		fatal("Decryption integrity check failed");
1361 	buffer_consume(&active_state->input, aadlen + need + authlen);
1362 	/*
1363 	 * compute MAC over seqnr and packet,
1364 	 * increment sequence number for incoming packet
1365 	 */
1366 	if (mac && mac->enabled) {
1367 		if (!mac->etm)
1368 			macbuf = mac_compute(mac, active_state->p_read.seqnr,
1369 			    buffer_ptr(&active_state->incoming_packet),
1370 			    buffer_len(&active_state->incoming_packet));
1371 		if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1372 		    mac->mac_len) != 0) {
1373 			logit("Corrupted MAC on input.");
1374 			if (need > PACKET_MAX_SIZE)
1375 				fatal("internal error need %d", need);
1376 			packet_start_discard(enc, mac, active_state->packlen,
1377 			    PACKET_MAX_SIZE - need);
1378 			return SSH_MSG_NONE;
1379 		}
1380 
1381 		DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1382 		buffer_consume(&active_state->input, mac->mac_len);
1383 	}
1384 	/* XXX now it's safe to use fatal/packet_disconnect */
1385 	if (seqnr_p != NULL)
1386 		*seqnr_p = active_state->p_read.seqnr;
1387 	if (++active_state->p_read.seqnr == 0)
1388 		logit("incoming seqnr wraps around");
1389 	if (++active_state->p_read.packets == 0)
1390 		if (!(datafellows & SSH_BUG_NOREKEY))
1391 			fatal("XXX too many packets with same key");
1392 	active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1393 	active_state->p_read.bytes += active_state->packlen + 4;
1394 
1395 	/* get padlen */
1396 	cp = buffer_ptr(&active_state->incoming_packet);
1397 	padlen = cp[4];
1398 	DBG(debug("input: padlen %d", padlen));
1399 	if (padlen < 4)
1400 		packet_disconnect("Corrupted padlen %d on input.", padlen);
1401 
1402 	/* skip packet size + padlen, discard padding */
1403 	buffer_consume(&active_state->incoming_packet, 4 + 1);
1404 	buffer_consume_end(&active_state->incoming_packet, padlen);
1405 
1406 	DBG(debug("input: len before de-compress %d",
1407 	    buffer_len(&active_state->incoming_packet)));
1408 	if (comp && comp->enabled) {
1409 		buffer_clear(&active_state->compression_buffer);
1410 		buffer_uncompress(&active_state->incoming_packet,
1411 		    &active_state->compression_buffer);
1412 		buffer_clear(&active_state->incoming_packet);
1413 		buffer_append(&active_state->incoming_packet,
1414 		    buffer_ptr(&active_state->compression_buffer),
1415 		    buffer_len(&active_state->compression_buffer));
1416 		DBG(debug("input: len after de-compress %d",
1417 		    buffer_len(&active_state->incoming_packet)));
1418 	}
1419 	/*
1420 	 * get packet type, implies consume.
1421 	 * return length of payload (without type field)
1422 	 */
1423 	type = buffer_get_char(&active_state->incoming_packet);
1424 	if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1425 		packet_disconnect("Invalid ssh2 packet type: %d", type);
1426 	if (type == SSH2_MSG_NEWKEYS)
1427 		set_newkeys(MODE_IN);
1428 	else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1429 	    !active_state->server_side)
1430 		packet_enable_delayed_compress();
1431 #ifdef PACKET_DEBUG
1432 	fprintf(stderr, "read/plain[%d]:\r\n", type);
1433 	buffer_dump(&active_state->incoming_packet);
1434 #endif
1435 	/* reset for next packet */
1436 	active_state->packlen = 0;
1437 	return type;
1438 }
1439 
1440 int
1441 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1442 {
1443 	u_int reason, seqnr;
1444 	u_char type;
1445 	char *msg;
1446 
1447 	for (;;) {
1448 		if (compat20) {
1449 			type = packet_read_poll2(seqnr_p);
1450 			if (type) {
1451 				active_state->keep_alive_timeouts = 0;
1452 				DBG(debug("received packet type %d", type));
1453 			}
1454 			switch (type) {
1455 			case SSH2_MSG_IGNORE:
1456 				debug3("Received SSH2_MSG_IGNORE");
1457 				break;
1458 			case SSH2_MSG_DEBUG:
1459 				packet_get_char();
1460 				msg = packet_get_string(NULL);
1461 				debug("Remote: %.900s", msg);
1462 				free(msg);
1463 				msg = packet_get_string(NULL);
1464 				free(msg);
1465 				break;
1466 			case SSH2_MSG_DISCONNECT:
1467 				reason = packet_get_int();
1468 				msg = packet_get_string(NULL);
1469 				/* Ignore normal client exit notifications */
1470 				do_log2(active_state->server_side &&
1471 				    reason == SSH2_DISCONNECT_BY_APPLICATION ?
1472 				    SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1473 				    "Received disconnect from %s: %u: %.400s",
1474 				    get_remote_ipaddr(), reason, msg);
1475 				free(msg);
1476 				cleanup_exit(255);
1477 				break;
1478 			case SSH2_MSG_UNIMPLEMENTED:
1479 				seqnr = packet_get_int();
1480 				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1481 				    seqnr);
1482 				break;
1483 			default:
1484 				return type;
1485 			}
1486 		} else {
1487 			type = packet_read_poll1();
1488 			switch (type) {
1489 			case SSH_MSG_NONE:
1490 				return SSH_MSG_NONE;
1491 			case SSH_MSG_IGNORE:
1492 				break;
1493 			case SSH_MSG_DEBUG:
1494 				msg = packet_get_string(NULL);
1495 				debug("Remote: %.900s", msg);
1496 				free(msg);
1497 				break;
1498 			case SSH_MSG_DISCONNECT:
1499 				msg = packet_get_string(NULL);
1500 				error("Received disconnect from %s: %.400s",
1501 				    get_remote_ipaddr(), msg);
1502 				cleanup_exit(255);
1503 				break;
1504 			default:
1505 				DBG(debug("received packet type %d", type));
1506 				return type;
1507 			}
1508 		}
1509 	}
1510 }
1511 
1512 /*
1513  * Buffers the given amount of input characters.  This is intended to be used
1514  * together with packet_read_poll.
1515  */
1516 
1517 void
1518 packet_process_incoming(const char *buf, u_int len)
1519 {
1520 	if (active_state->packet_discard) {
1521 		active_state->keep_alive_timeouts = 0; /* ?? */
1522 		if (len >= active_state->packet_discard)
1523 			packet_stop_discard();
1524 		active_state->packet_discard -= len;
1525 		return;
1526 	}
1527 	buffer_append(&active_state->input, buf, len);
1528 }
1529 
1530 /* Returns a character from the packet. */
1531 
1532 u_int
1533 packet_get_char(void)
1534 {
1535 	char ch;
1536 
1537 	buffer_get(&active_state->incoming_packet, &ch, 1);
1538 	return (u_char) ch;
1539 }
1540 
1541 /* Returns an integer from the packet data. */
1542 
1543 u_int
1544 packet_get_int(void)
1545 {
1546 	return buffer_get_int(&active_state->incoming_packet);
1547 }
1548 
1549 /* Returns an 64 bit integer from the packet data. */
1550 
1551 u_int64_t
1552 packet_get_int64(void)
1553 {
1554 	return buffer_get_int64(&active_state->incoming_packet);
1555 }
1556 
1557 /*
1558  * Returns an arbitrary precision integer from the packet data.  The integer
1559  * must have been initialized before this call.
1560  */
1561 
1562 #ifdef WITH_OPENSSL
1563 void
1564 packet_get_bignum(BIGNUM * value)
1565 {
1566 	buffer_get_bignum(&active_state->incoming_packet, value);
1567 }
1568 
1569 void
1570 packet_get_bignum2(BIGNUM * value)
1571 {
1572 	buffer_get_bignum2(&active_state->incoming_packet, value);
1573 }
1574 
1575 void
1576 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1577 {
1578 	buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1579 }
1580 #endif
1581 
1582 void *
1583 packet_get_raw(u_int *length_ptr)
1584 {
1585 	u_int bytes = buffer_len(&active_state->incoming_packet);
1586 
1587 	if (length_ptr != NULL)
1588 		*length_ptr = bytes;
1589 	return buffer_ptr(&active_state->incoming_packet);
1590 }
1591 
1592 int
1593 packet_remaining(void)
1594 {
1595 	return buffer_len(&active_state->incoming_packet);
1596 }
1597 
1598 /*
1599  * Returns a string from the packet data.  The string is allocated using
1600  * xmalloc; it is the responsibility of the calling program to free it when
1601  * no longer needed.  The length_ptr argument may be NULL, or point to an
1602  * integer into which the length of the string is stored.
1603  */
1604 
1605 void *
1606 packet_get_string(u_int *length_ptr)
1607 {
1608 	return buffer_get_string(&active_state->incoming_packet, length_ptr);
1609 }
1610 
1611 const void *
1612 packet_get_string_ptr(u_int *length_ptr)
1613 {
1614 	return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1615 }
1616 
1617 /* Ensures the returned string has no embedded \0 characters in it. */
1618 char *
1619 packet_get_cstring(u_int *length_ptr)
1620 {
1621 	return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1622 }
1623 
1624 /*
1625  * Sends a diagnostic message from the server to the client.  This message
1626  * can be sent at any time (but not while constructing another message). The
1627  * message is printed immediately, but only if the client is being executed
1628  * in verbose mode.  These messages are primarily intended to ease debugging
1629  * authentication problems.   The length of the formatted message must not
1630  * exceed 1024 bytes.  This will automatically call packet_write_wait.
1631  */
1632 
1633 void
1634 packet_send_debug(const char *fmt,...)
1635 {
1636 	char buf[1024];
1637 	va_list args;
1638 
1639 	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1640 		return;
1641 
1642 	va_start(args, fmt);
1643 	vsnprintf(buf, sizeof(buf), fmt, args);
1644 	va_end(args);
1645 
1646 	if (compat20) {
1647 		packet_start(SSH2_MSG_DEBUG);
1648 		packet_put_char(0);	/* bool: always display */
1649 		packet_put_cstring(buf);
1650 		packet_put_cstring("");
1651 	} else {
1652 		packet_start(SSH_MSG_DEBUG);
1653 		packet_put_cstring(buf);
1654 	}
1655 	packet_send();
1656 	packet_write_wait();
1657 }
1658 
1659 /*
1660  * Logs the error plus constructs and sends a disconnect packet, closes the
1661  * connection, and exits.  This function never returns. The error message
1662  * should not contain a newline.  The length of the formatted message must
1663  * not exceed 1024 bytes.
1664  */
1665 
1666 void
1667 packet_disconnect(const char *fmt,...)
1668 {
1669 	char buf[1024];
1670 	va_list args;
1671 	static int disconnecting = 0;
1672 
1673 	if (disconnecting)	/* Guard against recursive invocations. */
1674 		fatal("packet_disconnect called recursively.");
1675 	disconnecting = 1;
1676 
1677 	/*
1678 	 * Format the message.  Note that the caller must make sure the
1679 	 * message is of limited size.
1680 	 */
1681 	va_start(args, fmt);
1682 	vsnprintf(buf, sizeof(buf), fmt, args);
1683 	va_end(args);
1684 
1685 	/* Display the error locally */
1686 	logit("Disconnecting: %.100s", buf);
1687 
1688 	/* Send the disconnect message to the other side, and wait for it to get sent. */
1689 	if (compat20) {
1690 		packet_start(SSH2_MSG_DISCONNECT);
1691 		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1692 		packet_put_cstring(buf);
1693 		packet_put_cstring("");
1694 	} else {
1695 		packet_start(SSH_MSG_DISCONNECT);
1696 		packet_put_cstring(buf);
1697 	}
1698 	packet_send();
1699 	packet_write_wait();
1700 
1701 	/* Stop listening for connections. */
1702 	channel_close_all();
1703 
1704 	/* Close the connection. */
1705 	packet_close();
1706 	cleanup_exit(255);
1707 }
1708 
1709 /* Checks if there is any buffered output, and tries to write some of the output. */
1710 
1711 void
1712 packet_write_poll(void)
1713 {
1714 	int len = buffer_len(&active_state->output);
1715 	int cont;
1716 
1717 	if (len > 0) {
1718 		cont = 0;
1719 		len = roaming_write(active_state->connection_out,
1720 		    buffer_ptr(&active_state->output), len, &cont);
1721 		if (len == -1) {
1722 			if (errno == EINTR || errno == EAGAIN)
1723 				return;
1724 			fatal("Write failed: %.100s", strerror(errno));
1725 		}
1726 		if (len == 0 && !cont)
1727 			fatal("Write connection closed");
1728 		buffer_consume(&active_state->output, len);
1729 	}
1730 }
1731 
1732 /*
1733  * Calls packet_write_poll repeatedly until all pending output data has been
1734  * written.
1735  */
1736 
1737 void
1738 packet_write_wait(void)
1739 {
1740 	fd_set *setp;
1741 	int ret, ms_remain = 0;
1742 	struct timeval start, timeout, *timeoutp = NULL;
1743 
1744 	setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1745 	    NFDBITS), sizeof(fd_mask));
1746 	packet_write_poll();
1747 	while (packet_have_data_to_write()) {
1748 		memset(setp, 0, howmany(active_state->connection_out + 1,
1749 		    NFDBITS) * sizeof(fd_mask));
1750 		FD_SET(active_state->connection_out, setp);
1751 
1752 		if (active_state->packet_timeout_ms > 0) {
1753 			ms_remain = active_state->packet_timeout_ms;
1754 			timeoutp = &timeout;
1755 		}
1756 		for (;;) {
1757 			if (active_state->packet_timeout_ms != -1) {
1758 				ms_to_timeval(&timeout, ms_remain);
1759 				gettimeofday(&start, NULL);
1760 			}
1761 			if ((ret = select(active_state->connection_out + 1,
1762 			    NULL, setp, NULL, timeoutp)) >= 0)
1763 				break;
1764 			if (errno != EAGAIN && errno != EINTR)
1765 				break;
1766 			if (active_state->packet_timeout_ms == -1)
1767 				continue;
1768 			ms_subtract_diff(&start, &ms_remain);
1769 			if (ms_remain <= 0) {
1770 				ret = 0;
1771 				break;
1772 			}
1773 		}
1774 		if (ret == 0) {
1775 			logit("Connection to %.200s timed out while "
1776 			    "waiting to write", get_remote_ipaddr());
1777 			cleanup_exit(255);
1778 		}
1779 		packet_write_poll();
1780 	}
1781 	free(setp);
1782 }
1783 
1784 /* Returns true if there is buffered data to write to the connection. */
1785 
1786 int
1787 packet_have_data_to_write(void)
1788 {
1789 	return buffer_len(&active_state->output) != 0;
1790 }
1791 
1792 /* Returns true if there is not too much data to write to the connection. */
1793 
1794 int
1795 packet_not_very_much_data_to_write(void)
1796 {
1797 	if (active_state->interactive_mode)
1798 		return buffer_len(&active_state->output) < 16384;
1799 	else
1800 		return buffer_len(&active_state->output) < 128 * 1024;
1801 }
1802 
1803 static void
1804 packet_set_tos(int tos)
1805 {
1806 	if (!packet_connection_is_on_socket())
1807 		return;
1808 	switch (packet_connection_af()) {
1809 	case AF_INET:
1810 		debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1811 		if (setsockopt(active_state->connection_in,
1812 		    IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
1813 			error("setsockopt IP_TOS %d: %.100s:",
1814 			    tos, strerror(errno));
1815 		break;
1816 	case AF_INET6:
1817 		debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1818 		if (setsockopt(active_state->connection_in,
1819 		    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
1820 			error("setsockopt IPV6_TCLASS %d: %.100s:",
1821 			    tos, strerror(errno));
1822 		break;
1823 	}
1824 }
1825 
1826 /* Informs that the current session is interactive.  Sets IP flags for that. */
1827 
1828 void
1829 packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
1830 {
1831 	if (active_state->set_interactive_called)
1832 		return;
1833 	active_state->set_interactive_called = 1;
1834 
1835 	/* Record that we are in interactive mode. */
1836 	active_state->interactive_mode = interactive;
1837 
1838 	/* Only set socket options if using a socket.  */
1839 	if (!packet_connection_is_on_socket())
1840 		return;
1841 	set_nodelay(active_state->connection_in);
1842 	packet_set_tos(interactive ? qos_interactive : qos_bulk);
1843 }
1844 
1845 /* Returns true if the current connection is interactive. */
1846 
1847 int
1848 packet_is_interactive(void)
1849 {
1850 	return active_state->interactive_mode;
1851 }
1852 
1853 int
1854 packet_set_maxsize(u_int s)
1855 {
1856 	if (active_state->set_maxsize_called) {
1857 		logit("packet_set_maxsize: called twice: old %d new %d",
1858 		    active_state->max_packet_size, s);
1859 		return -1;
1860 	}
1861 	if (s < 4 * 1024 || s > 1024 * 1024) {
1862 		logit("packet_set_maxsize: bad size %d", s);
1863 		return -1;
1864 	}
1865 	active_state->set_maxsize_called = 1;
1866 	debug("packet_set_maxsize: setting to %d", s);
1867 	active_state->max_packet_size = s;
1868 	return s;
1869 }
1870 
1871 int
1872 packet_inc_alive_timeouts(void)
1873 {
1874 	return ++active_state->keep_alive_timeouts;
1875 }
1876 
1877 void
1878 packet_set_alive_timeouts(int ka)
1879 {
1880 	active_state->keep_alive_timeouts = ka;
1881 }
1882 
1883 u_int
1884 packet_get_maxsize(void)
1885 {
1886 	return active_state->max_packet_size;
1887 }
1888 
1889 /* roundup current message to pad bytes */
1890 void
1891 packet_add_padding(u_char pad)
1892 {
1893 	active_state->extra_pad = pad;
1894 }
1895 
1896 /*
1897  * 9.2.  Ignored Data Message
1898  *
1899  *   byte      SSH_MSG_IGNORE
1900  *   string    data
1901  *
1902  * All implementations MUST understand (and ignore) this message at any
1903  * time (after receiving the protocol version). No implementation is
1904  * required to send them. This message can be used as an additional
1905  * protection measure against advanced traffic analysis techniques.
1906  */
1907 void
1908 packet_send_ignore(int nbytes)
1909 {
1910 	u_int32_t rnd = 0;
1911 	int i;
1912 
1913 	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1914 	packet_put_int(nbytes);
1915 	for (i = 0; i < nbytes; i++) {
1916 		if (i % 4 == 0)
1917 			rnd = arc4random();
1918 		packet_put_char((u_char)rnd & 0xff);
1919 		rnd >>= 8;
1920 	}
1921 }
1922 
1923 #define MAX_PACKETS	(1U<<31)
1924 int
1925 packet_need_rekeying(void)
1926 {
1927 	if (datafellows & SSH_BUG_NOREKEY)
1928 		return 0;
1929 	return
1930 	    (active_state->p_send.packets > MAX_PACKETS) ||
1931 	    (active_state->p_read.packets > MAX_PACKETS) ||
1932 	    (active_state->max_blocks_out &&
1933 	        (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1934 	    (active_state->max_blocks_in &&
1935 	        (active_state->p_read.blocks > active_state->max_blocks_in)) ||
1936 	    (active_state->rekey_interval != 0 && active_state->rekey_time +
1937 		 active_state->rekey_interval <= monotime());
1938 }
1939 
1940 void
1941 packet_set_rekey_limits(u_int32_t bytes, time_t seconds)
1942 {
1943 	debug3("rekey after %lld bytes, %d seconds", (long long)bytes,
1944 	    (int)seconds);
1945 	active_state->rekey_limit = bytes;
1946 	active_state->rekey_interval = seconds;
1947 	/*
1948 	 * We set the time here so that in post-auth privsep slave we count
1949 	 * from the completion of the authentication.
1950 	 */
1951 	active_state->rekey_time = monotime();
1952 }
1953 
1954 time_t
1955 packet_get_rekey_timeout(void)
1956 {
1957 	time_t seconds;
1958 
1959 	seconds = active_state->rekey_time + active_state->rekey_interval -
1960 	    monotime();
1961 	return (seconds <= 0 ? 1 : seconds);
1962 }
1963 
1964 void
1965 packet_set_server(void)
1966 {
1967 	active_state->server_side = 1;
1968 }
1969 
1970 void
1971 packet_set_authenticated(void)
1972 {
1973 	active_state->after_authentication = 1;
1974 }
1975 
1976 void *
1977 packet_get_input(void)
1978 {
1979 	return (void *)&active_state->input;
1980 }
1981 
1982 void *
1983 packet_get_output(void)
1984 {
1985 	return (void *)&active_state->output;
1986 }
1987 
1988 void *
1989 packet_get_newkeys(int mode)
1990 {
1991 	return (void *)active_state->newkeys[mode];
1992 }
1993 
1994 /*
1995  * Save the state for the real connection, and use a separate state when
1996  * resuming a suspended connection.
1997  */
1998 void
1999 packet_backup_state(void)
2000 {
2001 	struct session_state *tmp;
2002 
2003 	close(active_state->connection_in);
2004 	active_state->connection_in = -1;
2005 	close(active_state->connection_out);
2006 	active_state->connection_out = -1;
2007 	if (backup_state)
2008 		tmp = backup_state;
2009 	else
2010 		tmp = alloc_session_state();
2011 	backup_state = active_state;
2012 	active_state = tmp;
2013 }
2014 
2015 /*
2016  * Swap in the old state when resuming a connecion.
2017  */
2018 void
2019 packet_restore_state(void)
2020 {
2021 	struct session_state *tmp;
2022 	void *buf;
2023 	u_int len;
2024 
2025 	tmp = backup_state;
2026 	backup_state = active_state;
2027 	active_state = tmp;
2028 	active_state->connection_in = backup_state->connection_in;
2029 	backup_state->connection_in = -1;
2030 	active_state->connection_out = backup_state->connection_out;
2031 	backup_state->connection_out = -1;
2032 	len = buffer_len(&backup_state->input);
2033 	if (len > 0) {
2034 		buf = buffer_ptr(&backup_state->input);
2035 		buffer_append(&active_state->input, buf, len);
2036 		buffer_clear(&backup_state->input);
2037 		add_recv_bytes(len);
2038 	}
2039 }
2040 
2041 /* Reset after_authentication and reset compression in post-auth privsep */
2042 void
2043 packet_set_postauth(void)
2044 {
2045 	Comp *comp;
2046 	int mode;
2047 
2048 	debug("%s: called", __func__);
2049 	/* This was set in net child, but is not visible in user child */
2050 	active_state->after_authentication = 1;
2051 	active_state->rekeying = 0;
2052 	for (mode = 0; mode < MODE_MAX; mode++) {
2053 		if (active_state->newkeys[mode] == NULL)
2054 			continue;
2055 		comp = &active_state->newkeys[mode]->comp;
2056 		if (comp && comp->enabled)
2057 			packet_init_compression();
2058 	}
2059 }
2060