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