xref: /freebsd/crypto/openssh/packet.c (revision 586f63035fbe5e45cfc971037fd76375661ece26)
1 /* $OpenBSD: packet.c,v 1.173 2011/05/06 21:14:05 djm Exp $ */
2 /* $FreeBSD$ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * This file contains code implementing the packet protocol and communication
8  * with the other side.  This same code is used both on client and server side.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  *
17  * SSH2 packet format added by Markus Friedl.
18  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39  */
40 
41 #include "includes.h"
42 
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 	if (to.ss_family == AF_INET)
440 		return 1;
441 #ifdef IPV4_IN_IPV6
442 	if (to.ss_family == AF_INET6 &&
443 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
444 		return AF_INET;
445 #endif
446 	return to.ss_family;
447 }
448 
449 /* Sets the connection into non-blocking mode. */
450 
451 void
452 packet_set_nonblocking(void)
453 {
454 	/* Set the socket into non-blocking mode. */
455 	set_nonblock(active_state->connection_in);
456 
457 	if (active_state->connection_out != active_state->connection_in)
458 		set_nonblock(active_state->connection_out);
459 }
460 
461 /* Returns the socket used for reading. */
462 
463 int
464 packet_get_connection_in(void)
465 {
466 	return active_state->connection_in;
467 }
468 
469 /* Returns the descriptor used for writing. */
470 
471 int
472 packet_get_connection_out(void)
473 {
474 	return active_state->connection_out;
475 }
476 
477 /* Closes the connection and clears and frees internal data structures. */
478 
479 void
480 packet_close(void)
481 {
482 	if (!active_state->initialized)
483 		return;
484 	active_state->initialized = 0;
485 	if (active_state->connection_in == active_state->connection_out) {
486 		shutdown(active_state->connection_out, SHUT_RDWR);
487 		close(active_state->connection_out);
488 	} else {
489 		close(active_state->connection_in);
490 		close(active_state->connection_out);
491 	}
492 	buffer_free(&active_state->input);
493 	buffer_free(&active_state->output);
494 	buffer_free(&active_state->outgoing_packet);
495 	buffer_free(&active_state->incoming_packet);
496 	if (active_state->compression_buffer_ready) {
497 		buffer_free(&active_state->compression_buffer);
498 		buffer_compress_uninit();
499 	}
500 	cipher_cleanup(&active_state->send_context);
501 	cipher_cleanup(&active_state->receive_context);
502 }
503 
504 /* Sets remote side protocol flags. */
505 
506 void
507 packet_set_protocol_flags(u_int protocol_flags)
508 {
509 	active_state->remote_protocol_flags = protocol_flags;
510 }
511 
512 /* Returns the remote protocol flags set earlier by the above function. */
513 
514 u_int
515 packet_get_protocol_flags(void)
516 {
517 	return active_state->remote_protocol_flags;
518 }
519 
520 /*
521  * Starts packet compression from the next packet on in both directions.
522  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
523  */
524 
525 static void
526 packet_init_compression(void)
527 {
528 	if (active_state->compression_buffer_ready == 1)
529 		return;
530 	active_state->compression_buffer_ready = 1;
531 	buffer_init(&active_state->compression_buffer);
532 }
533 
534 void
535 packet_start_compression(int level)
536 {
537 	if (active_state->packet_compression && !compat20)
538 		fatal("Compression already enabled.");
539 	active_state->packet_compression = 1;
540 	packet_init_compression();
541 	buffer_compress_init_send(level);
542 	buffer_compress_init_recv();
543 }
544 
545 /*
546  * Causes any further packets to be encrypted using the given key.  The same
547  * key is used for both sending and reception.  However, both directions are
548  * encrypted independently of each other.
549  */
550 
551 void
552 packet_set_encryption_key(const u_char *key, u_int keylen, int number)
553 {
554 	Cipher *cipher = cipher_by_number(number);
555 
556 	if (cipher == NULL)
557 		fatal("packet_set_encryption_key: unknown cipher number %d", number);
558 	if (keylen < 20)
559 		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
560 	if (keylen > SSH_SESSION_KEY_LENGTH)
561 		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
562 	memcpy(active_state->ssh1_key, key, keylen);
563 	active_state->ssh1_keylen = keylen;
564 	cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
565 	    0, CIPHER_ENCRYPT);
566 	cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
567 	    0, CIPHER_DECRYPT);
568 }
569 
570 u_int
571 packet_get_encryption_key(u_char *key)
572 {
573 	if (key == NULL)
574 		return (active_state->ssh1_keylen);
575 	memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
576 	return (active_state->ssh1_keylen);
577 }
578 
579 /* Start constructing a packet to send. */
580 void
581 packet_start(u_char type)
582 {
583 	u_char buf[9];
584 	int len;
585 
586 	DBG(debug("packet_start[%d]", type));
587 	len = compat20 ? 6 : 9;
588 	memset(buf, 0, len - 1);
589 	buf[len - 1] = type;
590 	buffer_clear(&active_state->outgoing_packet);
591 	buffer_append(&active_state->outgoing_packet, buf, len);
592 }
593 
594 /* Append payload. */
595 void
596 packet_put_char(int value)
597 {
598 	char ch = value;
599 
600 	buffer_append(&active_state->outgoing_packet, &ch, 1);
601 }
602 
603 void
604 packet_put_int(u_int value)
605 {
606 	buffer_put_int(&active_state->outgoing_packet, value);
607 }
608 
609 void
610 packet_put_int64(u_int64_t value)
611 {
612 	buffer_put_int64(&active_state->outgoing_packet, value);
613 }
614 
615 void
616 packet_put_string(const void *buf, u_int len)
617 {
618 	buffer_put_string(&active_state->outgoing_packet, buf, len);
619 }
620 
621 void
622 packet_put_cstring(const char *str)
623 {
624 	buffer_put_cstring(&active_state->outgoing_packet, str);
625 }
626 
627 void
628 packet_put_raw(const void *buf, u_int len)
629 {
630 	buffer_append(&active_state->outgoing_packet, buf, len);
631 }
632 
633 void
634 packet_put_bignum(BIGNUM * value)
635 {
636 	buffer_put_bignum(&active_state->outgoing_packet, value);
637 }
638 
639 void
640 packet_put_bignum2(BIGNUM * value)
641 {
642 	buffer_put_bignum2(&active_state->outgoing_packet, value);
643 }
644 
645 #ifdef OPENSSL_HAS_ECC
646 void
647 packet_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point)
648 {
649 	buffer_put_ecpoint(&active_state->outgoing_packet, curve, point);
650 }
651 #endif
652 
653 /*
654  * Finalizes and sends the packet.  If the encryption key has been set,
655  * encrypts the packet before sending.
656  */
657 
658 static void
659 packet_send1(void)
660 {
661 	u_char buf[8], *cp;
662 	int i, padding, len;
663 	u_int checksum;
664 	u_int32_t rnd = 0;
665 
666 	/*
667 	 * If using packet compression, compress the payload of the outgoing
668 	 * packet.
669 	 */
670 	if (active_state->packet_compression) {
671 		buffer_clear(&active_state->compression_buffer);
672 		/* Skip padding. */
673 		buffer_consume(&active_state->outgoing_packet, 8);
674 		/* padding */
675 		buffer_append(&active_state->compression_buffer,
676 		    "\0\0\0\0\0\0\0\0", 8);
677 		buffer_compress(&active_state->outgoing_packet,
678 		    &active_state->compression_buffer);
679 		buffer_clear(&active_state->outgoing_packet);
680 		buffer_append(&active_state->outgoing_packet,
681 		    buffer_ptr(&active_state->compression_buffer),
682 		    buffer_len(&active_state->compression_buffer));
683 	}
684 	/* Compute packet length without padding (add checksum, remove padding). */
685 	len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
686 
687 	/* Insert padding. Initialized to zero in packet_start1() */
688 	padding = 8 - len % 8;
689 	if (!active_state->send_context.plaintext) {
690 		cp = buffer_ptr(&active_state->outgoing_packet);
691 		for (i = 0; i < padding; i++) {
692 			if (i % 4 == 0)
693 				rnd = arc4random();
694 			cp[7 - i] = rnd & 0xff;
695 			rnd >>= 8;
696 		}
697 	}
698 	buffer_consume(&active_state->outgoing_packet, 8 - padding);
699 
700 	/* Add check bytes. */
701 	checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
702 	    buffer_len(&active_state->outgoing_packet));
703 	put_u32(buf, checksum);
704 	buffer_append(&active_state->outgoing_packet, buf, 4);
705 
706 #ifdef PACKET_DEBUG
707 	fprintf(stderr, "packet_send plain: ");
708 	buffer_dump(&active_state->outgoing_packet);
709 #endif
710 
711 	/* Append to output. */
712 	put_u32(buf, len);
713 	buffer_append(&active_state->output, buf, 4);
714 	cp = buffer_append_space(&active_state->output,
715 	    buffer_len(&active_state->outgoing_packet));
716 	cipher_crypt(&active_state->send_context, cp,
717 	    buffer_ptr(&active_state->outgoing_packet),
718 	    buffer_len(&active_state->outgoing_packet));
719 
720 #ifdef PACKET_DEBUG
721 	fprintf(stderr, "encrypted: ");
722 	buffer_dump(&active_state->output);
723 #endif
724 	active_state->p_send.packets++;
725 	active_state->p_send.bytes += len +
726 	    buffer_len(&active_state->outgoing_packet);
727 	buffer_clear(&active_state->outgoing_packet);
728 
729 	/*
730 	 * Note that the packet is now only buffered in output.  It won't be
731 	 * actually sent until packet_write_wait or packet_write_poll is
732 	 * called.
733 	 */
734 }
735 
736 void
737 set_newkeys(int mode)
738 {
739 	Enc *enc;
740 	Mac *mac;
741 	Comp *comp;
742 	CipherContext *cc;
743 	u_int64_t *max_blocks;
744 	int crypt_type;
745 
746 	debug2("set_newkeys: mode %d", mode);
747 
748 	if (mode == MODE_OUT) {
749 		cc = &active_state->send_context;
750 		crypt_type = CIPHER_ENCRYPT;
751 		active_state->p_send.packets = active_state->p_send.blocks = 0;
752 		max_blocks = &active_state->max_blocks_out;
753 	} else {
754 		cc = &active_state->receive_context;
755 		crypt_type = CIPHER_DECRYPT;
756 		active_state->p_read.packets = active_state->p_read.blocks = 0;
757 		max_blocks = &active_state->max_blocks_in;
758 	}
759 	if (active_state->newkeys[mode] != NULL) {
760 		debug("set_newkeys: rekeying");
761 		cipher_cleanup(cc);
762 		enc  = &active_state->newkeys[mode]->enc;
763 		mac  = &active_state->newkeys[mode]->mac;
764 		comp = &active_state->newkeys[mode]->comp;
765 		mac_clear(mac);
766 		xfree(enc->name);
767 		xfree(enc->iv);
768 		xfree(enc->key);
769 		xfree(mac->name);
770 		xfree(mac->key);
771 		xfree(comp->name);
772 		xfree(active_state->newkeys[mode]);
773 	}
774 	active_state->newkeys[mode] = kex_get_newkeys(mode);
775 	if (active_state->newkeys[mode] == NULL)
776 		fatal("newkeys: no keys for mode %d", mode);
777 	enc  = &active_state->newkeys[mode]->enc;
778 	mac  = &active_state->newkeys[mode]->mac;
779 	comp = &active_state->newkeys[mode]->comp;
780 	if (mac_init(mac) == 0)
781 		mac->enabled = 1;
782 	DBG(debug("cipher_init_context: %d", mode));
783 	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
784 	    enc->iv, enc->block_size, crypt_type);
785 	/* Deleting the keys does not gain extra security */
786 	/* memset(enc->iv,  0, enc->block_size);
787 	   memset(enc->key, 0, enc->key_len);
788 	   memset(mac->key, 0, mac->key_len); */
789 	if ((comp->type == COMP_ZLIB ||
790 	    (comp->type == COMP_DELAYED &&
791 	     active_state->after_authentication)) && comp->enabled == 0) {
792 		packet_init_compression();
793 		if (mode == MODE_OUT)
794 			buffer_compress_init_send(6);
795 		else
796 			buffer_compress_init_recv();
797 		comp->enabled = 1;
798 	}
799 	/*
800 	 * The 2^(blocksize*2) limit is too expensive for 3DES,
801 	 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
802 	 */
803 	if (enc->block_size >= 16)
804 		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
805 	else
806 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
807 	if (active_state->rekey_limit)
808 		*max_blocks = MIN(*max_blocks,
809 		    active_state->rekey_limit / enc->block_size);
810 }
811 
812 /*
813  * Delayed compression for SSH2 is enabled after authentication:
814  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
815  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
816  */
817 static void
818 packet_enable_delayed_compress(void)
819 {
820 	Comp *comp = NULL;
821 	int mode;
822 
823 	/*
824 	 * Remember that we are past the authentication step, so rekeying
825 	 * with COMP_DELAYED will turn on compression immediately.
826 	 */
827 	active_state->after_authentication = 1;
828 	for (mode = 0; mode < MODE_MAX; mode++) {
829 		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
830 		if (active_state->newkeys[mode] == NULL)
831 			continue;
832 		comp = &active_state->newkeys[mode]->comp;
833 		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
834 			packet_init_compression();
835 			if (mode == MODE_OUT)
836 				buffer_compress_init_send(6);
837 			else
838 				buffer_compress_init_recv();
839 			comp->enabled = 1;
840 		}
841 	}
842 }
843 
844 /*
845  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
846  */
847 static void
848 packet_send2_wrapped(void)
849 {
850 	u_char type, *cp, *macbuf = NULL;
851 	u_char padlen, pad;
852 	u_int packet_length = 0;
853 	u_int i, len;
854 	u_int32_t rnd = 0;
855 	Enc *enc   = NULL;
856 	Mac *mac   = NULL;
857 	Comp *comp = NULL;
858 	int block_size;
859 
860 	if (active_state->newkeys[MODE_OUT] != NULL) {
861 		enc  = &active_state->newkeys[MODE_OUT]->enc;
862 		mac  = &active_state->newkeys[MODE_OUT]->mac;
863 		comp = &active_state->newkeys[MODE_OUT]->comp;
864 	}
865 	block_size = enc ? enc->block_size : 8;
866 
867 	cp = buffer_ptr(&active_state->outgoing_packet);
868 	type = cp[5];
869 
870 #ifdef PACKET_DEBUG
871 	fprintf(stderr, "plain:     ");
872 	buffer_dump(&active_state->outgoing_packet);
873 #endif
874 
875 	if (comp && comp->enabled) {
876 		len = buffer_len(&active_state->outgoing_packet);
877 		/* skip header, compress only payload */
878 		buffer_consume(&active_state->outgoing_packet, 5);
879 		buffer_clear(&active_state->compression_buffer);
880 		buffer_compress(&active_state->outgoing_packet,
881 		    &active_state->compression_buffer);
882 		buffer_clear(&active_state->outgoing_packet);
883 		buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
884 		buffer_append(&active_state->outgoing_packet,
885 		    buffer_ptr(&active_state->compression_buffer),
886 		    buffer_len(&active_state->compression_buffer));
887 		DBG(debug("compression: raw %d compressed %d", len,
888 		    buffer_len(&active_state->outgoing_packet)));
889 	}
890 
891 	/* sizeof (packet_len + pad_len + payload) */
892 	len = buffer_len(&active_state->outgoing_packet);
893 
894 	/*
895 	 * calc size of padding, alloc space, get random data,
896 	 * minimum padding is 4 bytes
897 	 */
898 	padlen = block_size - (len % block_size);
899 	if (padlen < 4)
900 		padlen += block_size;
901 	if (active_state->extra_pad) {
902 		/* will wrap if extra_pad+padlen > 255 */
903 		active_state->extra_pad =
904 		    roundup(active_state->extra_pad, block_size);
905 		pad = active_state->extra_pad -
906 		    ((len + padlen) % active_state->extra_pad);
907 		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
908 		    pad, len, padlen, active_state->extra_pad);
909 		padlen += pad;
910 		active_state->extra_pad = 0;
911 	}
912 	cp = buffer_append_space(&active_state->outgoing_packet, padlen);
913 	if (enc && !active_state->send_context.plaintext) {
914 		/* random padding */
915 		for (i = 0; i < padlen; i++) {
916 			if (i % 4 == 0)
917 				rnd = arc4random();
918 			cp[i] = rnd & 0xff;
919 			rnd >>= 8;
920 		}
921 	} else {
922 		/* clear padding */
923 		memset(cp, 0, padlen);
924 	}
925 	/* packet_length includes payload, padding and padding length field */
926 	packet_length = buffer_len(&active_state->outgoing_packet) - 4;
927 	cp = buffer_ptr(&active_state->outgoing_packet);
928 	put_u32(cp, packet_length);
929 	cp[4] = padlen;
930 	DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
931 
932 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
933 	if (mac && mac->enabled) {
934 		macbuf = mac_compute(mac, active_state->p_send.seqnr,
935 		    buffer_ptr(&active_state->outgoing_packet),
936 		    buffer_len(&active_state->outgoing_packet));
937 		DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
938 	}
939 	/* encrypt packet and append to output buffer. */
940 	cp = buffer_append_space(&active_state->output,
941 	    buffer_len(&active_state->outgoing_packet));
942 	cipher_crypt(&active_state->send_context, cp,
943 	    buffer_ptr(&active_state->outgoing_packet),
944 	    buffer_len(&active_state->outgoing_packet));
945 	/* append unencrypted MAC */
946 	if (mac && mac->enabled)
947 		buffer_append(&active_state->output, macbuf, mac->mac_len);
948 #ifdef PACKET_DEBUG
949 	fprintf(stderr, "encrypted: ");
950 	buffer_dump(&active_state->output);
951 #endif
952 	/* increment sequence number for outgoing packets */
953 	if (++active_state->p_send.seqnr == 0)
954 		logit("outgoing seqnr wraps around");
955 	if (++active_state->p_send.packets == 0)
956 		if (!(datafellows & SSH_BUG_NOREKEY))
957 			fatal("XXX too many packets with same key");
958 	active_state->p_send.blocks += (packet_length + 4) / block_size;
959 	active_state->p_send.bytes += packet_length + 4;
960 	buffer_clear(&active_state->outgoing_packet);
961 
962 	if (type == SSH2_MSG_NEWKEYS)
963 		set_newkeys(MODE_OUT);
964 	else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
965 		packet_enable_delayed_compress();
966 }
967 
968 static void
969 packet_send2(void)
970 {
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;
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 		active_state->packlen = get_u32(cp);
1273 		if (active_state->packlen < 1 + 4 ||
1274 		    active_state->packlen > PACKET_MAX_SIZE) {
1275 #ifdef PACKET_DEBUG
1276 			buffer_dump(&active_state->incoming_packet);
1277 #endif
1278 			logit("Bad packet length %u.", active_state->packlen);
1279 			packet_start_discard(enc, mac, active_state->packlen,
1280 			    PACKET_MAX_SIZE);
1281 			return SSH_MSG_NONE;
1282 		}
1283 		DBG(debug("input: packet len %u", active_state->packlen+4));
1284 		buffer_consume(&active_state->input, block_size);
1285 	}
1286 	/* we have a partial packet of block_size bytes */
1287 	need = 4 + active_state->packlen - block_size;
1288 	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1289 	    need, maclen));
1290 	if (need % block_size != 0) {
1291 		logit("padding error: need %d block %d mod %d",
1292 		    need, block_size, need % block_size);
1293 		packet_start_discard(enc, mac, active_state->packlen,
1294 		    PACKET_MAX_SIZE - block_size);
1295 		return SSH_MSG_NONE;
1296 	}
1297 	/*
1298 	 * check if the entire packet has been received and
1299 	 * decrypt into incoming_packet
1300 	 */
1301 	if (buffer_len(&active_state->input) < need + maclen)
1302 		return SSH_MSG_NONE;
1303 #ifdef PACKET_DEBUG
1304 	fprintf(stderr, "read_poll enc/full: ");
1305 	buffer_dump(&active_state->input);
1306 #endif
1307 	cp = buffer_append_space(&active_state->incoming_packet, need);
1308 	cipher_crypt(&active_state->receive_context, cp,
1309 	    buffer_ptr(&active_state->input), need);
1310 	buffer_consume(&active_state->input, need);
1311 	/*
1312 	 * compute MAC over seqnr and packet,
1313 	 * increment sequence number for incoming packet
1314 	 */
1315 	if (mac && mac->enabled) {
1316 		macbuf = mac_compute(mac, active_state->p_read.seqnr,
1317 		    buffer_ptr(&active_state->incoming_packet),
1318 		    buffer_len(&active_state->incoming_packet));
1319 		if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1320 		    mac->mac_len) != 0) {
1321 			logit("Corrupted MAC on input.");
1322 			if (need > PACKET_MAX_SIZE)
1323 				fatal("internal error need %d", need);
1324 			packet_start_discard(enc, mac, active_state->packlen,
1325 			    PACKET_MAX_SIZE - need);
1326 			return SSH_MSG_NONE;
1327 		}
1328 
1329 		DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1330 		buffer_consume(&active_state->input, mac->mac_len);
1331 	}
1332 	/* XXX now it's safe to use fatal/packet_disconnect */
1333 	if (seqnr_p != NULL)
1334 		*seqnr_p = active_state->p_read.seqnr;
1335 	if (++active_state->p_read.seqnr == 0)
1336 		logit("incoming seqnr wraps around");
1337 	if (++active_state->p_read.packets == 0)
1338 		if (!(datafellows & SSH_BUG_NOREKEY))
1339 			fatal("XXX too many packets with same key");
1340 	active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1341 	active_state->p_read.bytes += active_state->packlen + 4;
1342 
1343 	/* get padlen */
1344 	cp = buffer_ptr(&active_state->incoming_packet);
1345 	padlen = cp[4];
1346 	DBG(debug("input: padlen %d", padlen));
1347 	if (padlen < 4)
1348 		packet_disconnect("Corrupted padlen %d on input.", padlen);
1349 
1350 	/* skip packet size + padlen, discard padding */
1351 	buffer_consume(&active_state->incoming_packet, 4 + 1);
1352 	buffer_consume_end(&active_state->incoming_packet, padlen);
1353 
1354 	DBG(debug("input: len before de-compress %d",
1355 	    buffer_len(&active_state->incoming_packet)));
1356 	if (comp && comp->enabled) {
1357 		buffer_clear(&active_state->compression_buffer);
1358 		buffer_uncompress(&active_state->incoming_packet,
1359 		    &active_state->compression_buffer);
1360 		buffer_clear(&active_state->incoming_packet);
1361 		buffer_append(&active_state->incoming_packet,
1362 		    buffer_ptr(&active_state->compression_buffer),
1363 		    buffer_len(&active_state->compression_buffer));
1364 		DBG(debug("input: len after de-compress %d",
1365 		    buffer_len(&active_state->incoming_packet)));
1366 	}
1367 	/*
1368 	 * get packet type, implies consume.
1369 	 * return length of payload (without type field)
1370 	 */
1371 	type = buffer_get_char(&active_state->incoming_packet);
1372 	if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1373 		packet_disconnect("Invalid ssh2 packet type: %d", type);
1374 	if (type == SSH2_MSG_NEWKEYS)
1375 		set_newkeys(MODE_IN);
1376 	else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1377 	    !active_state->server_side)
1378 		packet_enable_delayed_compress();
1379 #ifdef PACKET_DEBUG
1380 	fprintf(stderr, "read/plain[%d]:\r\n", type);
1381 	buffer_dump(&active_state->incoming_packet);
1382 #endif
1383 	/* reset for next packet */
1384 	active_state->packlen = 0;
1385 	return type;
1386 }
1387 
1388 int
1389 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1390 {
1391 	u_int reason, seqnr;
1392 	u_char type;
1393 	char *msg;
1394 
1395 	for (;;) {
1396 		if (compat20) {
1397 			type = packet_read_poll2(seqnr_p);
1398 			if (type) {
1399 				active_state->keep_alive_timeouts = 0;
1400 				DBG(debug("received packet type %d", type));
1401 			}
1402 			switch (type) {
1403 			case SSH2_MSG_IGNORE:
1404 				debug3("Received SSH2_MSG_IGNORE");
1405 				break;
1406 			case SSH2_MSG_DEBUG:
1407 				packet_get_char();
1408 				msg = packet_get_string(NULL);
1409 				debug("Remote: %.900s", msg);
1410 				xfree(msg);
1411 				msg = packet_get_string(NULL);
1412 				xfree(msg);
1413 				break;
1414 			case SSH2_MSG_DISCONNECT:
1415 				reason = packet_get_int();
1416 				msg = packet_get_string(NULL);
1417 				logit("Received disconnect from %s: %u: %.400s",
1418 				    get_remote_ipaddr(), reason, msg);
1419 				xfree(msg);
1420 				cleanup_exit(255);
1421 				break;
1422 			case SSH2_MSG_UNIMPLEMENTED:
1423 				seqnr = packet_get_int();
1424 				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1425 				    seqnr);
1426 				break;
1427 			default:
1428 				return type;
1429 			}
1430 		} else {
1431 			type = packet_read_poll1();
1432 			switch (type) {
1433 			case SSH_MSG_IGNORE:
1434 				break;
1435 			case SSH_MSG_DEBUG:
1436 				msg = packet_get_string(NULL);
1437 				debug("Remote: %.900s", msg);
1438 				xfree(msg);
1439 				break;
1440 			case SSH_MSG_DISCONNECT:
1441 				msg = packet_get_string(NULL);
1442 				logit("Received disconnect from %s: %.400s",
1443 				    get_remote_ipaddr(), msg);
1444 				cleanup_exit(255);
1445 				break;
1446 			default:
1447 				if (type)
1448 					DBG(debug("received packet type %d", type));
1449 				return type;
1450 			}
1451 		}
1452 	}
1453 }
1454 
1455 int
1456 packet_read_poll(void)
1457 {
1458 	return packet_read_poll_seqnr(NULL);
1459 }
1460 
1461 /*
1462  * Buffers the given amount of input characters.  This is intended to be used
1463  * together with packet_read_poll.
1464  */
1465 
1466 void
1467 packet_process_incoming(const char *buf, u_int len)
1468 {
1469 	if (active_state->packet_discard) {
1470 		active_state->keep_alive_timeouts = 0; /* ?? */
1471 		if (len >= active_state->packet_discard)
1472 			packet_stop_discard();
1473 		active_state->packet_discard -= len;
1474 		return;
1475 	}
1476 	buffer_append(&active_state->input, buf, len);
1477 }
1478 
1479 /* Returns a character from the packet. */
1480 
1481 u_int
1482 packet_get_char(void)
1483 {
1484 	char ch;
1485 
1486 	buffer_get(&active_state->incoming_packet, &ch, 1);
1487 	return (u_char) ch;
1488 }
1489 
1490 /* Returns an integer from the packet data. */
1491 
1492 u_int
1493 packet_get_int(void)
1494 {
1495 	return buffer_get_int(&active_state->incoming_packet);
1496 }
1497 
1498 /* Returns an 64 bit integer from the packet data. */
1499 
1500 u_int64_t
1501 packet_get_int64(void)
1502 {
1503 	return buffer_get_int64(&active_state->incoming_packet);
1504 }
1505 
1506 /*
1507  * Returns an arbitrary precision integer from the packet data.  The integer
1508  * must have been initialized before this call.
1509  */
1510 
1511 void
1512 packet_get_bignum(BIGNUM * value)
1513 {
1514 	buffer_get_bignum(&active_state->incoming_packet, value);
1515 }
1516 
1517 void
1518 packet_get_bignum2(BIGNUM * value)
1519 {
1520 	buffer_get_bignum2(&active_state->incoming_packet, value);
1521 }
1522 
1523 #ifdef OPENSSL_HAS_ECC
1524 void
1525 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1526 {
1527 	buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1528 }
1529 #endif
1530 
1531 void *
1532 packet_get_raw(u_int *length_ptr)
1533 {
1534 	u_int bytes = buffer_len(&active_state->incoming_packet);
1535 
1536 	if (length_ptr != NULL)
1537 		*length_ptr = bytes;
1538 	return buffer_ptr(&active_state->incoming_packet);
1539 }
1540 
1541 int
1542 packet_remaining(void)
1543 {
1544 	return buffer_len(&active_state->incoming_packet);
1545 }
1546 
1547 /*
1548  * Returns a string from the packet data.  The string is allocated using
1549  * xmalloc; it is the responsibility of the calling program to free it when
1550  * no longer needed.  The length_ptr argument may be NULL, or point to an
1551  * integer into which the length of the string is stored.
1552  */
1553 
1554 void *
1555 packet_get_string(u_int *length_ptr)
1556 {
1557 	return buffer_get_string(&active_state->incoming_packet, length_ptr);
1558 }
1559 
1560 void *
1561 packet_get_string_ptr(u_int *length_ptr)
1562 {
1563 	return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1564 }
1565 
1566 /* Ensures the returned string has no embedded \0 characters in it. */
1567 char *
1568 packet_get_cstring(u_int *length_ptr)
1569 {
1570 	return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1571 }
1572 
1573 /*
1574  * Sends a diagnostic message from the server to the client.  This message
1575  * can be sent at any time (but not while constructing another message). The
1576  * message is printed immediately, but only if the client is being executed
1577  * in verbose mode.  These messages are primarily intended to ease debugging
1578  * authentication problems.   The length of the formatted message must not
1579  * exceed 1024 bytes.  This will automatically call packet_write_wait.
1580  */
1581 
1582 void
1583 packet_send_debug(const char *fmt,...)
1584 {
1585 	char buf[1024];
1586 	va_list args;
1587 
1588 	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1589 		return;
1590 
1591 	va_start(args, fmt);
1592 	vsnprintf(buf, sizeof(buf), fmt, args);
1593 	va_end(args);
1594 
1595 	if (compat20) {
1596 		packet_start(SSH2_MSG_DEBUG);
1597 		packet_put_char(0);	/* bool: always display */
1598 		packet_put_cstring(buf);
1599 		packet_put_cstring("");
1600 	} else {
1601 		packet_start(SSH_MSG_DEBUG);
1602 		packet_put_cstring(buf);
1603 	}
1604 	packet_send();
1605 	packet_write_wait();
1606 }
1607 
1608 /*
1609  * Logs the error plus constructs and sends a disconnect packet, closes the
1610  * connection, and exits.  This function never returns. The error message
1611  * should not contain a newline.  The length of the formatted message must
1612  * not exceed 1024 bytes.
1613  */
1614 
1615 void
1616 packet_disconnect(const char *fmt,...)
1617 {
1618 	char buf[1024];
1619 	va_list args;
1620 	static int disconnecting = 0;
1621 
1622 	if (disconnecting)	/* Guard against recursive invocations. */
1623 		fatal("packet_disconnect called recursively.");
1624 	disconnecting = 1;
1625 
1626 	/*
1627 	 * Format the message.  Note that the caller must make sure the
1628 	 * message is of limited size.
1629 	 */
1630 	va_start(args, fmt);
1631 	vsnprintf(buf, sizeof(buf), fmt, args);
1632 	va_end(args);
1633 
1634 	/* Display the error locally */
1635 	logit("Disconnecting: %.100s", buf);
1636 
1637 	/* Send the disconnect message to the other side, and wait for it to get sent. */
1638 	if (compat20) {
1639 		packet_start(SSH2_MSG_DISCONNECT);
1640 		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1641 		packet_put_cstring(buf);
1642 		packet_put_cstring("");
1643 	} else {
1644 		packet_start(SSH_MSG_DISCONNECT);
1645 		packet_put_cstring(buf);
1646 	}
1647 	packet_send();
1648 	packet_write_wait();
1649 
1650 	/* Stop listening for connections. */
1651 	channel_close_all();
1652 
1653 	/* Close the connection. */
1654 	packet_close();
1655 	cleanup_exit(255);
1656 }
1657 
1658 /* Checks if there is any buffered output, and tries to write some of the output. */
1659 
1660 void
1661 packet_write_poll(void)
1662 {
1663 	int len = buffer_len(&active_state->output);
1664 	int cont;
1665 
1666 	if (len > 0) {
1667 		cont = 0;
1668 		len = roaming_write(active_state->connection_out,
1669 		    buffer_ptr(&active_state->output), len, &cont);
1670 		if (len == -1) {
1671 			if (errno == EINTR || errno == EAGAIN ||
1672 			    errno == EWOULDBLOCK)
1673 				return;
1674 			fatal("Write failed: %.100s", strerror(errno));
1675 		}
1676 		if (len == 0 && !cont)
1677 			fatal("Write connection closed");
1678 		buffer_consume(&active_state->output, len);
1679 	}
1680 }
1681 
1682 /*
1683  * Calls packet_write_poll repeatedly until all pending output data has been
1684  * written.
1685  */
1686 
1687 void
1688 packet_write_wait(void)
1689 {
1690 	fd_set *setp;
1691 	int ret, ms_remain;
1692 	struct timeval start, timeout, *timeoutp = NULL;
1693 
1694 	setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1695 	    NFDBITS), sizeof(fd_mask));
1696 	packet_write_poll();
1697 	while (packet_have_data_to_write()) {
1698 		memset(setp, 0, howmany(active_state->connection_out + 1,
1699 		    NFDBITS) * sizeof(fd_mask));
1700 		FD_SET(active_state->connection_out, setp);
1701 
1702 		if (active_state->packet_timeout_ms > 0) {
1703 			ms_remain = active_state->packet_timeout_ms;
1704 			timeoutp = &timeout;
1705 		}
1706 		for (;;) {
1707 			if (active_state->packet_timeout_ms != -1) {
1708 				ms_to_timeval(&timeout, ms_remain);
1709 				gettimeofday(&start, NULL);
1710 			}
1711 			if ((ret = select(active_state->connection_out + 1,
1712 			    NULL, setp, NULL, timeoutp)) >= 0)
1713 				break;
1714 			if (errno != EAGAIN && errno != EINTR &&
1715 			    errno != EWOULDBLOCK)
1716 				break;
1717 			if (active_state->packet_timeout_ms == -1)
1718 				continue;
1719 			ms_subtract_diff(&start, &ms_remain);
1720 			if (ms_remain <= 0) {
1721 				ret = 0;
1722 				break;
1723 			}
1724 		}
1725 		if (ret == 0) {
1726 			logit("Connection to %.200s timed out while "
1727 			    "waiting to write", get_remote_ipaddr());
1728 			cleanup_exit(255);
1729 		}
1730 		packet_write_poll();
1731 	}
1732 	xfree(setp);
1733 }
1734 
1735 /* Returns true if there is buffered data to write to the connection. */
1736 
1737 int
1738 packet_have_data_to_write(void)
1739 {
1740 	return buffer_len(&active_state->output) != 0;
1741 }
1742 
1743 /* Returns true if there is not too much data to write to the connection. */
1744 
1745 int
1746 packet_not_very_much_data_to_write(void)
1747 {
1748 	if (active_state->interactive_mode)
1749 		return buffer_len(&active_state->output) < 16384;
1750 	else
1751 		return buffer_len(&active_state->output) < 128 * 1024;
1752 }
1753 
1754 static void
1755 packet_set_tos(int tos)
1756 {
1757 #ifndef IP_TOS_IS_BROKEN
1758 	if (!packet_connection_is_on_socket())
1759 		return;
1760 	switch (packet_connection_af()) {
1761 # ifdef IP_TOS
1762 	case AF_INET:
1763 		debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1764 		if (setsockopt(active_state->connection_in,
1765 		    IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
1766 			error("setsockopt IP_TOS %d: %.100s:",
1767 			    tos, strerror(errno));
1768 		break;
1769 # endif /* IP_TOS */
1770 # ifdef IPV6_TCLASS
1771 	case AF_INET6:
1772 		debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1773 		if (setsockopt(active_state->connection_in,
1774 		    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
1775 			error("setsockopt IPV6_TCLASS %d: %.100s:",
1776 			    tos, strerror(errno));
1777 		break;
1778 # endif /* IPV6_TCLASS */
1779 	}
1780 #endif /* IP_TOS_IS_BROKEN */
1781 }
1782 
1783 /* Informs that the current session is interactive.  Sets IP flags for that. */
1784 
1785 void
1786 packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
1787 {
1788 	if (active_state->set_interactive_called)
1789 		return;
1790 	active_state->set_interactive_called = 1;
1791 
1792 	/* Record that we are in interactive mode. */
1793 	active_state->interactive_mode = interactive;
1794 
1795 	/* Only set socket options if using a socket.  */
1796 	if (!packet_connection_is_on_socket())
1797 		return;
1798 	set_nodelay(active_state->connection_in);
1799 	packet_set_tos(interactive ? qos_interactive : qos_bulk);
1800 }
1801 
1802 /* Returns true if the current connection is interactive. */
1803 
1804 int
1805 packet_is_interactive(void)
1806 {
1807 	return active_state->interactive_mode;
1808 }
1809 
1810 int
1811 packet_set_maxsize(u_int s)
1812 {
1813 	if (active_state->set_maxsize_called) {
1814 		logit("packet_set_maxsize: called twice: old %d new %d",
1815 		    active_state->max_packet_size, s);
1816 		return -1;
1817 	}
1818 	if (s < 4 * 1024 || s > 1024 * 1024) {
1819 		logit("packet_set_maxsize: bad size %d", s);
1820 		return -1;
1821 	}
1822 	active_state->set_maxsize_called = 1;
1823 	debug("packet_set_maxsize: setting to %d", s);
1824 	active_state->max_packet_size = s;
1825 	return s;
1826 }
1827 
1828 int
1829 packet_inc_alive_timeouts(void)
1830 {
1831 	return ++active_state->keep_alive_timeouts;
1832 }
1833 
1834 void
1835 packet_set_alive_timeouts(int ka)
1836 {
1837 	active_state->keep_alive_timeouts = ka;
1838 }
1839 
1840 u_int
1841 packet_get_maxsize(void)
1842 {
1843 	return active_state->max_packet_size;
1844 }
1845 
1846 /* roundup current message to pad bytes */
1847 void
1848 packet_add_padding(u_char pad)
1849 {
1850 	active_state->extra_pad = pad;
1851 }
1852 
1853 /*
1854  * 9.2.  Ignored Data Message
1855  *
1856  *   byte      SSH_MSG_IGNORE
1857  *   string    data
1858  *
1859  * All implementations MUST understand (and ignore) this message at any
1860  * time (after receiving the protocol version). No implementation is
1861  * required to send them. This message can be used as an additional
1862  * protection measure against advanced traffic analysis techniques.
1863  */
1864 void
1865 packet_send_ignore(int nbytes)
1866 {
1867 	u_int32_t rnd = 0;
1868 	int i;
1869 
1870 	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1871 	packet_put_int(nbytes);
1872 	for (i = 0; i < nbytes; i++) {
1873 		if (i % 4 == 0)
1874 			rnd = arc4random();
1875 		packet_put_char((u_char)rnd & 0xff);
1876 		rnd >>= 8;
1877 	}
1878 }
1879 
1880 #ifdef	NONE_CIPHER_ENABLED
1881 void
1882 packet_request_rekeying(void)
1883 {
1884 	rekey_requested = 1;
1885 }
1886 #endif
1887 
1888 #define MAX_PACKETS	(1U<<31)
1889 int
1890 packet_need_rekeying(void)
1891 {
1892 	if (datafellows & SSH_BUG_NOREKEY)
1893 		return 0;
1894 #ifdef	NONE_CIPHER_ENABLED
1895 	if (rekey_requested == 1) {
1896 		rekey_requested = 0;
1897 		return 1;
1898 	}
1899 #endif
1900 	return
1901 	    (active_state->p_send.packets > MAX_PACKETS) ||
1902 	    (active_state->p_read.packets > MAX_PACKETS) ||
1903 	    (active_state->max_blocks_out &&
1904 	        (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1905 	    (active_state->max_blocks_in &&
1906 	        (active_state->p_read.blocks > active_state->max_blocks_in));
1907 }
1908 
1909 void
1910 packet_set_rekey_limit(u_int32_t bytes)
1911 {
1912 	active_state->rekey_limit = bytes;
1913 }
1914 
1915 void
1916 packet_set_server(void)
1917 {
1918 	active_state->server_side = 1;
1919 }
1920 
1921 void
1922 packet_set_authenticated(void)
1923 {
1924 	active_state->after_authentication = 1;
1925 }
1926 
1927 void *
1928 packet_get_input(void)
1929 {
1930 	return (void *)&active_state->input;
1931 }
1932 
1933 void *
1934 packet_get_output(void)
1935 {
1936 	return (void *)&active_state->output;
1937 }
1938 
1939 void *
1940 packet_get_newkeys(int mode)
1941 {
1942 	return (void *)active_state->newkeys[mode];
1943 }
1944 
1945 /*
1946  * Save the state for the real connection, and use a separate state when
1947  * resuming a suspended connection.
1948  */
1949 void
1950 packet_backup_state(void)
1951 {
1952 	struct session_state *tmp;
1953 
1954 	close(active_state->connection_in);
1955 	active_state->connection_in = -1;
1956 	close(active_state->connection_out);
1957 	active_state->connection_out = -1;
1958 	if (backup_state)
1959 		tmp = backup_state;
1960 	else
1961 		tmp = alloc_session_state();
1962 	backup_state = active_state;
1963 	active_state = tmp;
1964 }
1965 
1966 /*
1967  * Swap in the old state when resuming a connecion.
1968  */
1969 void
1970 packet_restore_state(void)
1971 {
1972 	struct session_state *tmp;
1973 	void *buf;
1974 	u_int len;
1975 
1976 	tmp = backup_state;
1977 	backup_state = active_state;
1978 	active_state = tmp;
1979 	active_state->connection_in = backup_state->connection_in;
1980 	backup_state->connection_in = -1;
1981 	active_state->connection_out = backup_state->connection_out;
1982 	backup_state->connection_out = -1;
1983 	len = buffer_len(&backup_state->input);
1984 	if (len > 0) {
1985 		buf = buffer_ptr(&backup_state->input);
1986 		buffer_append(&active_state->input, buf, len);
1987 		buffer_clear(&backup_state->input);
1988 		add_recv_bytes(len);
1989 	}
1990 }
1991 
1992 #ifdef	NONE_CIPHER_ENABLED
1993 int
1994 packet_get_authentication_state(void)
1995 {
1996 	return (active_state->after_authentication);
1997 }
1998 #endif
1999