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