xref: /titanic_41/usr/src/cmd/ssh/libssh/common/packet.c (revision f998c95e3b7029fe5f7542e115f7474ddb8024d7)
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 2007 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: rekeying");
561 		cipher_cleanup(cc);
562 		free_keys(newkeys[mode]);
563 	}
564 	newkeys[mode] = kex_get_newkeys(mode);
565 	if (newkeys[mode] == NULL)
566 		fatal("newkeys: no keys for mode %d", mode);
567 	enc  = &newkeys[mode]->enc;
568 	mac  = &newkeys[mode]->mac;
569 	comp = &newkeys[mode]->comp;
570 	if (mac->md != NULL)
571 		mac->enabled = 1;
572 	DBG(debug("cipher_init_context: %d", mode));
573 	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
574 	    enc->iv, enc->block_size, crypt_type);
575 	/* Deleting the keys does not gain extra security */
576 	/* memset(enc->iv,  0, enc->block_size);
577 	   memset(enc->key, 0, enc->key_len); */
578 	if (comp->type != 0 && comp->enabled == 0) {
579 		packet_init_compression();
580 		if (mode == MODE_OUT)
581 			buffer_compress_init_send(6);
582 		else
583 			buffer_compress_init_recv();
584 		comp->enabled = 1;
585 	}
586 
587 	/*
588 	 * In accordance to the RFCs listed below we enforce the key
589 	 * re-exchange for:
590 	 *
591 	 * - every 1GB of transmitted data if the selected cipher block size
592 	 *   is less than 16 bytes (3DES, Blowfish)
593 	 * - every 2^(2*B) cipher blocks transmitted (B is block size in bytes)
594 	 *   if the cipher block size is greater than or equal to 16 bytes (AES)
595 	 * - and we never send more than 2^32 SSH packets using the same keys.
596 	 *   The recommendation of 2^31 packets is not enforced here but in
597 	 *   packet_need_rekeying(). There is also a hard check in
598 	 *   packet_send2_wrapped() that we don't send more than 2^32 packets.
599 	 *
600 	 * Note that if the SSH_BUG_NOREKEY compatibility flag is set then no
601 	 * automatic rekeying is performed nor do we enforce the 3rd rule.
602 	 * This means that we can be always forced by the opposite side to never
603 	 * initiate automatic key re-exchange. This might change in the future.
604 	 *
605 	 * The RekeyLimit option keyword may only enforce more frequent key
606 	 * renegotiation, never less. For more information on key renegotiation,
607 	 * see:
608 	 *
609 	 * - RFC 4253 (SSH Transport Layer Protocol), section "9. Key
610 	 *   Re-Exchange"
611 	 * - RFC 4344 (SSH Transport Layer Encryption Modes), sections "3.
612 	 *   Rekeying" and "6.1 Rekeying Considerations"
613 	 */
614 	if (enc->block_size >= 16)
615 		*max_blocks = (u_int64_t)1 << (enc->block_size * 2);
616 	else
617 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
618 
619 	if (rekey_limit)
620 		*max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
621 }
622 
623 void
624 free_keys(Newkeys *keys)
625 {
626 	Enc *enc;
627 	Mac *mac;
628 	Comp *comp;
629 
630 	enc  = &keys->enc;
631 	mac  = &keys->mac;
632 	comp = &keys->comp;
633 	memset(mac->key, 0, mac->key_len);
634 	xfree(enc->name);
635 	xfree(enc->iv);
636 	xfree(enc->key);
637 	xfree(mac->name);
638 	xfree(mac->key);
639 	xfree(comp->name);
640 	xfree(keys);
641 }
642 
643 /*
644  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
645  */
646 static void
647 packet_send2_wrapped(void)
648 {
649 	u_char type, *cp, *macbuf = NULL;
650 	u_char padlen, pad;
651 	u_int packet_length = 0;
652 	u_int i, len;
653 	u_int32_t rnd = 0;
654 	Enc *enc   = NULL;
655 	Mac *mac   = NULL;
656 	Comp *comp = NULL;
657 	int block_size;
658 
659 	if (newkeys[MODE_OUT] != NULL) {
660 		enc  = &newkeys[MODE_OUT]->enc;
661 		mac  = &newkeys[MODE_OUT]->mac;
662 		comp = &newkeys[MODE_OUT]->comp;
663 	}
664 	block_size = enc ? enc->block_size : 8;
665 
666 	cp = buffer_ptr(&outgoing_packet);
667 	type = cp[5];
668 
669 #ifdef PACKET_DEBUG
670 	fprintf(stderr, "plain:     ");
671 	buffer_dump(&outgoing_packet);
672 #endif
673 
674 	if (comp && comp->enabled) {
675 		len = buffer_len(&outgoing_packet);
676 		/* skip header, compress only payload */
677 		buffer_consume(&outgoing_packet, 5);
678 		buffer_clear(&compression_buffer);
679 		buffer_compress(&outgoing_packet, &compression_buffer);
680 		buffer_clear(&outgoing_packet);
681 		buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
682 		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
683 		    buffer_len(&compression_buffer));
684 		DBG(debug("compression: raw %d compressed %d", len,
685 		    buffer_len(&outgoing_packet)));
686 	}
687 
688 	/* sizeof (packet_len + pad_len + payload) */
689 	len = buffer_len(&outgoing_packet);
690 
691 	/*
692 	 * calc size of padding, alloc space, get random data,
693 	 * minimum padding is 4 bytes
694 	 */
695 	padlen = block_size - (len % block_size);
696 	if (padlen < 4)
697 		padlen += block_size;
698 	if (extra_pad) {
699 		/* will wrap if extra_pad+padlen > 255 */
700 		extra_pad  = roundup(extra_pad, block_size);
701 		pad = extra_pad - ((len + padlen) % extra_pad);
702 		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
703 		    pad, len, padlen, extra_pad);
704 		padlen += pad;
705 		extra_pad = 0;
706 	}
707 	cp = buffer_append_space(&outgoing_packet, padlen);
708 	if (enc && !send_context.plaintext) {
709 		/* random padding */
710 		for (i = 0; i < padlen; i++) {
711 			if (i % 4 == 0)
712 				rnd = arc4random();
713 			cp[i] = rnd & 0xff;
714 			rnd >>= 8;
715 		}
716 	} else {
717 		/* clear padding */
718 		memset(cp, 0, padlen);
719 	}
720 	/* packet_length includes payload, padding and padding length field */
721 	packet_length = buffer_len(&outgoing_packet) - 4;
722 	cp = buffer_ptr(&outgoing_packet);
723 	PUT_32BIT(cp, packet_length);
724 	cp[4] = padlen;
725 	DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
726 
727 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
728 	if (mac && mac->enabled) {
729 		macbuf = mac_compute(mac, p_send.seqnr,
730 		    buffer_ptr(&outgoing_packet),
731 		    buffer_len(&outgoing_packet));
732 		DBG(debug("done calc MAC out #%d", p_send.seqnr));
733 	}
734 	/* encrypt packet and append to output buffer. */
735 	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
736 	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
737 	    buffer_len(&outgoing_packet));
738 	/* append unencrypted MAC */
739 	if (mac && mac->enabled)
740 		buffer_append(&output, (char *)macbuf, mac->mac_len);
741 #ifdef PACKET_DEBUG
742 	fprintf(stderr, "encrypted: ");
743 	buffer_dump(&output);
744 #endif
745 	/* increment sequence number for outgoing packets */
746 	if (++p_send.seqnr == 0)
747 		log("outgoing seqnr wraps around");
748 
749 	/*
750 	 * RFC 4344: 3.1. First Rekeying Recommendation
751 	 *
752 	 * "Because of possible information leakage through the MAC tag after a
753 	 * key exchange, .... an SSH implementation SHOULD NOT send more than
754 	 * 2**32 packets before rekeying again."
755 	 *
756 	 * The code below is a hard check so that we are sure we don't go across
757 	 * the suggestion. However, since the largest cipher block size we have
758 	 * (AES) is 16 bytes we can't reach 2^32 SSH packets encrypted with the
759 	 * same key while performing periodic rekeying.
760 	 */
761 	if (++p_send.packets == 0)
762 		if (!(datafellows & SSH_BUG_NOREKEY))
763 			fatal("too many packets encrypted with same key");
764 	p_send.blocks += (packet_length + 4) / block_size;
765 	buffer_clear(&outgoing_packet);
766 
767 	if (type == SSH2_MSG_NEWKEYS)
768 #ifdef ALTPRIVSEP
769 		/* set_newkeys(MODE_OUT) in client, server, but not monitor */
770 		if (!packet_is_server() && !packet_is_monitor())
771 #endif /* ALTPRIVSEP */
772 		set_newkeys(MODE_OUT);
773 }
774 
775 static void
776 packet_send2(void)
777 {
778 	static int rekeying = 0;
779 	struct packet *p;
780 	u_char type, *cp;
781 
782 	cp = buffer_ptr(&outgoing_packet);
783 	type = cp[5];
784 
785 	/* during rekeying we can only send key exchange messages */
786 	if (rekeying) {
787 		if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
788 		    (type <= SSH2_MSG_TRANSPORT_MAX))) {
789 			debug("enqueue packet: %u", type);
790 			p = xmalloc(sizeof(*p));
791 			p->type = type;
792 			memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
793 			buffer_init(&outgoing_packet);
794 			TAILQ_INSERT_TAIL(&outgoing, p, next);
795 			return;
796 		}
797 	}
798 
799 	/* rekeying starts with sending KEXINIT */
800 	if (type == SSH2_MSG_KEXINIT)
801 		rekeying = 1;
802 
803 	packet_send2_wrapped();
804 
805 	/* after a NEWKEYS message we can send the complete queue */
806 	if (type == SSH2_MSG_NEWKEYS) {
807 		rekeying = 0;
808 		while ((p = TAILQ_FIRST(&outgoing)) != NULL) {
809 			type = p->type;
810 			debug("dequeue packet: %u", type);
811 			buffer_free(&outgoing_packet);
812 			memcpy(&outgoing_packet, &p->payload, sizeof(Buffer));
813 			TAILQ_REMOVE(&outgoing, p, next);
814 			xfree(p);
815 			packet_send2_wrapped();
816 		}
817 	}
818 }
819 
820 void
821 packet_send(void)
822 {
823 	if (compat20)
824 		packet_send2();
825 	else
826 		packet_send1();
827 	DBG(debug("packet_send done"));
828 }
829 
830 /*
831  * Waits until a packet has been received, and returns its type.  Note that
832  * no other data is processed until this returns, so this function should not
833  * be used during the interactive session.
834  */
835 
836 int
837 packet_read_seqnr(u_int32_t *seqnr_p)
838 {
839 	int type, len;
840 	fd_set *setp;
841 	char buf[8192];
842 	DBG(debug("packet_read()"));
843 
844 	setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
845 	    sizeof(fd_mask));
846 
847 	/* Since we are blocking, ensure that all written packets have been sent. */
848 	packet_write_wait();
849 
850 	/* Stay in the loop until we have received a complete packet. */
851 	for (;;) {
852 		/* Try to read a packet from the buffer. */
853 		type = packet_read_poll_seqnr(seqnr_p);
854 		if (!compat20 && (
855 		    type == SSH_SMSG_SUCCESS
856 		    || type == SSH_SMSG_FAILURE
857 		    || type == SSH_CMSG_EOF
858 		    || type == SSH_CMSG_EXIT_CONFIRMATION))
859 			packet_check_eom();
860 		/* If we got a packet, return it. */
861 		if (type != SSH_MSG_NONE) {
862 			xfree(setp);
863 			return type;
864 		}
865 		/*
866 		 * Otherwise, wait for some data to arrive, add it to the
867 		 * buffer, and try again.
868 		 */
869 		memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
870 		    sizeof(fd_mask));
871 		FD_SET(connection_in, setp);
872 
873 		/* Wait for some data to arrive. */
874 		while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
875 		    (errno == EAGAIN || errno == EINTR))
876 			;
877 
878 		/* Read data from the socket. */
879 		len = read(connection_in, buf, sizeof(buf));
880 		if (len == 0) {
881 			log("Connection closed by %.200s", get_remote_ipaddr());
882 			fatal_cleanup();
883 		}
884 		if (len < 0)
885 			fatal("Read from socket failed: %.100s", strerror(errno));
886 		/* Append it to the buffer. */
887 		packet_process_incoming(buf, len);
888 	}
889 	/* NOTREACHED */
890 }
891 
892 int
893 packet_read(void)
894 {
895 	return packet_read_seqnr(NULL);
896 }
897 
898 /*
899  * Waits until a packet has been received, verifies that its type matches
900  * that given, and gives a fatal error and exits if there is a mismatch.
901  */
902 
903 void
904 packet_read_expect(int expected_type)
905 {
906 	int type;
907 
908 	type = packet_read();
909 	if (type != expected_type)
910 		packet_disconnect("Protocol error: expected packet type %d, got %d",
911 		    expected_type, type);
912 }
913 
914 /* Checks if a full packet is available in the data received so far via
915  * packet_process_incoming.  If so, reads the packet; otherwise returns
916  * SSH_MSG_NONE.  This does not wait for data from the connection.
917  *
918  * SSH_MSG_DISCONNECT is handled specially here.  Also,
919  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
920  * to higher levels.
921  */
922 
923 static int
924 packet_read_poll1(void)
925 {
926 	u_int len, padded_len;
927 	u_char *cp, type;
928 	u_int checksum, stored_checksum;
929 
930 	/* Check if input size is less than minimum packet size. */
931 	if (buffer_len(&input) < 4 + 8)
932 		return SSH_MSG_NONE;
933 	/* Get length of incoming packet. */
934 	cp = buffer_ptr(&input);
935 	len = GET_32BIT(cp);
936 	if (len < 1 + 2 + 2 || len > 256 * 1024)
937 		packet_disconnect("Bad packet length %d.", len);
938 	padded_len = (len + 8) & ~7;
939 
940 	/* Check if the packet has been entirely received. */
941 	if (buffer_len(&input) < 4 + padded_len)
942 		return SSH_MSG_NONE;
943 
944 	/* The entire packet is in buffer. */
945 
946 	/* Consume packet length. */
947 	buffer_consume(&input, 4);
948 
949 	/*
950 	 * Cryptographic attack detector for ssh
951 	 * (C)1998 CORE-SDI, Buenos Aires Argentina
952 	 * Ariel Futoransky(futo@core-sdi.com)
953 	 */
954 	if (!receive_context.plaintext) {
955 		switch (detect_attack(buffer_ptr(&input), padded_len, NULL)) {
956 		case DEATTACK_DETECTED:
957 			packet_disconnect("crc32 compensation attack: "
958 			    "network attack detected");
959 			break;
960 		case DEATTACK_DOS_DETECTED:
961 			packet_disconnect("deattack denial of "
962 			    "service detected");
963 			break;
964 		}
965 	}
966 
967 	/* Decrypt data to incoming_packet. */
968 	buffer_clear(&incoming_packet);
969 	cp = buffer_append_space(&incoming_packet, padded_len);
970 	cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
971 
972 	buffer_consume(&input, padded_len);
973 
974 #ifdef PACKET_DEBUG
975 	fprintf(stderr, "read_poll plain: ");
976 	buffer_dump(&incoming_packet);
977 #endif
978 
979 	/* Compute packet checksum. */
980 	checksum = ssh_crc32(buffer_ptr(&incoming_packet),
981 	    buffer_len(&incoming_packet) - 4);
982 
983 	/* Skip padding. */
984 	buffer_consume(&incoming_packet, 8 - len % 8);
985 
986 	/* Test check bytes. */
987 	if (len != buffer_len(&incoming_packet))
988 		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
989 		    len, buffer_len(&incoming_packet));
990 
991 	cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
992 	stored_checksum = GET_32BIT(cp);
993 	if (checksum != stored_checksum)
994 		packet_disconnect("Corrupted check bytes on input.");
995 	buffer_consume_end(&incoming_packet, 4);
996 
997 	if (packet_compression) {
998 		buffer_clear(&compression_buffer);
999 		buffer_uncompress(&incoming_packet, &compression_buffer);
1000 		buffer_clear(&incoming_packet);
1001 		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1002 		    buffer_len(&compression_buffer));
1003 	}
1004 	type = buffer_get_char(&incoming_packet);
1005 	return type;
1006 }
1007 
1008 static int
1009 packet_read_poll2(u_int32_t *seqnr_p)
1010 {
1011 	static u_int packet_length = 0;
1012 	u_int padlen, need;
1013 	u_char *macbuf, *cp, type;
1014 	int maclen, block_size;
1015 	Enc *enc   = NULL;
1016 	Mac *mac   = NULL;
1017 	Comp *comp = NULL;
1018 
1019 	if (newkeys[MODE_IN] != NULL) {
1020 		enc  = &newkeys[MODE_IN]->enc;
1021 		mac  = &newkeys[MODE_IN]->mac;
1022 		comp = &newkeys[MODE_IN]->comp;
1023 	}
1024 	maclen = mac && mac->enabled ? mac->mac_len : 0;
1025 	block_size = enc ? enc->block_size : 8;
1026 
1027 	if (packet_length == 0) {
1028 		/*
1029 		 * check if input size is less than the cipher block size,
1030 		 * decrypt first block and extract length of incoming packet
1031 		 */
1032 		if (buffer_len(&input) < block_size)
1033 			return SSH_MSG_NONE;
1034 		buffer_clear(&incoming_packet);
1035 		cp = buffer_append_space(&incoming_packet, block_size);
1036 		cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1037 		    block_size);
1038 		cp = buffer_ptr(&incoming_packet);
1039 		packet_length = GET_32BIT(cp);
1040 		if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1041 			buffer_dump(&incoming_packet);
1042 			packet_disconnect("Bad packet length %d.", packet_length);
1043 		}
1044 		DBG(debug("input: packet len %u", packet_length + 4));
1045 		buffer_consume(&input, block_size);
1046 	}
1047 	/* we have a partial packet of block_size bytes */
1048 	need = 4 + packet_length - block_size;
1049 	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1050 	    need, maclen));
1051 	if (need % block_size != 0)
1052 		fatal("padding error: need %d block %d mod %d",
1053 		    need, block_size, need % block_size);
1054 	/*
1055 	 * check if the entire packet has been received and
1056 	 * decrypt into incoming_packet
1057 	 */
1058 	if (buffer_len(&input) < need + maclen)
1059 		return SSH_MSG_NONE;
1060 #ifdef PACKET_DEBUG
1061 	fprintf(stderr, "read_poll enc/full: ");
1062 	buffer_dump(&input);
1063 #endif
1064 	cp = buffer_append_space(&incoming_packet, need);
1065 	cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1066 	buffer_consume(&input, need);
1067 	/*
1068 	 * compute MAC over seqnr and packet,
1069 	 * increment sequence number for incoming packet
1070 	 */
1071 	if (mac && mac->enabled) {
1072 		macbuf = mac_compute(mac, p_read.seqnr,
1073 		    buffer_ptr(&incoming_packet),
1074 		    buffer_len(&incoming_packet));
1075 		if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1076 			packet_disconnect("Corrupted MAC on input.");
1077 		DBG(debug("MAC #%d ok", p_read.seqnr));
1078 		buffer_consume(&input, mac->mac_len);
1079 	}
1080 	if (seqnr_p != NULL)
1081 		*seqnr_p = p_read.seqnr;
1082 	if (++p_read.seqnr == 0)
1083 		log("incoming seqnr wraps around");
1084 
1085 	/* see above for the comment on "First Rekeying Recommendation" */
1086 	if (++p_read.packets == 0)
1087 		if (!(datafellows & SSH_BUG_NOREKEY))
1088 			fatal("too many packets with same key");
1089 	p_read.blocks += (packet_length + 4) / block_size;
1090 
1091 	/* get padlen */
1092 	cp = buffer_ptr(&incoming_packet);
1093 	padlen = cp[4];
1094 	DBG(debug("input: padlen %d", padlen));
1095 	if (padlen < 4)
1096 		packet_disconnect("Corrupted padlen %d on input.", padlen);
1097 
1098 	/* skip packet size + padlen, discard padding */
1099 	buffer_consume(&incoming_packet, 4 + 1);
1100 	buffer_consume_end(&incoming_packet, padlen);
1101 
1102 	DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
1103 	if (comp && comp->enabled) {
1104 		buffer_clear(&compression_buffer);
1105 		buffer_uncompress(&incoming_packet, &compression_buffer);
1106 		buffer_clear(&incoming_packet);
1107 		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1108 		    buffer_len(&compression_buffer));
1109 		DBG(debug("input: len after de-compress %d",
1110 		    buffer_len(&incoming_packet)));
1111 	}
1112 	/*
1113 	 * get packet type, implies consume.
1114 	 * return length of payload (without type field)
1115 	 */
1116 	type = buffer_get_char(&incoming_packet);
1117 #ifdef ALTPRIVSEP
1118 	if (type == SSH2_MSG_NEWKEYS)
1119 		/* set_newkeys(MODE_OUT) in client, server, but not monitor */
1120 		if (!packet_is_server() && !packet_is_monitor())
1121 			set_newkeys(MODE_IN);
1122 #else /* ALTPRIVSEP */
1123 	if (type == SSH2_MSG_NEWKEYS)
1124 		set_newkeys(MODE_IN);
1125 #endif /* ALTPRIVSEP */
1126 #ifdef PACKET_DEBUG
1127 	fprintf(stderr, "read/plain[%d]:\r\n", type);
1128 	buffer_dump(&incoming_packet);
1129 #endif
1130 	/* reset for next packet */
1131 	packet_length = 0;
1132 	return type;
1133 }
1134 
1135 int
1136 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1137 {
1138 	u_int reason, seqnr;
1139 	u_char type;
1140 	char *msg;
1141 
1142 	for (;;) {
1143 		if (compat20) {
1144 			type = packet_read_poll2(seqnr_p);
1145 			DBG(debug("received packet type %d", type));
1146 			switch (type) {
1147 			case SSH2_MSG_IGNORE:
1148 				break;
1149 			case SSH2_MSG_DEBUG:
1150 				packet_get_char();
1151 				msg = packet_get_string(NULL);
1152 				debug("Remote: %.900s", msg);
1153 				xfree(msg);
1154 				msg = packet_get_string(NULL);
1155 				xfree(msg);
1156 				break;
1157 			case SSH2_MSG_DISCONNECT:
1158 				reason = packet_get_int();
1159 				msg = packet_get_string(NULL);
1160 				log("Received disconnect from %s: %u: %.400s",
1161 				    get_remote_ipaddr(), reason, msg);
1162 				xfree(msg);
1163 				fatal_cleanup();
1164 				break;
1165 			case SSH2_MSG_UNIMPLEMENTED:
1166 				seqnr = packet_get_int();
1167 				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1168 				    seqnr);
1169 				break;
1170 			default:
1171 				return type;
1172 				break;
1173 			}
1174 		} else {
1175 			type = packet_read_poll1();
1176 			DBG(debug("received packet type %d", type));
1177 			switch (type) {
1178 			case SSH_MSG_IGNORE:
1179 				break;
1180 			case SSH_MSG_DEBUG:
1181 				msg = packet_get_string(NULL);
1182 				debug("Remote: %.900s", msg);
1183 				xfree(msg);
1184 				break;
1185 			case SSH_MSG_DISCONNECT:
1186 				msg = packet_get_string(NULL);
1187 				log("Received disconnect from %s: %.400s",
1188 				    get_remote_ipaddr(), msg);
1189 				fatal_cleanup();
1190 				xfree(msg);
1191 				break;
1192 			default:
1193 				return type;
1194 				break;
1195 			}
1196 		}
1197 	}
1198 }
1199 
1200 int
1201 packet_read_poll(void)
1202 {
1203 	return packet_read_poll_seqnr(NULL);
1204 }
1205 
1206 /*
1207  * Buffers the given amount of input characters.  This is intended to be used
1208  * together with packet_read_poll.
1209  */
1210 
1211 void
1212 packet_process_incoming(const char *buf, u_int len)
1213 {
1214 	buffer_append(&input, buf, len);
1215 }
1216 
1217 /* Returns a character from the packet. */
1218 
1219 u_int
1220 packet_get_char(void)
1221 {
1222 	char ch;
1223 
1224 	buffer_get(&incoming_packet, &ch, 1);
1225 	return (u_char) ch;
1226 }
1227 
1228 /* Returns an integer from the packet data. */
1229 
1230 u_int
1231 packet_get_int(void)
1232 {
1233 	return buffer_get_int(&incoming_packet);
1234 }
1235 
1236 /*
1237  * Returns an arbitrary precision integer from the packet data.  The integer
1238  * must have been initialized before this call.
1239  */
1240 
1241 void
1242 packet_get_bignum(BIGNUM * value)
1243 {
1244 	buffer_get_bignum(&incoming_packet, value);
1245 }
1246 
1247 void
1248 packet_get_bignum2(BIGNUM * value)
1249 {
1250 	buffer_get_bignum2(&incoming_packet, value);
1251 }
1252 
1253 void *
1254 packet_get_raw(u_int *length_ptr)
1255 {
1256 	u_int bytes = buffer_len(&incoming_packet);
1257 
1258 	if (length_ptr != NULL)
1259 		*length_ptr = bytes;
1260 	return buffer_ptr(&incoming_packet);
1261 }
1262 
1263 int
1264 packet_remaining(void)
1265 {
1266 	return buffer_len(&incoming_packet);
1267 }
1268 
1269 /*
1270  * Returns a string from the packet data.  The string is allocated using
1271  * xmalloc; it is the responsibility of the calling program to free it when
1272  * no longer needed.  The length_ptr argument may be NULL, or point to an
1273  * integer into which the length of the string is stored.
1274  */
1275 
1276 void *
1277 packet_get_string(u_int *length_ptr)
1278 {
1279 	return buffer_get_string(&incoming_packet, length_ptr);
1280 }
1281 char *
1282 packet_get_ascii_cstring()
1283 {
1284 	return buffer_get_ascii_cstring(&incoming_packet);
1285 }
1286 u_char *
1287 packet_get_utf8_cstring()
1288 {
1289 	return buffer_get_utf8_cstring(&incoming_packet);
1290 }
1291 
1292 /*
1293  * Sends a diagnostic message from the server to the client.  This message
1294  * can be sent at any time (but not while constructing another message). The
1295  * message is printed immediately, but only if the client is being executed
1296  * in verbose mode.  These messages are primarily intended to ease debugging
1297  * authentication problems.   The length of the formatted message must not
1298  * exceed 1024 bytes.  This will automatically call packet_write_wait.
1299  */
1300 
1301 void
1302 packet_send_debug(const char *fmt,...)
1303 {
1304 	char buf[1024];
1305 	va_list args;
1306 
1307 	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1308 		return;
1309 
1310 	va_start(args, fmt);
1311 	vsnprintf(buf, sizeof(buf), gettext(fmt), args);
1312 	va_end(args);
1313 
1314 #ifdef ALTPRIVSEP
1315 	/* shouldn't happen */
1316 	if (packet_monitor) {
1317 		debug("packet_send_debug: %s", buf);
1318 		return;
1319 	}
1320 #endif /* ALTPRIVSEP */
1321 
1322 	if (compat20) {
1323 		packet_start(SSH2_MSG_DEBUG);
1324 		packet_put_char(0);	/* bool: always display */
1325 		packet_put_cstring(buf);
1326 		packet_put_cstring("");
1327 	} else {
1328 		packet_start(SSH_MSG_DEBUG);
1329 		packet_put_cstring(buf);
1330 	}
1331 	packet_send();
1332 	packet_write_wait();
1333 }
1334 
1335 /*
1336  * Logs the error plus constructs and sends a disconnect packet, closes the
1337  * connection, and exits.  This function never returns. The error message
1338  * should not contain a newline.  The length of the formatted message must
1339  * not exceed 1024 bytes.
1340  */
1341 
1342 void
1343 packet_disconnect(const char *fmt,...)
1344 {
1345 	char buf[1024];
1346 	va_list args;
1347 	static int disconnecting = 0;
1348 
1349 	if (disconnecting)	/* Guard against recursive invocations. */
1350 		fatal("packet_disconnect called recursively.");
1351 	disconnecting = 1;
1352 
1353 	/*
1354 	 * Format the message.  Note that the caller must make sure the
1355 	 * message is of limited size.
1356 	 */
1357 	va_start(args, fmt);
1358 	vsnprintf(buf, sizeof(buf), fmt, args);
1359 	va_end(args);
1360 
1361 #ifdef ALTPRIVSEP
1362 	/*
1363 	 * If we packet_disconnect() in the monitor the fatal cleanups will take
1364 	 * care of the child.  See main() in sshd.c.  We don't send the packet
1365 	 * disconnect message here because: a) the child might not be looking
1366 	 * for it and b) because we don't really know if the child is compat20
1367 	 * or not as we lost that information when packet_set_monitor() was
1368 	 * called.
1369 	 */
1370 	if (packet_monitor)
1371 		goto close_stuff;
1372 #endif /* ALTPRIVSEP */
1373 
1374 	/* Send the disconnect message to the other side, and wait for it to get sent. */
1375 	if (compat20) {
1376 		packet_start(SSH2_MSG_DISCONNECT);
1377 		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1378 		packet_put_cstring(buf);
1379 		packet_put_cstring("");
1380 	} else {
1381 		packet_start(SSH_MSG_DISCONNECT);
1382 		packet_put_cstring(buf);
1383 	}
1384 	packet_send();
1385 	packet_write_wait();
1386 
1387 #ifdef ALTPRIVSEP
1388 close_stuff:
1389 #endif /* ALTPRIVSEP */
1390 	/* Stop listening for connections. */
1391 	channel_close_all();
1392 
1393 	/* Close the connection. */
1394 	packet_close();
1395 
1396 	/* Display the error locally and exit. */
1397 	log("Disconnecting: %.100s", buf);
1398 	fatal_cleanup();
1399 }
1400 
1401 /* Checks if there is any buffered output, and tries to write some of the output. */
1402 
1403 void
1404 packet_write_poll(void)
1405 {
1406 	int len = buffer_len(&output);
1407 
1408 	if (len > 0) {
1409 		len = write(connection_out, buffer_ptr(&output), len);
1410 		if (len <= 0) {
1411 			if (errno == EAGAIN)
1412 				return;
1413 			else
1414 				fatal("Write failed: %.100s", strerror(errno));
1415 		}
1416 		buffer_consume(&output, len);
1417 	}
1418 }
1419 
1420 /*
1421  * Calls packet_write_poll repeatedly until all pending output data has been
1422  * written.
1423  */
1424 
1425 void
1426 packet_write_wait(void)
1427 {
1428 	fd_set *setp;
1429 
1430 	setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1431 	    sizeof(fd_mask));
1432 	packet_write_poll();
1433 	while (packet_have_data_to_write()) {
1434 		memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1435 		    sizeof(fd_mask));
1436 		FD_SET(connection_out, setp);
1437 		while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1438 		    (errno == EAGAIN || errno == EINTR))
1439 			;
1440 		packet_write_poll();
1441 	}
1442 	xfree(setp);
1443 }
1444 
1445 /* Returns true if there is buffered data to write to the connection. */
1446 
1447 int
1448 packet_have_data_to_write(void)
1449 {
1450 	return buffer_len(&output) != 0;
1451 }
1452 
1453 /* Returns true if there is not too much data to write to the connection. */
1454 
1455 int
1456 packet_not_very_much_data_to_write(void)
1457 {
1458 	if (interactive_mode)
1459 		return buffer_len(&output) < 16384;
1460 	else
1461 		return buffer_len(&output) < 128 * 1024;
1462 }
1463 
1464 /* Informs that the current session is interactive.  Sets IP flags for that. */
1465 
1466 void
1467 packet_set_interactive(int interactive)
1468 {
1469 	static int called = 0;
1470 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1471 	int lowdelay = IPTOS_LOWDELAY;
1472 	int throughput = IPTOS_THROUGHPUT;
1473 #endif
1474 
1475 	if (called)
1476 		return;
1477 	called = 1;
1478 
1479 	/* Record that we are in interactive mode. */
1480 	interactive_mode = interactive;
1481 
1482 	/* Only set socket options if using a socket.  */
1483 	if (!packet_connection_is_on_socket())
1484 		return;
1485 	/*
1486 	 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1487 	 */
1488 	if (interactive) {
1489 		/*
1490 		 * Set IP options for an interactive connection.  Use
1491 		 * IPTOS_LOWDELAY and TCP_NODELAY.
1492 		 */
1493 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1494 		if (packet_connection_is_ipv4()) {
1495 			if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1496 			    &lowdelay, sizeof(lowdelay)) < 0)
1497 				error("setsockopt IPTOS_LOWDELAY: %.100s",
1498 				    strerror(errno));
1499 		}
1500 #endif
1501 		set_nodelay(connection_in);
1502 	}
1503 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1504 	else if (packet_connection_is_ipv4()) {
1505 		/*
1506 		 * Set IP options for a non-interactive connection.  Use
1507 		 * IPTOS_THROUGHPUT.
1508 		 */
1509 		if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &throughput,
1510 		    sizeof(throughput)) < 0)
1511 			error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1512 	}
1513 #endif
1514 }
1515 
1516 /* Returns true if the current connection is interactive. */
1517 
1518 int
1519 packet_is_interactive(void)
1520 {
1521 	return interactive_mode;
1522 }
1523 
1524 int
1525 packet_set_maxsize(int s)
1526 {
1527 	static int called = 0;
1528 
1529 	if (called) {
1530 		log("packet_set_maxsize: called twice: old %d new %d",
1531 		    max_packet_size, s);
1532 		return -1;
1533 	}
1534 	if (s < 4 * 1024 || s > 1024 * 1024) {
1535 		log("packet_set_maxsize: bad size %d", s);
1536 		return -1;
1537 	}
1538 	called = 1;
1539 	debug("packet_set_maxsize: setting to %d", s);
1540 	max_packet_size = s;
1541 	return s;
1542 }
1543 
1544 /* roundup current message to pad bytes */
1545 void
1546 packet_add_padding(u_char pad)
1547 {
1548 	extra_pad = pad;
1549 }
1550 
1551 /*
1552  * 9.2.  Ignored Data Message
1553  *
1554  *   byte      SSH_MSG_IGNORE
1555  *   string    data
1556  *
1557  * All implementations MUST understand (and ignore) this message at any
1558  * time (after receiving the protocol version). No implementation is
1559  * required to send them. This message can be used as an additional
1560  * protection measure against advanced traffic analysis techniques.
1561  */
1562 void
1563 packet_send_ignore(int nbytes)
1564 {
1565 	u_int32_t rnd = 0;
1566 	int i;
1567 
1568 #ifdef ALTPRIVSEP
1569 	/* shouldn't happen -- see packet_set_monitor() */
1570 	if (packet_monitor)
1571 		return;
1572 #endif /* ALTPRIVSEP */
1573 
1574 	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1575 	packet_put_int(nbytes);
1576 	for (i = 0; i < nbytes; i++) {
1577 		if (i % 4 == 0)
1578 			rnd = arc4random();
1579 		packet_put_char((u_char)rnd & 0xff);
1580 		rnd >>= 8;
1581 	}
1582 }
1583 
1584 #define MAX_PACKETS	(1U<<31)
1585 int
1586 packet_need_rekeying(void)
1587 {
1588 	if (datafellows & SSH_BUG_NOREKEY)
1589 		return 0;
1590 	return
1591 	    (p_send.packets > MAX_PACKETS) ||
1592 	    (p_read.packets > MAX_PACKETS) ||
1593 	    (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
1594 	    (max_blocks_in  && (p_read.blocks > max_blocks_in));
1595 }
1596 
1597 void
1598 packet_set_rekey_limit(u_int32_t bytes)
1599 {
1600 	rekey_limit = bytes;
1601 }
1602 
1603 #ifdef ALTPRIVSEP
1604 void
1605 packet_set_server(void)
1606 {
1607 	packet_server = 1;
1608 }
1609 
1610 void
1611 packet_set_no_monitor(void)
1612 {
1613 	packet_server = 0;
1614 }
1615 
1616 int
1617 packet_is_server(void)
1618 {
1619 	return (packet_server);
1620 }
1621 
1622 void
1623 packet_set_monitor(int pipe)
1624 {
1625 	int dup_fd;
1626 
1627 	packet_server = 1;
1628 	packet_monitor = 1;
1629 
1630 	/*
1631 	 * Awful hack follows.
1632 	 *
1633 	 * For SSHv1 the monitor does not process any SSHv1 packets, only
1634 	 * ALTPRIVSEP packets.  We take advantage of that here to keep changes
1635 	 * to packet.c to a minimum by using the SSHv2 binary packet protocol,
1636 	 * with cipher "none," mac "none" and compression alg "none," as the
1637 	 * basis for the monitor protocol.  And so to force packet.c to treat
1638 	 * packets as SSHv2 we force compat20 == 1 here.
1639 	 *
1640 	 * For completeness and to help future developers catch this we also
1641 	 * force compat20 == 1 in the monitor loop, in serverloop.c.
1642 	 */
1643 	compat20 = 1;
1644 
1645 	/*
1646 	 * NOTE:  Assumptions below!
1647 	 *
1648 	 *  - lots of packet.c code assumes that (connection_in ==
1649 	 *  connection_out) -> connection is socket
1650 	 *
1651 	 *  - packet_close() does not shutdown() the connection fildes
1652 	 *  if connection_in != connection_out
1653 	 *
1654 	 *  - other code assumes the connection is a socket if
1655 	 *  connection_in == connection_out
1656 	 */
1657 
1658 	if ((dup_fd = dup(pipe)) < 0)
1659 		fatal("Monitor failed to start: %s", strerror(errno));
1660 
1661 	/*
1662 	 * make sure that the monitor's child's socket is not shutdown(3SOCKET)
1663 	 * when we packet_close()
1664 	 */
1665 	if (packet_connection_is_on_socket())
1666 		connection_out = -1;
1667 
1668 	/* now cleanup state related to ssh socket */
1669 	packet_close();
1670 
1671 	/* now make the monitor pipe look like the ssh connection */
1672 	packet_set_connection(pipe, dup_fd);
1673 }
1674 
1675 int
1676 packet_is_monitor(void)
1677 {
1678 	return (packet_monitor);
1679 }
1680 #endif /* ALTPRIVSEP */
1681