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