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