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