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