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