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