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