xref: /titanic_41/usr/src/cmd/ssh/libssh/common/packet.c (revision c5024742c2f7d10880eae26cc592353b20a58f4a)
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 2004 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 	    detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
918 		packet_disconnect("crc32 compensation attack: network attack detected");
919 
920 	/* Decrypt data to incoming_packet. */
921 	buffer_clear(&incoming_packet);
922 	cp = buffer_append_space(&incoming_packet, padded_len);
923 	cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
924 
925 	buffer_consume(&input, padded_len);
926 
927 #ifdef PACKET_DEBUG
928 	fprintf(stderr, "read_poll plain: ");
929 	buffer_dump(&incoming_packet);
930 #endif
931 
932 	/* Compute packet checksum. */
933 	checksum = ssh_crc32(buffer_ptr(&incoming_packet),
934 	    buffer_len(&incoming_packet) - 4);
935 
936 	/* Skip padding. */
937 	buffer_consume(&incoming_packet, 8 - len % 8);
938 
939 	/* Test check bytes. */
940 	if (len != buffer_len(&incoming_packet))
941 		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
942 		    len, buffer_len(&incoming_packet));
943 
944 	cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
945 	stored_checksum = GET_32BIT(cp);
946 	if (checksum != stored_checksum)
947 		packet_disconnect("Corrupted check bytes on input.");
948 	buffer_consume_end(&incoming_packet, 4);
949 
950 	if (packet_compression) {
951 		buffer_clear(&compression_buffer);
952 		buffer_uncompress(&incoming_packet, &compression_buffer);
953 		buffer_clear(&incoming_packet);
954 		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
955 		    buffer_len(&compression_buffer));
956 	}
957 	type = buffer_get_char(&incoming_packet);
958 	return type;
959 }
960 
961 static int
962 packet_read_poll2(u_int32_t *seqnr_p)
963 {
964 	static u_int packet_length = 0;
965 	u_int padlen, need;
966 	u_char *macbuf, *cp, type;
967 	int maclen, block_size;
968 	Enc *enc   = NULL;
969 	Mac *mac   = NULL;
970 	Comp *comp = NULL;
971 
972 	if (newkeys[MODE_IN] != NULL) {
973 		enc  = &newkeys[MODE_IN]->enc;
974 		mac  = &newkeys[MODE_IN]->mac;
975 		comp = &newkeys[MODE_IN]->comp;
976 	}
977 	maclen = mac && mac->enabled ? mac->mac_len : 0;
978 	block_size = enc ? enc->block_size : 8;
979 
980 	if (packet_length == 0) {
981 		/*
982 		 * check if input size is less than the cipher block size,
983 		 * decrypt first block and extract length of incoming packet
984 		 */
985 		if (buffer_len(&input) < block_size)
986 			return SSH_MSG_NONE;
987 		buffer_clear(&incoming_packet);
988 		cp = buffer_append_space(&incoming_packet, block_size);
989 		cipher_crypt(&receive_context, cp, buffer_ptr(&input),
990 		    block_size);
991 		cp = buffer_ptr(&incoming_packet);
992 		packet_length = GET_32BIT(cp);
993 		if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
994 			buffer_dump(&incoming_packet);
995 			packet_disconnect("Bad packet length %d.", packet_length);
996 		}
997 		DBG(debug("input: packet len %d", packet_length+4));
998 		buffer_consume(&input, block_size);
999 	}
1000 	/* we have a partial packet of block_size bytes */
1001 	need = 4 + packet_length - block_size;
1002 	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1003 	    need, maclen));
1004 	if (need % block_size != 0)
1005 		fatal("padding error: need %d block %d mod %d",
1006 		    need, block_size, need % block_size);
1007 	/*
1008 	 * check if the entire packet has been received and
1009 	 * decrypt into incoming_packet
1010 	 */
1011 	if (buffer_len(&input) < need + maclen)
1012 		return SSH_MSG_NONE;
1013 #ifdef PACKET_DEBUG
1014 	fprintf(stderr, "read_poll enc/full: ");
1015 	buffer_dump(&input);
1016 #endif
1017 	cp = buffer_append_space(&incoming_packet, need);
1018 	cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1019 	buffer_consume(&input, need);
1020 	/*
1021 	 * compute MAC over seqnr and packet,
1022 	 * increment sequence number for incoming packet
1023 	 */
1024 	if (mac && mac->enabled) {
1025 		macbuf = mac_compute(mac, read_seqnr,
1026 		    buffer_ptr(&incoming_packet),
1027 		    buffer_len(&incoming_packet));
1028 		if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1029 			packet_disconnect("Corrupted MAC on input.");
1030 		DBG(debug("MAC #%d ok", read_seqnr));
1031 		buffer_consume(&input, mac->mac_len);
1032 	}
1033 	if (seqnr_p != NULL)
1034 		*seqnr_p = read_seqnr;
1035 	if (++read_seqnr == 0)
1036 		log("incoming seqnr wraps around");
1037 
1038 	/* get padlen */
1039 	cp = buffer_ptr(&incoming_packet);
1040 	padlen = cp[4];
1041 	DBG(debug("input: padlen %d", padlen));
1042 	if (padlen < 4)
1043 		packet_disconnect("Corrupted padlen %d on input.", padlen);
1044 
1045 	/* skip packet size + padlen, discard padding */
1046 	buffer_consume(&incoming_packet, 4 + 1);
1047 	buffer_consume_end(&incoming_packet, padlen);
1048 
1049 	DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
1050 	if (comp && comp->enabled) {
1051 		buffer_clear(&compression_buffer);
1052 		buffer_uncompress(&incoming_packet, &compression_buffer);
1053 		buffer_clear(&incoming_packet);
1054 		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1055 		    buffer_len(&compression_buffer));
1056 		DBG(debug("input: len after de-compress %d",
1057 		    buffer_len(&incoming_packet)));
1058 	}
1059 	/*
1060 	 * get packet type, implies consume.
1061 	 * return length of payload (without type field)
1062 	 */
1063 	type = buffer_get_char(&incoming_packet);
1064 #ifdef ALTPRIVSEP
1065 	if (type == SSH2_MSG_NEWKEYS)
1066 		/* set_newkeys(MODE_OUT) in client, server, but not monitor */
1067 		if (!packet_is_server() && !packet_is_monitor())
1068 			set_newkeys(MODE_IN);
1069 #else /* ALTPRIVSEP */
1070 	if (type == SSH2_MSG_NEWKEYS)
1071 		set_newkeys(MODE_IN);
1072 #endif /* ALTPRIVSEP */
1073 #ifdef PACKET_DEBUG
1074 	fprintf(stderr, "read/plain[%d]:\r\n", type);
1075 	buffer_dump(&incoming_packet);
1076 #endif
1077 	/* reset for next packet */
1078 	packet_length = 0;
1079 	return type;
1080 }
1081 
1082 int
1083 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1084 {
1085 	u_int reason, seqnr;
1086 	u_char type;
1087 	char *msg;
1088 
1089 	for (;;) {
1090 		if (compat20) {
1091 			type = packet_read_poll2(seqnr_p);
1092 			DBG(debug("received packet type %d", type));
1093 			switch (type) {
1094 			case SSH2_MSG_IGNORE:
1095 				break;
1096 			case SSH2_MSG_DEBUG:
1097 				packet_get_char();
1098 				msg = packet_get_string(NULL);
1099 				debug("Remote: %.900s", msg);
1100 				xfree(msg);
1101 				msg = packet_get_string(NULL);
1102 				xfree(msg);
1103 				break;
1104 			case SSH2_MSG_DISCONNECT:
1105 				reason = packet_get_int();
1106 				msg = packet_get_string(NULL);
1107 				log("Received disconnect from %s: %u: %.400s",
1108 				    get_remote_ipaddr(), reason, msg);
1109 				xfree(msg);
1110 				fatal_cleanup();
1111 				break;
1112 			case SSH2_MSG_UNIMPLEMENTED:
1113 				seqnr = packet_get_int();
1114 				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1115 				    seqnr);
1116 				break;
1117 			default:
1118 				return type;
1119 				break;
1120 			}
1121 		} else {
1122 			type = packet_read_poll1();
1123 			DBG(debug("received packet type %d", type));
1124 			switch (type) {
1125 			case SSH_MSG_IGNORE:
1126 				break;
1127 			case SSH_MSG_DEBUG:
1128 				msg = packet_get_string(NULL);
1129 				debug("Remote: %.900s", msg);
1130 				xfree(msg);
1131 				break;
1132 			case SSH_MSG_DISCONNECT:
1133 				msg = packet_get_string(NULL);
1134 				log("Received disconnect from %s: %.400s",
1135 				    get_remote_ipaddr(), msg);
1136 				fatal_cleanup();
1137 				xfree(msg);
1138 				break;
1139 			default:
1140 				return type;
1141 				break;
1142 			}
1143 		}
1144 	}
1145 }
1146 
1147 int
1148 packet_read_poll(void)
1149 {
1150 	return packet_read_poll_seqnr(NULL);
1151 }
1152 
1153 /*
1154  * Buffers the given amount of input characters.  This is intended to be used
1155  * together with packet_read_poll.
1156  */
1157 
1158 void
1159 packet_process_incoming(const char *buf, u_int len)
1160 {
1161 	buffer_append(&input, buf, len);
1162 }
1163 
1164 /* Returns a character from the packet. */
1165 
1166 u_int
1167 packet_get_char(void)
1168 {
1169 	char ch;
1170 
1171 	buffer_get(&incoming_packet, &ch, 1);
1172 	return (u_char) ch;
1173 }
1174 
1175 /* Returns an integer from the packet data. */
1176 
1177 u_int
1178 packet_get_int(void)
1179 {
1180 	return buffer_get_int(&incoming_packet);
1181 }
1182 
1183 /*
1184  * Returns an arbitrary precision integer from the packet data.  The integer
1185  * must have been initialized before this call.
1186  */
1187 
1188 void
1189 packet_get_bignum(BIGNUM * value)
1190 {
1191 	buffer_get_bignum(&incoming_packet, value);
1192 }
1193 
1194 void
1195 packet_get_bignum2(BIGNUM * value)
1196 {
1197 	buffer_get_bignum2(&incoming_packet, value);
1198 }
1199 
1200 void *
1201 packet_get_raw(u_int *length_ptr)
1202 {
1203 	u_int bytes = buffer_len(&incoming_packet);
1204 
1205 	if (length_ptr != NULL)
1206 		*length_ptr = bytes;
1207 	return buffer_ptr(&incoming_packet);
1208 }
1209 
1210 int
1211 packet_remaining(void)
1212 {
1213 	return buffer_len(&incoming_packet);
1214 }
1215 
1216 /*
1217  * Returns a string from the packet data.  The string is allocated using
1218  * xmalloc; it is the responsibility of the calling program to free it when
1219  * no longer needed.  The length_ptr argument may be NULL, or point to an
1220  * integer into which the length of the string is stored.
1221  */
1222 
1223 void *
1224 packet_get_string(u_int *length_ptr)
1225 {
1226 	return buffer_get_string(&incoming_packet, length_ptr);
1227 }
1228 char *
1229 packet_get_ascii_cstring()
1230 {
1231 	return buffer_get_ascii_cstring(&incoming_packet);
1232 }
1233 u_char *
1234 packet_get_utf8_cstring()
1235 {
1236 	return buffer_get_utf8_cstring(&incoming_packet);
1237 }
1238 
1239 /*
1240  * Sends a diagnostic message from the server to the client.  This message
1241  * can be sent at any time (but not while constructing another message). The
1242  * message is printed immediately, but only if the client is being executed
1243  * in verbose mode.  These messages are primarily intended to ease debugging
1244  * authentication problems.   The length of the formatted message must not
1245  * exceed 1024 bytes.  This will automatically call packet_write_wait.
1246  */
1247 
1248 void
1249 packet_send_debug(const char *fmt,...)
1250 {
1251 	char buf[1024];
1252 	va_list args;
1253 
1254 	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1255 		return;
1256 
1257 	va_start(args, fmt);
1258 	vsnprintf(buf, sizeof(buf), gettext(fmt), args);
1259 	va_end(args);
1260 
1261 #ifdef ALTPRIVSEP
1262 	/* shouldn't happen */
1263 	if (packet_monitor) {
1264 		debug("packet_send_debug: %s", buf);
1265 		return;
1266 	}
1267 #endif /* ALTPRIVSEP */
1268 
1269 	if (compat20) {
1270 		packet_start(SSH2_MSG_DEBUG);
1271 		packet_put_char(0);	/* bool: always display */
1272 		packet_put_cstring(buf);
1273 		packet_put_cstring("");
1274 	} else {
1275 		packet_start(SSH_MSG_DEBUG);
1276 		packet_put_cstring(buf);
1277 	}
1278 	packet_send();
1279 	packet_write_wait();
1280 }
1281 
1282 /*
1283  * Logs the error plus constructs and sends a disconnect packet, closes the
1284  * connection, and exits.  This function never returns. The error message
1285  * should not contain a newline.  The length of the formatted message must
1286  * not exceed 1024 bytes.
1287  */
1288 
1289 void
1290 packet_disconnect(const char *fmt,...)
1291 {
1292 	char buf[1024];
1293 	va_list args;
1294 	static int disconnecting = 0;
1295 
1296 	if (disconnecting)	/* Guard against recursive invocations. */
1297 		fatal("packet_disconnect called recursively.");
1298 	disconnecting = 1;
1299 
1300 	/*
1301 	 * Format the message.  Note that the caller must make sure the
1302 	 * message is of limited size.
1303 	 */
1304 	va_start(args, fmt);
1305 	vsnprintf(buf, sizeof(buf), fmt, args);
1306 	va_end(args);
1307 
1308 #ifdef ALTPRIVSEP
1309 	/*
1310 	 * If we packet_disconnect() in the monitor the fatal cleanups will take
1311 	 * care of the child.  See main() in sshd.c.  We don't send the packet
1312 	 * disconnect message here because: a) the child might not be looking
1313 	 * for it and b) because we don't really know if the child is compat20
1314 	 * or not as we lost that information when packet_set_monitor() was
1315 	 * called.
1316 	 */
1317 	if (packet_monitor)
1318 		goto close_stuff;
1319 #endif /* ALTPRIVSEP */
1320 
1321 	/* Send the disconnect message to the other side, and wait for it to get sent. */
1322 	if (compat20) {
1323 		packet_start(SSH2_MSG_DISCONNECT);
1324 		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1325 		packet_put_cstring(buf);
1326 		packet_put_cstring("");
1327 	} else {
1328 		packet_start(SSH_MSG_DISCONNECT);
1329 		packet_put_cstring(buf);
1330 	}
1331 	packet_send();
1332 	packet_write_wait();
1333 
1334 #ifdef ALTPRIVSEP
1335 close_stuff:
1336 #endif /* ALTPRIVSEP */
1337 	/* Stop listening for connections. */
1338 	channel_close_all();
1339 
1340 	/* Close the connection. */
1341 	packet_close();
1342 
1343 	/* Display the error locally and exit. */
1344 	log("Disconnecting: %.100s", buf);
1345 	fatal_cleanup();
1346 }
1347 
1348 /* Checks if there is any buffered output, and tries to write some of the output. */
1349 
1350 void
1351 packet_write_poll(void)
1352 {
1353 	int len = buffer_len(&output);
1354 
1355 	if (len > 0) {
1356 		len = write(connection_out, buffer_ptr(&output), len);
1357 		if (len <= 0) {
1358 			if (errno == EAGAIN)
1359 				return;
1360 			else
1361 				fatal("Write failed: %.100s", strerror(errno));
1362 		}
1363 		buffer_consume(&output, len);
1364 	}
1365 }
1366 
1367 /*
1368  * Calls packet_write_poll repeatedly until all pending output data has been
1369  * written.
1370  */
1371 
1372 void
1373 packet_write_wait(void)
1374 {
1375 	fd_set *setp;
1376 
1377 	setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1378 	    sizeof(fd_mask));
1379 	packet_write_poll();
1380 	while (packet_have_data_to_write()) {
1381 		memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1382 		    sizeof(fd_mask));
1383 		FD_SET(connection_out, setp);
1384 		while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1385 		    (errno == EAGAIN || errno == EINTR))
1386 			;
1387 		packet_write_poll();
1388 	}
1389 	xfree(setp);
1390 }
1391 
1392 /* Returns true if there is buffered data to write to the connection. */
1393 
1394 int
1395 packet_have_data_to_write(void)
1396 {
1397 	return buffer_len(&output) != 0;
1398 }
1399 
1400 /* Returns true if there is not too much data to write to the connection. */
1401 
1402 int
1403 packet_not_very_much_data_to_write(void)
1404 {
1405 	if (interactive_mode)
1406 		return buffer_len(&output) < 16384;
1407 	else
1408 		return buffer_len(&output) < 128 * 1024;
1409 }
1410 
1411 /* Informs that the current session is interactive.  Sets IP flags for that. */
1412 
1413 void
1414 packet_set_interactive(int interactive)
1415 {
1416 	static int called = 0;
1417 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1418 	int lowdelay = IPTOS_LOWDELAY;
1419 	int throughput = IPTOS_THROUGHPUT;
1420 #endif
1421 
1422 	if (called)
1423 		return;
1424 	called = 1;
1425 
1426 	/* Record that we are in interactive mode. */
1427 	interactive_mode = interactive;
1428 
1429 	/* Only set socket options if using a socket.  */
1430 	if (!packet_connection_is_on_socket())
1431 		return;
1432 	/*
1433 	 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1434 	 */
1435 	if (interactive) {
1436 		/*
1437 		 * Set IP options for an interactive connection.  Use
1438 		 * IPTOS_LOWDELAY and TCP_NODELAY.
1439 		 */
1440 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1441 		if (packet_connection_is_ipv4()) {
1442 			if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1443 			    &lowdelay, sizeof(lowdelay)) < 0)
1444 				error("setsockopt IPTOS_LOWDELAY: %.100s",
1445 				    strerror(errno));
1446 		}
1447 #endif
1448 		set_nodelay(connection_in);
1449 	}
1450 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1451 	else if (packet_connection_is_ipv4()) {
1452 		/*
1453 		 * Set IP options for a non-interactive connection.  Use
1454 		 * IPTOS_THROUGHPUT.
1455 		 */
1456 		if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &throughput,
1457 		    sizeof(throughput)) < 0)
1458 			error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1459 	}
1460 #endif
1461 }
1462 
1463 /* Returns true if the current connection is interactive. */
1464 
1465 int
1466 packet_is_interactive(void)
1467 {
1468 	return interactive_mode;
1469 }
1470 
1471 int
1472 packet_set_maxsize(int s)
1473 {
1474 	static int called = 0;
1475 
1476 	if (called) {
1477 		log("packet_set_maxsize: called twice: old %d new %d",
1478 		    max_packet_size, s);
1479 		return -1;
1480 	}
1481 	if (s < 4 * 1024 || s > 1024 * 1024) {
1482 		log("packet_set_maxsize: bad size %d", s);
1483 		return -1;
1484 	}
1485 	called = 1;
1486 	debug("packet_set_maxsize: setting to %d", s);
1487 	max_packet_size = s;
1488 	return s;
1489 }
1490 
1491 /* roundup current message to pad bytes */
1492 void
1493 packet_add_padding(u_char pad)
1494 {
1495 	extra_pad = pad;
1496 }
1497 
1498 /*
1499  * 9.2.  Ignored Data Message
1500  *
1501  *   byte      SSH_MSG_IGNORE
1502  *   string    data
1503  *
1504  * All implementations MUST understand (and ignore) this message at any
1505  * time (after receiving the protocol version). No implementation is
1506  * required to send them. This message can be used as an additional
1507  * protection measure against advanced traffic analysis techniques.
1508  */
1509 void
1510 packet_send_ignore(int nbytes)
1511 {
1512 	u_int32_t rand = 0;
1513 	int i;
1514 
1515 #ifdef ALTPRIVSEP
1516 	/* shouldn't happen -- see packet_set_monitor() */
1517 	if (packet_monitor)
1518 		return;
1519 #endif /* ALTPRIVSEP */
1520 
1521 	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1522 	packet_put_int(nbytes);
1523 	for (i = 0; i < nbytes; i++) {
1524 		if (i % 4 == 0)
1525 			rand = arc4random();
1526 		packet_put_char(rand & 0xff);
1527 		rand >>= 8;
1528 	}
1529 }
1530 
1531 #ifdef ALTPRIVSEP
1532 void
1533 packet_set_server(void)
1534 {
1535 	packet_server = 1;
1536 }
1537 
1538 void
1539 packet_set_no_monitor(void)
1540 {
1541 	packet_server = 0;
1542 }
1543 
1544 int
1545 packet_is_server(void)
1546 {
1547 	return (packet_server);
1548 }
1549 
1550 void
1551 packet_set_monitor(int pipe)
1552 {
1553 	int dup_fd;
1554 
1555 	packet_server = 1;
1556 	packet_monitor = 1;
1557 
1558 	/*
1559 	 * Awful hack follows.
1560 	 *
1561 	 * For SSHv1 the monitor does not process any SSHv1 packets, only
1562 	 * ALTPRIVSEP packets.  We take advantage of that here to keep changes
1563 	 * to packet.c to a minimum by using the SSHv2 binary packet protocol,
1564 	 * with cipher "none," mac "none" and compression alg "none," as the
1565 	 * basis for the monitor protocol.  And so to force packet.c to treat
1566 	 * packets as SSHv2 we force compat20 == 1 here.
1567 	 *
1568 	 * For completeness and to help future developers catch this we also
1569 	 * force compat20 == 1 in the monitor loop, in serverloop.c.
1570 	 */
1571 	compat20 = 1;
1572 
1573 	/*
1574 	 * NOTE:  Assumptions below!
1575 	 *
1576 	 *  - lots of packet.c code assumes that (connection_in ==
1577 	 *  connection_out) -> connection is socket
1578 	 *
1579 	 *  - packet_close() does not shutdown() the connection fildes
1580 	 *  if connection_in != connection_out
1581 	 *
1582 	 *  - other code assumes the connection is a socket if
1583 	 *  connection_in == connection_out
1584 	 */
1585 
1586 	if ((dup_fd = dup(pipe)) < 0)
1587 		fatal("Monitor failed to start: %s", strerror(errno));
1588 
1589 	/*
1590 	 * make sure that the monitor's child's socket is not shutdown(3SOCKET)
1591 	 * when we packet_close()
1592 	 */
1593 	if (packet_connection_is_on_socket())
1594 		connection_out = -1;
1595 
1596 	/* now cleanup state related to ssh socket */
1597 	packet_close();
1598 
1599 	/* now make the monitor pipe look like the ssh connection */
1600 	packet_set_connection(pipe, dup_fd);
1601 }
1602 
1603 int
1604 packet_is_monitor(void)
1605 {
1606 	return (packet_monitor);
1607 }
1608 #endif /* ALTPRIVSEP */
1609