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