xref: /freebsd/crypto/openssh/packet.c (revision c243e4902be8df1e643c76b5f18b68bb77cc5268)
1 /* $OpenBSD: packet.c,v 1.176 2012/01/25 19:40:09 markus Exp $ */
2 /* $FreeBSD$ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * This file contains code implementing the packet protocol and communication
8  * with the other side.  This same code is used both on client and server side.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  *
17  * SSH2 packet format added by Markus Friedl.
18  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39  */
40 
41 #include "includes.h"
42 
43 #include <sys/types.h>
44 #include "openbsd-compat/sys-queue.h"
45 #include <sys/param.h>
46 #include <sys/socket.h>
47 #ifdef HAVE_SYS_TIME_H
48 # include <sys/time.h>
49 #endif
50 
51 #include <netinet/in.h>
52 #include <netinet/ip.h>
53 #include <arpa/inet.h>
54 
55 #include <errno.h>
56 #include <stdarg.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <unistd.h>
61 #include <signal.h>
62 
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 "channels.h"
70 #include "compat.h"
71 #include "ssh1.h"
72 #include "ssh2.h"
73 #include "cipher.h"
74 #include "key.h"
75 #include "kex.h"
76 #include "mac.h"
77 #include "log.h"
78 #include "canohost.h"
79 #include "misc.h"
80 #include "ssh.h"
81 #include "roaming.h"
82 
83 #ifdef PACKET_DEBUG
84 #define DBG(x) x
85 #else
86 #define DBG(x)
87 #endif
88 
89 #define PACKET_MAX_SIZE (256 * 1024)
90 
91 struct packet_state {
92 	u_int32_t seqnr;
93 	u_int32_t packets;
94 	u_int64_t blocks;
95 	u_int64_t bytes;
96 };
97 
98 struct packet {
99 	TAILQ_ENTRY(packet) next;
100 	u_char type;
101 	Buffer payload;
102 };
103 
104 struct session_state {
105 	/*
106 	 * This variable contains the file descriptors used for
107 	 * communicating with the other side.  connection_in is used for
108 	 * reading; connection_out for writing.  These can be the same
109 	 * descriptor, in which case it is assumed to be a socket.
110 	 */
111 	int connection_in;
112 	int connection_out;
113 
114 	/* Protocol flags for the remote side. */
115 	u_int remote_protocol_flags;
116 
117 	/* Encryption context for receiving data.  Only used for decryption. */
118 	CipherContext receive_context;
119 
120 	/* Encryption context for sending data.  Only used for encryption. */
121 	CipherContext send_context;
122 
123 	/* Buffer for raw input data from the socket. */
124 	Buffer input;
125 
126 	/* Buffer for raw output data going to the socket. */
127 	Buffer output;
128 
129 	/* Buffer for the partial outgoing packet being constructed. */
130 	Buffer outgoing_packet;
131 
132 	/* Buffer for the incoming packet currently being processed. */
133 	Buffer incoming_packet;
134 
135 	/* Scratch buffer for packet compression/decompression. */
136 	Buffer compression_buffer;
137 	int compression_buffer_ready;
138 
139 	/*
140 	 * Flag indicating whether packet compression/decompression is
141 	 * enabled.
142 	 */
143 	int packet_compression;
144 
145 	/* default maximum packet size */
146 	u_int max_packet_size;
147 
148 	/* Flag indicating whether this module has been initialized. */
149 	int initialized;
150 
151 	/* Set to true if the connection is interactive. */
152 	int interactive_mode;
153 
154 	/* Set to true if we are the server side. */
155 	int server_side;
156 
157 	/* Set to true if we are authenticated. */
158 	int after_authentication;
159 
160 	int keep_alive_timeouts;
161 
162 	/* The maximum time that we will wait to send or receive a packet */
163 	int packet_timeout_ms;
164 
165 	/* Session key information for Encryption and MAC */
166 	Newkeys *newkeys[MODE_MAX];
167 	struct packet_state p_read, p_send;
168 
169 	u_int64_t max_blocks_in, max_blocks_out;
170 	u_int32_t rekey_limit;
171 
172 	/* Session key for protocol v1 */
173 	u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
174 	u_int ssh1_keylen;
175 
176 	/* roundup current message to extra_pad bytes */
177 	u_char extra_pad;
178 
179 	/* XXX discard incoming data after MAC error */
180 	u_int packet_discard;
181 	Mac *packet_discard_mac;
182 
183 	/* Used in packet_read_poll2() */
184 	u_int packlen;
185 
186 	/* Used in packet_send2 */
187 	int rekeying;
188 
189 	/* Used in packet_set_interactive */
190 	int set_interactive_called;
191 
192 	/* Used in packet_set_maxsize */
193 	int set_maxsize_called;
194 
195 	TAILQ_HEAD(, packet) outgoing;
196 };
197 
198 static struct session_state *active_state, *backup_state;
199 #ifdef	NONE_CIPHER_ENABLED
200 static int rekey_requested = 0;
201 #endif
202 
203 static struct session_state *
204 alloc_session_state(void)
205 {
206 	struct session_state *s = xcalloc(1, sizeof(*s));
207 
208 	s->connection_in = -1;
209 	s->connection_out = -1;
210 	s->max_packet_size = 32768;
211 	s->packet_timeout_ms = -1;
212 	return s;
213 }
214 
215 /*
216  * Sets the descriptors used for communication.  Disables encryption until
217  * packet_set_encryption_key is called.
218  */
219 void
220 packet_set_connection(int fd_in, int fd_out)
221 {
222 	Cipher *none = cipher_by_name("none");
223 
224 	if (none == NULL)
225 		fatal("packet_set_connection: cannot load cipher 'none'");
226 	if (active_state == NULL)
227 		active_state = alloc_session_state();
228 	active_state->connection_in = fd_in;
229 	active_state->connection_out = fd_out;
230 	cipher_init(&active_state->send_context, none, (const u_char *)"",
231 	    0, NULL, 0, CIPHER_ENCRYPT);
232 	cipher_init(&active_state->receive_context, none, (const u_char *)"",
233 	    0, NULL, 0, CIPHER_DECRYPT);
234 	active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
235 	if (!active_state->initialized) {
236 		active_state->initialized = 1;
237 		buffer_init(&active_state->input);
238 		buffer_init(&active_state->output);
239 		buffer_init(&active_state->outgoing_packet);
240 		buffer_init(&active_state->incoming_packet);
241 		TAILQ_INIT(&active_state->outgoing);
242 		active_state->p_send.packets = active_state->p_read.packets = 0;
243 	}
244 }
245 
246 void
247 packet_set_timeout(int timeout, int count)
248 {
249 	if (timeout <= 0 || count <= 0) {
250 		active_state->packet_timeout_ms = -1;
251 		return;
252 	}
253 	if ((INT_MAX / 1000) / count < timeout)
254 		active_state->packet_timeout_ms = INT_MAX;
255 	else
256 		active_state->packet_timeout_ms = timeout * count * 1000;
257 }
258 
259 static void
260 packet_stop_discard(void)
261 {
262 	if (active_state->packet_discard_mac) {
263 		char buf[1024];
264 
265 		memset(buf, 'a', sizeof(buf));
266 		while (buffer_len(&active_state->incoming_packet) <
267 		    PACKET_MAX_SIZE)
268 			buffer_append(&active_state->incoming_packet, buf,
269 			    sizeof(buf));
270 		(void) mac_compute(active_state->packet_discard_mac,
271 		    active_state->p_read.seqnr,
272 		    buffer_ptr(&active_state->incoming_packet),
273 		    PACKET_MAX_SIZE);
274 	}
275 	logit("Finished discarding for %.200s", get_remote_ipaddr());
276 	cleanup_exit(255);
277 }
278 
279 static void
280 packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
281 {
282 	if (enc == NULL || !cipher_is_cbc(enc->cipher))
283 		packet_disconnect("Packet corrupt");
284 	if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
285 		active_state->packet_discard_mac = mac;
286 	if (buffer_len(&active_state->input) >= discard)
287 		packet_stop_discard();
288 	active_state->packet_discard = discard -
289 	    buffer_len(&active_state->input);
290 }
291 
292 /* Returns 1 if remote host is connected via socket, 0 if not. */
293 
294 int
295 packet_connection_is_on_socket(void)
296 {
297 	struct sockaddr_storage from, to;
298 	socklen_t fromlen, tolen;
299 
300 	/* filedescriptors in and out are the same, so it's a socket */
301 	if (active_state->connection_in == active_state->connection_out)
302 		return 1;
303 	fromlen = sizeof(from);
304 	memset(&from, 0, sizeof(from));
305 	if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
306 	    &fromlen) < 0)
307 		return 0;
308 	tolen = sizeof(to);
309 	memset(&to, 0, sizeof(to));
310 	if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
311 	    &tolen) < 0)
312 		return 0;
313 	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
314 		return 0;
315 	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
316 		return 0;
317 	return 1;
318 }
319 
320 /*
321  * Exports an IV from the CipherContext required to export the key
322  * state back from the unprivileged child to the privileged parent
323  * process.
324  */
325 
326 void
327 packet_get_keyiv(int mode, u_char *iv, u_int len)
328 {
329 	CipherContext *cc;
330 
331 	if (mode == MODE_OUT)
332 		cc = &active_state->send_context;
333 	else
334 		cc = &active_state->receive_context;
335 
336 	cipher_get_keyiv(cc, iv, len);
337 }
338 
339 int
340 packet_get_keycontext(int mode, u_char *dat)
341 {
342 	CipherContext *cc;
343 
344 	if (mode == MODE_OUT)
345 		cc = &active_state->send_context;
346 	else
347 		cc = &active_state->receive_context;
348 
349 	return (cipher_get_keycontext(cc, dat));
350 }
351 
352 void
353 packet_set_keycontext(int mode, u_char *dat)
354 {
355 	CipherContext *cc;
356 
357 	if (mode == MODE_OUT)
358 		cc = &active_state->send_context;
359 	else
360 		cc = &active_state->receive_context;
361 
362 	cipher_set_keycontext(cc, dat);
363 }
364 
365 int
366 packet_get_keyiv_len(int mode)
367 {
368 	CipherContext *cc;
369 
370 	if (mode == MODE_OUT)
371 		cc = &active_state->send_context;
372 	else
373 		cc = &active_state->receive_context;
374 
375 	return (cipher_get_keyiv_len(cc));
376 }
377 
378 void
379 packet_set_iv(int mode, u_char *dat)
380 {
381 	CipherContext *cc;
382 
383 	if (mode == MODE_OUT)
384 		cc = &active_state->send_context;
385 	else
386 		cc = &active_state->receive_context;
387 
388 	cipher_set_keyiv(cc, dat);
389 }
390 
391 int
392 packet_get_ssh1_cipher(void)
393 {
394 	return (cipher_get_number(active_state->receive_context.cipher));
395 }
396 
397 void
398 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks,
399     u_int32_t *packets, u_int64_t *bytes)
400 {
401 	struct packet_state *state;
402 
403 	state = (mode == MODE_IN) ?
404 	    &active_state->p_read : &active_state->p_send;
405 	if (seqnr)
406 		*seqnr = state->seqnr;
407 	if (blocks)
408 		*blocks = state->blocks;
409 	if (packets)
410 		*packets = state->packets;
411 	if (bytes)
412 		*bytes = state->bytes;
413 }
414 
415 void
416 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
417     u_int64_t bytes)
418 {
419 	struct packet_state *state;
420 
421 	state = (mode == MODE_IN) ?
422 	    &active_state->p_read : &active_state->p_send;
423 	state->seqnr = seqnr;
424 	state->blocks = blocks;
425 	state->packets = packets;
426 	state->bytes = bytes;
427 }
428 
429 static int
430 packet_connection_af(void)
431 {
432 	struct sockaddr_storage to;
433 	socklen_t tolen = sizeof(to);
434 
435 	memset(&to, 0, sizeof(to));
436 	if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
437 	    &tolen) < 0)
438 		return 0;
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 AF_INET;
443 #endif
444 	return to.ss_family;
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 void
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 }
965 
966 static void
967 packet_send2(void)
968 {
969 	struct packet *p;
970 	u_char type, *cp;
971 
972 	cp = buffer_ptr(&active_state->outgoing_packet);
973 	type = cp[5];
974 
975 	/* during rekeying we can only send key exchange messages */
976 	if (active_state->rekeying) {
977 		if ((type < SSH2_MSG_TRANSPORT_MIN) ||
978 		    (type > SSH2_MSG_TRANSPORT_MAX) ||
979 		    (type == SSH2_MSG_SERVICE_REQUEST) ||
980 		    (type == SSH2_MSG_SERVICE_ACCEPT)) {
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;
989 		}
990 	}
991 
992 	/* rekeying starts with sending KEXINIT */
993 	if (type == SSH2_MSG_KEXINIT)
994 		active_state->rekeying = 1;
995 
996 	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_send2_wrapped();
1010 		}
1011 	}
1012 }
1013 
1014 void
1015 packet_send(void)
1016 {
1017 	if (compat20)
1018 		packet_send2();
1019 	else
1020 		packet_send1();
1021 	DBG(debug("packet_send done"));
1022 }
1023 
1024 /*
1025  * Waits until a packet has been received, and returns its type.  Note that
1026  * no other data is processed until this returns, so this function should not
1027  * be used during the interactive session.
1028  */
1029 
1030 int
1031 packet_read_seqnr(u_int32_t *seqnr_p)
1032 {
1033 	int type, len, ret, ms_remain, cont;
1034 	fd_set *setp;
1035 	char buf[8192];
1036 	struct timeval timeout, start, *timeoutp = NULL;
1037 
1038 	DBG(debug("packet_read()"));
1039 
1040 	setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1041 	    NFDBITS), sizeof(fd_mask));
1042 
1043 	/* Since we are blocking, ensure that all written packets have been sent. */
1044 	packet_write_wait();
1045 
1046 	/* Stay in the loop until we have received a complete packet. */
1047 	for (;;) {
1048 		/* Try to read a packet from the buffer. */
1049 		type = packet_read_poll_seqnr(seqnr_p);
1050 		if (!compat20 && (
1051 		    type == SSH_SMSG_SUCCESS
1052 		    || type == SSH_SMSG_FAILURE
1053 		    || type == SSH_CMSG_EOF
1054 		    || type == SSH_CMSG_EXIT_CONFIRMATION))
1055 			packet_check_eom();
1056 		/* If we got a packet, return it. */
1057 		if (type != SSH_MSG_NONE) {
1058 			xfree(setp);
1059 			return type;
1060 		}
1061 		/*
1062 		 * Otherwise, wait for some data to arrive, add it to the
1063 		 * buffer, and try again.
1064 		 */
1065 		memset(setp, 0, howmany(active_state->connection_in + 1,
1066 		    NFDBITS) * sizeof(fd_mask));
1067 		FD_SET(active_state->connection_in, setp);
1068 
1069 		if (active_state->packet_timeout_ms > 0) {
1070 			ms_remain = active_state->packet_timeout_ms;
1071 			timeoutp = &timeout;
1072 		}
1073 		/* Wait for some data to arrive. */
1074 		for (;;) {
1075 			if (active_state->packet_timeout_ms != -1) {
1076 				ms_to_timeval(&timeout, ms_remain);
1077 				gettimeofday(&start, NULL);
1078 			}
1079 			if ((ret = select(active_state->connection_in + 1, setp,
1080 			    NULL, NULL, timeoutp)) >= 0)
1081 				break;
1082 			if (errno != EAGAIN && errno != EINTR &&
1083 			    errno != EWOULDBLOCK)
1084 				break;
1085 			if (active_state->packet_timeout_ms == -1)
1086 				continue;
1087 			ms_subtract_diff(&start, &ms_remain);
1088 			if (ms_remain <= 0) {
1089 				ret = 0;
1090 				break;
1091 			}
1092 		}
1093 		if (ret == 0) {
1094 			logit("Connection to %.200s timed out while "
1095 			    "waiting to read", get_remote_ipaddr());
1096 			cleanup_exit(255);
1097 		}
1098 		/* Read data from the socket. */
1099 		do {
1100 			cont = 0;
1101 			len = roaming_read(active_state->connection_in, buf,
1102 			    sizeof(buf), &cont);
1103 		} while (len == 0 && cont);
1104 		if (len == 0) {
1105 			logit("Connection closed by %.200s", get_remote_ipaddr());
1106 			cleanup_exit(255);
1107 		}
1108 		if (len < 0)
1109 			fatal("Read from socket failed: %.100s", strerror(errno));
1110 		/* Append it to the buffer. */
1111 		packet_process_incoming(buf, len);
1112 	}
1113 	/* NOTREACHED */
1114 }
1115 
1116 int
1117 packet_read(void)
1118 {
1119 	return packet_read_seqnr(NULL);
1120 }
1121 
1122 /*
1123  * Waits until a packet has been received, verifies that its type matches
1124  * that given, and gives a fatal error and exits if there is a mismatch.
1125  */
1126 
1127 void
1128 packet_read_expect(int expected_type)
1129 {
1130 	int type;
1131 
1132 	type = packet_read();
1133 	if (type != expected_type)
1134 		packet_disconnect("Protocol error: expected packet type %d, got %d",
1135 		    expected_type, type);
1136 }
1137 
1138 /* Checks if a full packet is available in the data received so far via
1139  * packet_process_incoming.  If so, reads the packet; otherwise returns
1140  * SSH_MSG_NONE.  This does not wait for data from the connection.
1141  *
1142  * SSH_MSG_DISCONNECT is handled specially here.  Also,
1143  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1144  * to higher levels.
1145  */
1146 
1147 static int
1148 packet_read_poll1(void)
1149 {
1150 	u_int len, padded_len;
1151 	u_char *cp, type;
1152 	u_int checksum, stored_checksum;
1153 
1154 	/* Check if input size is less than minimum packet size. */
1155 	if (buffer_len(&active_state->input) < 4 + 8)
1156 		return SSH_MSG_NONE;
1157 	/* Get length of incoming packet. */
1158 	cp = buffer_ptr(&active_state->input);
1159 	len = get_u32(cp);
1160 	if (len < 1 + 2 + 2 || len > 256 * 1024)
1161 		packet_disconnect("Bad packet length %u.", len);
1162 	padded_len = (len + 8) & ~7;
1163 
1164 	/* Check if the packet has been entirely received. */
1165 	if (buffer_len(&active_state->input) < 4 + padded_len)
1166 		return SSH_MSG_NONE;
1167 
1168 	/* The entire packet is in buffer. */
1169 
1170 	/* Consume packet length. */
1171 	buffer_consume(&active_state->input, 4);
1172 
1173 	/*
1174 	 * Cryptographic attack detector for ssh
1175 	 * (C)1998 CORE-SDI, Buenos Aires Argentina
1176 	 * Ariel Futoransky(futo@core-sdi.com)
1177 	 */
1178 	if (!active_state->receive_context.plaintext) {
1179 		switch (detect_attack(buffer_ptr(&active_state->input),
1180 		    padded_len)) {
1181 		case DEATTACK_DETECTED:
1182 			packet_disconnect("crc32 compensation attack: "
1183 			    "network attack detected");
1184 		case DEATTACK_DOS_DETECTED:
1185 			packet_disconnect("deattack denial of "
1186 			    "service detected");
1187 		}
1188 	}
1189 
1190 	/* Decrypt data to incoming_packet. */
1191 	buffer_clear(&active_state->incoming_packet);
1192 	cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1193 	cipher_crypt(&active_state->receive_context, cp,
1194 	    buffer_ptr(&active_state->input), padded_len);
1195 
1196 	buffer_consume(&active_state->input, padded_len);
1197 
1198 #ifdef PACKET_DEBUG
1199 	fprintf(stderr, "read_poll plain: ");
1200 	buffer_dump(&active_state->incoming_packet);
1201 #endif
1202 
1203 	/* Compute packet checksum. */
1204 	checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1205 	    buffer_len(&active_state->incoming_packet) - 4);
1206 
1207 	/* Skip padding. */
1208 	buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1209 
1210 	/* Test check bytes. */
1211 	if (len != buffer_len(&active_state->incoming_packet))
1212 		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1213 		    len, buffer_len(&active_state->incoming_packet));
1214 
1215 	cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1216 	stored_checksum = get_u32(cp);
1217 	if (checksum != stored_checksum)
1218 		packet_disconnect("Corrupted check bytes on input.");
1219 	buffer_consume_end(&active_state->incoming_packet, 4);
1220 
1221 	if (active_state->packet_compression) {
1222 		buffer_clear(&active_state->compression_buffer);
1223 		buffer_uncompress(&active_state->incoming_packet,
1224 		    &active_state->compression_buffer);
1225 		buffer_clear(&active_state->incoming_packet);
1226 		buffer_append(&active_state->incoming_packet,
1227 		    buffer_ptr(&active_state->compression_buffer),
1228 		    buffer_len(&active_state->compression_buffer));
1229 	}
1230 	active_state->p_read.packets++;
1231 	active_state->p_read.bytes += padded_len + 4;
1232 	type = buffer_get_char(&active_state->incoming_packet);
1233 	if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1234 		packet_disconnect("Invalid ssh1 packet type: %d", type);
1235 	return type;
1236 }
1237 
1238 static int
1239 packet_read_poll2(u_int32_t *seqnr_p)
1240 {
1241 	u_int padlen, need;
1242 	u_char *macbuf, *cp, type;
1243 	u_int maclen, block_size;
1244 	Enc *enc   = NULL;
1245 	Mac *mac   = NULL;
1246 	Comp *comp = NULL;
1247 
1248 	if (active_state->packet_discard)
1249 		return SSH_MSG_NONE;
1250 
1251 	if (active_state->newkeys[MODE_IN] != NULL) {
1252 		enc  = &active_state->newkeys[MODE_IN]->enc;
1253 		mac  = &active_state->newkeys[MODE_IN]->mac;
1254 		comp = &active_state->newkeys[MODE_IN]->comp;
1255 	}
1256 	maclen = mac && mac->enabled ? mac->mac_len : 0;
1257 	block_size = enc ? enc->block_size : 8;
1258 
1259 	if (active_state->packlen == 0) {
1260 		/*
1261 		 * check if input size is less than the cipher block size,
1262 		 * decrypt first block and extract length of incoming packet
1263 		 */
1264 		if (buffer_len(&active_state->input) < block_size)
1265 			return SSH_MSG_NONE;
1266 		buffer_clear(&active_state->incoming_packet);
1267 		cp = buffer_append_space(&active_state->incoming_packet,
1268 		    block_size);
1269 		cipher_crypt(&active_state->receive_context, cp,
1270 		    buffer_ptr(&active_state->input), block_size);
1271 		cp = buffer_ptr(&active_state->incoming_packet);
1272 
1273 		active_state->packlen = get_u32(cp);
1274 		if (active_state->packlen < 1 + 4 ||
1275 		    active_state->packlen > PACKET_MAX_SIZE) {
1276 #ifdef PACKET_DEBUG
1277 			buffer_dump(&active_state->incoming_packet);
1278 #endif
1279 			logit("Bad packet length %u.", active_state->packlen);
1280 			packet_start_discard(enc, mac, active_state->packlen,
1281 			    PACKET_MAX_SIZE);
1282 			return SSH_MSG_NONE;
1283 		}
1284 		DBG(debug("input: packet len %u", active_state->packlen+4));
1285 		buffer_consume(&active_state->input, block_size);
1286 	}
1287 	/* we have a partial packet of block_size bytes */
1288 	need = 4 + active_state->packlen - block_size;
1289 	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1290 	    need, maclen));
1291 	if (need % block_size != 0) {
1292 		logit("padding error: need %d block %d mod %d",
1293 		    need, block_size, need % block_size);
1294 		packet_start_discard(enc, mac, active_state->packlen,
1295 		    PACKET_MAX_SIZE - block_size);
1296 		return SSH_MSG_NONE;
1297 	}
1298 	/*
1299 	 * check if the entire packet has been received and
1300 	 * decrypt into incoming_packet
1301 	 */
1302 	if (buffer_len(&active_state->input) < need + maclen)
1303 		return SSH_MSG_NONE;
1304 #ifdef PACKET_DEBUG
1305 	fprintf(stderr, "read_poll enc/full: ");
1306 	buffer_dump(&active_state->input);
1307 #endif
1308 	cp = buffer_append_space(&active_state->incoming_packet, need);
1309 	cipher_crypt(&active_state->receive_context, cp,
1310 	    buffer_ptr(&active_state->input), need);
1311 	buffer_consume(&active_state->input, need);
1312 	/*
1313 	 * compute MAC over seqnr and packet,
1314 	 * increment sequence number for incoming packet
1315 	 */
1316 	if (mac && mac->enabled) {
1317 		macbuf = mac_compute(mac, active_state->p_read.seqnr,
1318 		    buffer_ptr(&active_state->incoming_packet),
1319 		    buffer_len(&active_state->incoming_packet));
1320 		if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1321 		    mac->mac_len) != 0) {
1322 			logit("Corrupted MAC on input.");
1323 			if (need > PACKET_MAX_SIZE)
1324 				fatal("internal error need %d", need);
1325 			packet_start_discard(enc, mac, active_state->packlen,
1326 			    PACKET_MAX_SIZE - need);
1327 			return SSH_MSG_NONE;
1328 		}
1329 
1330 		DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1331 		buffer_consume(&active_state->input, mac->mac_len);
1332 	}
1333 	/* XXX now it's safe to use fatal/packet_disconnect */
1334 	if (seqnr_p != NULL)
1335 		*seqnr_p = active_state->p_read.seqnr;
1336 	if (++active_state->p_read.seqnr == 0)
1337 		logit("incoming seqnr wraps around");
1338 	if (++active_state->p_read.packets == 0)
1339 		if (!(datafellows & SSH_BUG_NOREKEY))
1340 			fatal("XXX too many packets with same key");
1341 	active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1342 	active_state->p_read.bytes += active_state->packlen + 4;
1343 
1344 	/* get padlen */
1345 	cp = buffer_ptr(&active_state->incoming_packet);
1346 	padlen = cp[4];
1347 	DBG(debug("input: padlen %d", padlen));
1348 	if (padlen < 4)
1349 		packet_disconnect("Corrupted padlen %d on input.", padlen);
1350 
1351 	/* skip packet size + padlen, discard padding */
1352 	buffer_consume(&active_state->incoming_packet, 4 + 1);
1353 	buffer_consume_end(&active_state->incoming_packet, padlen);
1354 
1355 	DBG(debug("input: len before de-compress %d",
1356 	    buffer_len(&active_state->incoming_packet)));
1357 	if (comp && comp->enabled) {
1358 		buffer_clear(&active_state->compression_buffer);
1359 		buffer_uncompress(&active_state->incoming_packet,
1360 		    &active_state->compression_buffer);
1361 		buffer_clear(&active_state->incoming_packet);
1362 		buffer_append(&active_state->incoming_packet,
1363 		    buffer_ptr(&active_state->compression_buffer),
1364 		    buffer_len(&active_state->compression_buffer));
1365 		DBG(debug("input: len after de-compress %d",
1366 		    buffer_len(&active_state->incoming_packet)));
1367 	}
1368 	/*
1369 	 * get packet type, implies consume.
1370 	 * return length of payload (without type field)
1371 	 */
1372 	type = buffer_get_char(&active_state->incoming_packet);
1373 	if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1374 		packet_disconnect("Invalid ssh2 packet type: %d", type);
1375 	if (type == SSH2_MSG_NEWKEYS)
1376 		set_newkeys(MODE_IN);
1377 	else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1378 	    !active_state->server_side)
1379 		packet_enable_delayed_compress();
1380 #ifdef PACKET_DEBUG
1381 	fprintf(stderr, "read/plain[%d]:\r\n", type);
1382 	buffer_dump(&active_state->incoming_packet);
1383 #endif
1384 	/* reset for next packet */
1385 	active_state->packlen = 0;
1386 	return type;
1387 }
1388 
1389 int
1390 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1391 {
1392 	u_int reason, seqnr;
1393 	u_char type;
1394 	char *msg;
1395 
1396 	for (;;) {
1397 		if (compat20) {
1398 			type = packet_read_poll2(seqnr_p);
1399 			if (type) {
1400 				active_state->keep_alive_timeouts = 0;
1401 				DBG(debug("received packet type %d", type));
1402 			}
1403 			switch (type) {
1404 			case SSH2_MSG_IGNORE:
1405 				debug3("Received SSH2_MSG_IGNORE");
1406 				break;
1407 			case SSH2_MSG_DEBUG:
1408 				packet_get_char();
1409 				msg = packet_get_string(NULL);
1410 				debug("Remote: %.900s", msg);
1411 				xfree(msg);
1412 				msg = packet_get_string(NULL);
1413 				xfree(msg);
1414 				break;
1415 			case SSH2_MSG_DISCONNECT:
1416 				reason = packet_get_int();
1417 				msg = packet_get_string(NULL);
1418 				logit("Received disconnect from %s: %u: %.400s",
1419 				    get_remote_ipaddr(), reason, msg);
1420 				xfree(msg);
1421 				cleanup_exit(255);
1422 				break;
1423 			case SSH2_MSG_UNIMPLEMENTED:
1424 				seqnr = packet_get_int();
1425 				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1426 				    seqnr);
1427 				break;
1428 			default:
1429 				return type;
1430 			}
1431 		} else {
1432 			type = packet_read_poll1();
1433 			switch (type) {
1434 			case SSH_MSG_IGNORE:
1435 				break;
1436 			case SSH_MSG_DEBUG:
1437 				msg = packet_get_string(NULL);
1438 				debug("Remote: %.900s", msg);
1439 				xfree(msg);
1440 				break;
1441 			case SSH_MSG_DISCONNECT:
1442 				msg = packet_get_string(NULL);
1443 				logit("Received disconnect from %s: %.400s",
1444 				    get_remote_ipaddr(), msg);
1445 				cleanup_exit(255);
1446 				break;
1447 			default:
1448 				if (type)
1449 					DBG(debug("received packet type %d", type));
1450 				return type;
1451 			}
1452 		}
1453 	}
1454 }
1455 
1456 /*
1457  * Buffers the given amount of input characters.  This is intended to be used
1458  * together with packet_read_poll.
1459  */
1460 
1461 void
1462 packet_process_incoming(const char *buf, u_int len)
1463 {
1464 	if (active_state->packet_discard) {
1465 		active_state->keep_alive_timeouts = 0; /* ?? */
1466 		if (len >= active_state->packet_discard)
1467 			packet_stop_discard();
1468 		active_state->packet_discard -= len;
1469 		return;
1470 	}
1471 	buffer_append(&active_state->input, buf, len);
1472 }
1473 
1474 /* Returns a character from the packet. */
1475 
1476 u_int
1477 packet_get_char(void)
1478 {
1479 	char ch;
1480 
1481 	buffer_get(&active_state->incoming_packet, &ch, 1);
1482 	return (u_char) ch;
1483 }
1484 
1485 /* Returns an integer from the packet data. */
1486 
1487 u_int
1488 packet_get_int(void)
1489 {
1490 	return buffer_get_int(&active_state->incoming_packet);
1491 }
1492 
1493 /* Returns an 64 bit integer from the packet data. */
1494 
1495 u_int64_t
1496 packet_get_int64(void)
1497 {
1498 	return buffer_get_int64(&active_state->incoming_packet);
1499 }
1500 
1501 /*
1502  * Returns an arbitrary precision integer from the packet data.  The integer
1503  * must have been initialized before this call.
1504  */
1505 
1506 void
1507 packet_get_bignum(BIGNUM * value)
1508 {
1509 	buffer_get_bignum(&active_state->incoming_packet, value);
1510 }
1511 
1512 void
1513 packet_get_bignum2(BIGNUM * value)
1514 {
1515 	buffer_get_bignum2(&active_state->incoming_packet, value);
1516 }
1517 
1518 #ifdef OPENSSL_HAS_ECC
1519 void
1520 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1521 {
1522 	buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1523 }
1524 #endif
1525 
1526 void *
1527 packet_get_raw(u_int *length_ptr)
1528 {
1529 	u_int bytes = buffer_len(&active_state->incoming_packet);
1530 
1531 	if (length_ptr != NULL)
1532 		*length_ptr = bytes;
1533 	return buffer_ptr(&active_state->incoming_packet);
1534 }
1535 
1536 int
1537 packet_remaining(void)
1538 {
1539 	return buffer_len(&active_state->incoming_packet);
1540 }
1541 
1542 /*
1543  * Returns a string from the packet data.  The string is allocated using
1544  * xmalloc; it is the responsibility of the calling program to free it when
1545  * no longer needed.  The length_ptr argument may be NULL, or point to an
1546  * integer into which the length of the string is stored.
1547  */
1548 
1549 void *
1550 packet_get_string(u_int *length_ptr)
1551 {
1552 	return buffer_get_string(&active_state->incoming_packet, length_ptr);
1553 }
1554 
1555 void *
1556 packet_get_string_ptr(u_int *length_ptr)
1557 {
1558 	return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1559 }
1560 
1561 /* Ensures the returned string has no embedded \0 characters in it. */
1562 char *
1563 packet_get_cstring(u_int *length_ptr)
1564 {
1565 	return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1566 }
1567 
1568 /*
1569  * Sends a diagnostic message from the server to the client.  This message
1570  * can be sent at any time (but not while constructing another message). The
1571  * message is printed immediately, but only if the client is being executed
1572  * in verbose mode.  These messages are primarily intended to ease debugging
1573  * authentication problems.   The length of the formatted message must not
1574  * exceed 1024 bytes.  This will automatically call packet_write_wait.
1575  */
1576 
1577 void
1578 packet_send_debug(const char *fmt,...)
1579 {
1580 	char buf[1024];
1581 	va_list args;
1582 
1583 	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1584 		return;
1585 
1586 	va_start(args, fmt);
1587 	vsnprintf(buf, sizeof(buf), fmt, args);
1588 	va_end(args);
1589 
1590 	if (compat20) {
1591 		packet_start(SSH2_MSG_DEBUG);
1592 		packet_put_char(0);	/* bool: always display */
1593 		packet_put_cstring(buf);
1594 		packet_put_cstring("");
1595 	} else {
1596 		packet_start(SSH_MSG_DEBUG);
1597 		packet_put_cstring(buf);
1598 	}
1599 	packet_send();
1600 	packet_write_wait();
1601 }
1602 
1603 /*
1604  * Logs the error plus constructs and sends a disconnect packet, closes the
1605  * connection, and exits.  This function never returns. The error message
1606  * should not contain a newline.  The length of the formatted message must
1607  * not exceed 1024 bytes.
1608  */
1609 
1610 void
1611 packet_disconnect(const char *fmt,...)
1612 {
1613 	char buf[1024];
1614 	va_list args;
1615 	static int disconnecting = 0;
1616 
1617 	if (disconnecting)	/* Guard against recursive invocations. */
1618 		fatal("packet_disconnect called recursively.");
1619 	disconnecting = 1;
1620 
1621 	/*
1622 	 * Format the message.  Note that the caller must make sure the
1623 	 * message is of limited size.
1624 	 */
1625 	va_start(args, fmt);
1626 	vsnprintf(buf, sizeof(buf), fmt, args);
1627 	va_end(args);
1628 
1629 	/* Display the error locally */
1630 	logit("Disconnecting: %.100s", buf);
1631 
1632 	/* Send the disconnect message to the other side, and wait for it to get sent. */
1633 	if (compat20) {
1634 		packet_start(SSH2_MSG_DISCONNECT);
1635 		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1636 		packet_put_cstring(buf);
1637 		packet_put_cstring("");
1638 	} else {
1639 		packet_start(SSH_MSG_DISCONNECT);
1640 		packet_put_cstring(buf);
1641 	}
1642 	packet_send();
1643 	packet_write_wait();
1644 
1645 	/* Stop listening for connections. */
1646 	channel_close_all();
1647 
1648 	/* Close the connection. */
1649 	packet_close();
1650 	cleanup_exit(255);
1651 }
1652 
1653 /* Checks if there is any buffered output, and tries to write some of the output. */
1654 
1655 void
1656 packet_write_poll(void)
1657 {
1658 	int len = buffer_len(&active_state->output);
1659 	int cont;
1660 
1661 	if (len > 0) {
1662 		cont = 0;
1663 		len = roaming_write(active_state->connection_out,
1664 		    buffer_ptr(&active_state->output), len, &cont);
1665 		if (len == -1) {
1666 			if (errno == EINTR || errno == EAGAIN ||
1667 			    errno == EWOULDBLOCK)
1668 				return;
1669 			fatal("Write failed: %.100s", strerror(errno));
1670 		}
1671 		if (len == 0 && !cont)
1672 			fatal("Write connection closed");
1673 		buffer_consume(&active_state->output, len);
1674 	}
1675 }
1676 
1677 /*
1678  * Calls packet_write_poll repeatedly until all pending output data has been
1679  * written.
1680  */
1681 
1682 void
1683 packet_write_wait(void)
1684 {
1685 	fd_set *setp;
1686 	int ret, ms_remain;
1687 	struct timeval start, timeout, *timeoutp = NULL;
1688 
1689 	setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1690 	    NFDBITS), sizeof(fd_mask));
1691 	packet_write_poll();
1692 	while (packet_have_data_to_write()) {
1693 		memset(setp, 0, howmany(active_state->connection_out + 1,
1694 		    NFDBITS) * sizeof(fd_mask));
1695 		FD_SET(active_state->connection_out, setp);
1696 
1697 		if (active_state->packet_timeout_ms > 0) {
1698 			ms_remain = active_state->packet_timeout_ms;
1699 			timeoutp = &timeout;
1700 		}
1701 		for (;;) {
1702 			if (active_state->packet_timeout_ms != -1) {
1703 				ms_to_timeval(&timeout, ms_remain);
1704 				gettimeofday(&start, NULL);
1705 			}
1706 			if ((ret = select(active_state->connection_out + 1,
1707 			    NULL, setp, NULL, timeoutp)) >= 0)
1708 				break;
1709 			if (errno != EAGAIN && errno != EINTR &&
1710 			    errno != EWOULDBLOCK)
1711 				break;
1712 			if (active_state->packet_timeout_ms == -1)
1713 				continue;
1714 			ms_subtract_diff(&start, &ms_remain);
1715 			if (ms_remain <= 0) {
1716 				ret = 0;
1717 				break;
1718 			}
1719 		}
1720 		if (ret == 0) {
1721 			logit("Connection to %.200s timed out while "
1722 			    "waiting to write", get_remote_ipaddr());
1723 			cleanup_exit(255);
1724 		}
1725 		packet_write_poll();
1726 	}
1727 	xfree(setp);
1728 }
1729 
1730 /* Returns true if there is buffered data to write to the connection. */
1731 
1732 int
1733 packet_have_data_to_write(void)
1734 {
1735 	return buffer_len(&active_state->output) != 0;
1736 }
1737 
1738 /* Returns true if there is not too much data to write to the connection. */
1739 
1740 int
1741 packet_not_very_much_data_to_write(void)
1742 {
1743 	if (active_state->interactive_mode)
1744 		return buffer_len(&active_state->output) < 16384;
1745 	else
1746 		return buffer_len(&active_state->output) < 128 * 1024;
1747 }
1748 
1749 static void
1750 packet_set_tos(int tos)
1751 {
1752 #ifndef IP_TOS_IS_BROKEN
1753 	if (!packet_connection_is_on_socket())
1754 		return;
1755 	switch (packet_connection_af()) {
1756 # ifdef IP_TOS
1757 	case AF_INET:
1758 		debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1759 		if (setsockopt(active_state->connection_in,
1760 		    IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
1761 			error("setsockopt IP_TOS %d: %.100s:",
1762 			    tos, strerror(errno));
1763 		break;
1764 # endif /* IP_TOS */
1765 # ifdef IPV6_TCLASS
1766 	case AF_INET6:
1767 		debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1768 		if (setsockopt(active_state->connection_in,
1769 		    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
1770 			error("setsockopt IPV6_TCLASS %d: %.100s:",
1771 			    tos, strerror(errno));
1772 		break;
1773 # endif /* IPV6_TCLASS */
1774 	}
1775 #endif /* IP_TOS_IS_BROKEN */
1776 }
1777 
1778 /* Informs that the current session is interactive.  Sets IP flags for that. */
1779 
1780 void
1781 packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
1782 {
1783 	if (active_state->set_interactive_called)
1784 		return;
1785 	active_state->set_interactive_called = 1;
1786 
1787 	/* Record that we are in interactive mode. */
1788 	active_state->interactive_mode = interactive;
1789 
1790 	/* Only set socket options if using a socket.  */
1791 	if (!packet_connection_is_on_socket())
1792 		return;
1793 	set_nodelay(active_state->connection_in);
1794 	packet_set_tos(interactive ? qos_interactive : qos_bulk);
1795 }
1796 
1797 /* Returns true if the current connection is interactive. */
1798 
1799 int
1800 packet_is_interactive(void)
1801 {
1802 	return active_state->interactive_mode;
1803 }
1804 
1805 int
1806 packet_set_maxsize(u_int s)
1807 {
1808 	if (active_state->set_maxsize_called) {
1809 		logit("packet_set_maxsize: called twice: old %d new %d",
1810 		    active_state->max_packet_size, s);
1811 		return -1;
1812 	}
1813 	if (s < 4 * 1024 || s > 1024 * 1024) {
1814 		logit("packet_set_maxsize: bad size %d", s);
1815 		return -1;
1816 	}
1817 	active_state->set_maxsize_called = 1;
1818 	debug("packet_set_maxsize: setting to %d", s);
1819 	active_state->max_packet_size = s;
1820 	return s;
1821 }
1822 
1823 int
1824 packet_inc_alive_timeouts(void)
1825 {
1826 	return ++active_state->keep_alive_timeouts;
1827 }
1828 
1829 void
1830 packet_set_alive_timeouts(int ka)
1831 {
1832 	active_state->keep_alive_timeouts = ka;
1833 }
1834 
1835 u_int
1836 packet_get_maxsize(void)
1837 {
1838 	return active_state->max_packet_size;
1839 }
1840 
1841 /* roundup current message to pad bytes */
1842 void
1843 packet_add_padding(u_char pad)
1844 {
1845 	active_state->extra_pad = pad;
1846 }
1847 
1848 /*
1849  * 9.2.  Ignored Data Message
1850  *
1851  *   byte      SSH_MSG_IGNORE
1852  *   string    data
1853  *
1854  * All implementations MUST understand (and ignore) this message at any
1855  * time (after receiving the protocol version). No implementation is
1856  * required to send them. This message can be used as an additional
1857  * protection measure against advanced traffic analysis techniques.
1858  */
1859 void
1860 packet_send_ignore(int nbytes)
1861 {
1862 	u_int32_t rnd = 0;
1863 	int i;
1864 
1865 	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1866 	packet_put_int(nbytes);
1867 	for (i = 0; i < nbytes; i++) {
1868 		if (i % 4 == 0)
1869 			rnd = arc4random();
1870 		packet_put_char((u_char)rnd & 0xff);
1871 		rnd >>= 8;
1872 	}
1873 }
1874 
1875 #ifdef	NONE_CIPHER_ENABLED
1876 void
1877 packet_request_rekeying(void)
1878 {
1879 	rekey_requested = 1;
1880 }
1881 #endif
1882 
1883 #define MAX_PACKETS	(1U<<31)
1884 int
1885 packet_need_rekeying(void)
1886 {
1887 	if (datafellows & SSH_BUG_NOREKEY)
1888 		return 0;
1889 #ifdef	NONE_CIPHER_ENABLED
1890 	if (rekey_requested == 1) {
1891 		rekey_requested = 0;
1892 		return 1;
1893 	}
1894 #endif
1895 	return
1896 	    (active_state->p_send.packets > MAX_PACKETS) ||
1897 	    (active_state->p_read.packets > MAX_PACKETS) ||
1898 	    (active_state->max_blocks_out &&
1899 	        (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1900 	    (active_state->max_blocks_in &&
1901 	        (active_state->p_read.blocks > active_state->max_blocks_in));
1902 }
1903 
1904 void
1905 packet_set_rekey_limit(u_int32_t bytes)
1906 {
1907 	active_state->rekey_limit = bytes;
1908 }
1909 
1910 void
1911 packet_set_server(void)
1912 {
1913 	active_state->server_side = 1;
1914 }
1915 
1916 void
1917 packet_set_authenticated(void)
1918 {
1919 	active_state->after_authentication = 1;
1920 }
1921 
1922 void *
1923 packet_get_input(void)
1924 {
1925 	return (void *)&active_state->input;
1926 }
1927 
1928 void *
1929 packet_get_output(void)
1930 {
1931 	return (void *)&active_state->output;
1932 }
1933 
1934 void *
1935 packet_get_newkeys(int mode)
1936 {
1937 	return (void *)active_state->newkeys[mode];
1938 }
1939 
1940 /*
1941  * Save the state for the real connection, and use a separate state when
1942  * resuming a suspended connection.
1943  */
1944 void
1945 packet_backup_state(void)
1946 {
1947 	struct session_state *tmp;
1948 
1949 	close(active_state->connection_in);
1950 	active_state->connection_in = -1;
1951 	close(active_state->connection_out);
1952 	active_state->connection_out = -1;
1953 	if (backup_state)
1954 		tmp = backup_state;
1955 	else
1956 		tmp = alloc_session_state();
1957 	backup_state = active_state;
1958 	active_state = tmp;
1959 }
1960 
1961 /*
1962  * Swap in the old state when resuming a connecion.
1963  */
1964 void
1965 packet_restore_state(void)
1966 {
1967 	struct session_state *tmp;
1968 	void *buf;
1969 	u_int len;
1970 
1971 	tmp = backup_state;
1972 	backup_state = active_state;
1973 	active_state = tmp;
1974 	active_state->connection_in = backup_state->connection_in;
1975 	backup_state->connection_in = -1;
1976 	active_state->connection_out = backup_state->connection_out;
1977 	backup_state->connection_out = -1;
1978 	len = buffer_len(&backup_state->input);
1979 	if (len > 0) {
1980 		buf = buffer_ptr(&backup_state->input);
1981 		buffer_append(&active_state->input, buf, len);
1982 		buffer_clear(&backup_state->input);
1983 		add_recv_bytes(len);
1984 	}
1985 }
1986 
1987 #ifdef	NONE_CIPHER_ENABLED
1988 int
1989 packet_get_authentication_state(void)
1990 {
1991 	return (active_state->after_authentication);
1992 }
1993 #endif
1994