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