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