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