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