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