xref: /openbsd-src/usr.bin/ssh/packet.c (revision 48950c12d106c85f315112191a0228d7b83b9510)
1 /* $OpenBSD: packet.c,v 1.181 2013/02/10 23:35:24 djm 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) || (mac && mac->etm))
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), 0, 0);
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 		memset(enc->iv,  0, enc->iv_len);
750 		memset(enc->key, 0, enc->key_len);
751 		memset(mac->key, 0, mac->key_len);
752 		xfree(enc->name);
753 		xfree(enc->iv);
754 		xfree(enc->key);
755 		xfree(mac->name);
756 		xfree(mac->key);
757 		xfree(comp->name);
758 		xfree(active_state->newkeys[mode]);
759 	}
760 	active_state->newkeys[mode] = kex_get_newkeys(mode);
761 	if (active_state->newkeys[mode] == NULL)
762 		fatal("newkeys: no keys for mode %d", mode);
763 	enc  = &active_state->newkeys[mode]->enc;
764 	mac  = &active_state->newkeys[mode]->mac;
765 	comp = &active_state->newkeys[mode]->comp;
766 	if (cipher_authlen(enc->cipher) == 0 && mac_init(mac) == 0)
767 		mac->enabled = 1;
768 	DBG(debug("cipher_init_context: %d", mode));
769 	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
770 	    enc->iv, enc->iv_len, crypt_type);
771 	/* Deleting the keys does not gain extra security */
772 	/* memset(enc->iv,  0, enc->block_size);
773 	   memset(enc->key, 0, enc->key_len);
774 	   memset(mac->key, 0, mac->key_len); */
775 	if ((comp->type == COMP_ZLIB ||
776 	    (comp->type == COMP_DELAYED &&
777 	     active_state->after_authentication)) && comp->enabled == 0) {
778 		packet_init_compression();
779 		if (mode == MODE_OUT)
780 			buffer_compress_init_send(6);
781 		else
782 			buffer_compress_init_recv();
783 		comp->enabled = 1;
784 	}
785 	/*
786 	 * The 2^(blocksize*2) limit is too expensive for 3DES,
787 	 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
788 	 */
789 	if (enc->block_size >= 16)
790 		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
791 	else
792 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
793 	if (active_state->rekey_limit)
794 		*max_blocks = MIN(*max_blocks,
795 		    active_state->rekey_limit / enc->block_size);
796 }
797 
798 /*
799  * Delayed compression for SSH2 is enabled after authentication:
800  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
801  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
802  */
803 static void
804 packet_enable_delayed_compress(void)
805 {
806 	Comp *comp = NULL;
807 	int mode;
808 
809 	/*
810 	 * Remember that we are past the authentication step, so rekeying
811 	 * with COMP_DELAYED will turn on compression immediately.
812 	 */
813 	active_state->after_authentication = 1;
814 	for (mode = 0; mode < MODE_MAX; mode++) {
815 		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
816 		if (active_state->newkeys[mode] == NULL)
817 			continue;
818 		comp = &active_state->newkeys[mode]->comp;
819 		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
820 			packet_init_compression();
821 			if (mode == MODE_OUT)
822 				buffer_compress_init_send(6);
823 			else
824 				buffer_compress_init_recv();
825 			comp->enabled = 1;
826 		}
827 	}
828 }
829 
830 /*
831  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
832  */
833 static void
834 packet_send2_wrapped(void)
835 {
836 	u_char type, *cp, *macbuf = NULL;
837 	u_char padlen, pad = 0;
838 	u_int i, len, authlen = 0, aadlen = 0;
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 		/* disable mac for authenticated encryption */
850 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
851 			mac = NULL;
852 	}
853 	block_size = enc ? enc->block_size : 8;
854 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
855 
856 	cp = buffer_ptr(&active_state->outgoing_packet);
857 	type = cp[5];
858 
859 #ifdef PACKET_DEBUG
860 	fprintf(stderr, "plain:     ");
861 	buffer_dump(&active_state->outgoing_packet);
862 #endif
863 
864 	if (comp && comp->enabled) {
865 		len = buffer_len(&active_state->outgoing_packet);
866 		/* skip header, compress only payload */
867 		buffer_consume(&active_state->outgoing_packet, 5);
868 		buffer_clear(&active_state->compression_buffer);
869 		buffer_compress(&active_state->outgoing_packet,
870 		    &active_state->compression_buffer);
871 		buffer_clear(&active_state->outgoing_packet);
872 		buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
873 		buffer_append(&active_state->outgoing_packet,
874 		    buffer_ptr(&active_state->compression_buffer),
875 		    buffer_len(&active_state->compression_buffer));
876 		DBG(debug("compression: raw %d compressed %d", len,
877 		    buffer_len(&active_state->outgoing_packet)));
878 	}
879 
880 	/* sizeof (packet_len + pad_len + payload) */
881 	len = buffer_len(&active_state->outgoing_packet);
882 
883 	/*
884 	 * calc size of padding, alloc space, get random data,
885 	 * minimum padding is 4 bytes
886 	 */
887 	len -= aadlen; /* packet length is not encrypted for EtM modes */
888 	padlen = block_size - (len % block_size);
889 	if (padlen < 4)
890 		padlen += block_size;
891 	if (active_state->extra_pad) {
892 		/* will wrap if extra_pad+padlen > 255 */
893 		active_state->extra_pad =
894 		    roundup(active_state->extra_pad, block_size);
895 		pad = active_state->extra_pad -
896 		    ((len + padlen) % active_state->extra_pad);
897 		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
898 		    pad, len, padlen, active_state->extra_pad);
899 		padlen += pad;
900 		active_state->extra_pad = 0;
901 	}
902 	cp = buffer_append_space(&active_state->outgoing_packet, padlen);
903 	if (enc && !active_state->send_context.plaintext) {
904 		/* random padding */
905 		for (i = 0; i < padlen; i++) {
906 			if (i % 4 == 0)
907 				rnd = arc4random();
908 			cp[i] = rnd & 0xff;
909 			rnd >>= 8;
910 		}
911 	} else {
912 		/* clear padding */
913 		memset(cp, 0, padlen);
914 	}
915 	/* sizeof (packet_len + pad_len + payload + padding) */
916 	len = buffer_len(&active_state->outgoing_packet);
917 	cp = buffer_ptr(&active_state->outgoing_packet);
918 	/* packet_length includes payload, padding and padding length field */
919 	put_u32(cp, len - 4);
920 	cp[4] = padlen;
921 	DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
922 	    len, padlen, aadlen));
923 
924 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
925 	if (mac && mac->enabled && !mac->etm) {
926 		macbuf = mac_compute(mac, active_state->p_send.seqnr,
927 		    buffer_ptr(&active_state->outgoing_packet), len);
928 		DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
929 	}
930 	/* encrypt packet and append to output buffer. */
931 	cp = buffer_append_space(&active_state->output, len + authlen);
932 	cipher_crypt(&active_state->send_context, cp,
933 	    buffer_ptr(&active_state->outgoing_packet),
934 	    len - aadlen, aadlen, authlen);
935 	/* append unencrypted MAC */
936 	if (mac && mac->enabled) {
937 		if (mac->etm) {
938 			/* EtM: compute mac over aadlen + cipher text */
939 			macbuf = mac_compute(mac,
940 			    active_state->p_send.seqnr, cp, len);
941 			DBG(debug("done calc MAC(EtM) out #%d",
942 			    active_state->p_send.seqnr));
943 		}
944 		buffer_append(&active_state->output, macbuf, mac->mac_len);
945 	}
946 #ifdef PACKET_DEBUG
947 	fprintf(stderr, "encrypted: ");
948 	buffer_dump(&active_state->output);
949 #endif
950 	/* increment sequence number for outgoing packets */
951 	if (++active_state->p_send.seqnr == 0)
952 		logit("outgoing seqnr wraps around");
953 	if (++active_state->p_send.packets == 0)
954 		if (!(datafellows & SSH_BUG_NOREKEY))
955 			fatal("XXX too many packets with same key");
956 	active_state->p_send.blocks += len / block_size;
957 	active_state->p_send.bytes += len;
958 	buffer_clear(&active_state->outgoing_packet);
959 
960 	if (type == SSH2_MSG_NEWKEYS)
961 		set_newkeys(MODE_OUT);
962 	else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
963 		packet_enable_delayed_compress();
964 }
965 
966 static void
967 packet_send2(void)
968 {
969 	struct packet *p;
970 	u_char type, *cp;
971 
972 	cp = buffer_ptr(&active_state->outgoing_packet);
973 	type = cp[5];
974 
975 	/* during rekeying we can only send key exchange messages */
976 	if (active_state->rekeying) {
977 		if ((type < SSH2_MSG_TRANSPORT_MIN) ||
978 		    (type > SSH2_MSG_TRANSPORT_MAX) ||
979 		    (type == SSH2_MSG_SERVICE_REQUEST) ||
980 		    (type == SSH2_MSG_SERVICE_ACCEPT)) {
981 			debug("enqueue packet: %u", type);
982 			p = xmalloc(sizeof(*p));
983 			p->type = type;
984 			memcpy(&p->payload, &active_state->outgoing_packet,
985 			    sizeof(Buffer));
986 			buffer_init(&active_state->outgoing_packet);
987 			TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
988 			return;
989 		}
990 	}
991 
992 	/* rekeying starts with sending KEXINIT */
993 	if (type == SSH2_MSG_KEXINIT)
994 		active_state->rekeying = 1;
995 
996 	packet_send2_wrapped();
997 
998 	/* after a NEWKEYS message we can send the complete queue */
999 	if (type == SSH2_MSG_NEWKEYS) {
1000 		active_state->rekeying = 0;
1001 		while ((p = TAILQ_FIRST(&active_state->outgoing))) {
1002 			type = p->type;
1003 			debug("dequeue packet: %u", type);
1004 			buffer_free(&active_state->outgoing_packet);
1005 			memcpy(&active_state->outgoing_packet, &p->payload,
1006 			    sizeof(Buffer));
1007 			TAILQ_REMOVE(&active_state->outgoing, p, next);
1008 			xfree(p);
1009 			packet_send2_wrapped();
1010 		}
1011 	}
1012 }
1013 
1014 void
1015 packet_send(void)
1016 {
1017 	if (compat20)
1018 		packet_send2();
1019 	else
1020 		packet_send1();
1021 	DBG(debug("packet_send done"));
1022 }
1023 
1024 /*
1025  * Waits until a packet has been received, and returns its type.  Note that
1026  * no other data is processed until this returns, so this function should not
1027  * be used during the interactive session.
1028  */
1029 
1030 int
1031 packet_read_seqnr(u_int32_t *seqnr_p)
1032 {
1033 	int type, len, ret, ms_remain, cont;
1034 	fd_set *setp;
1035 	char buf[8192];
1036 	struct timeval timeout, start, *timeoutp = NULL;
1037 
1038 	DBG(debug("packet_read()"));
1039 
1040 	setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1041 	    NFDBITS), sizeof(fd_mask));
1042 
1043 	/* Since we are blocking, ensure that all written packets have been sent. */
1044 	packet_write_wait();
1045 
1046 	/* Stay in the loop until we have received a complete packet. */
1047 	for (;;) {
1048 		/* Try to read a packet from the buffer. */
1049 		type = packet_read_poll_seqnr(seqnr_p);
1050 		if (!compat20 && (
1051 		    type == SSH_SMSG_SUCCESS
1052 		    || type == SSH_SMSG_FAILURE
1053 		    || type == SSH_CMSG_EOF
1054 		    || type == SSH_CMSG_EXIT_CONFIRMATION))
1055 			packet_check_eom();
1056 		/* If we got a packet, return it. */
1057 		if (type != SSH_MSG_NONE) {
1058 			xfree(setp);
1059 			return type;
1060 		}
1061 		/*
1062 		 * Otherwise, wait for some data to arrive, add it to the
1063 		 * buffer, and try again.
1064 		 */
1065 		memset(setp, 0, howmany(active_state->connection_in + 1,
1066 		    NFDBITS) * sizeof(fd_mask));
1067 		FD_SET(active_state->connection_in, setp);
1068 
1069 		if (active_state->packet_timeout_ms > 0) {
1070 			ms_remain = active_state->packet_timeout_ms;
1071 			timeoutp = &timeout;
1072 		}
1073 		/* Wait for some data to arrive. */
1074 		for (;;) {
1075 			if (active_state->packet_timeout_ms != -1) {
1076 				ms_to_timeval(&timeout, ms_remain);
1077 				gettimeofday(&start, NULL);
1078 			}
1079 			if ((ret = select(active_state->connection_in + 1, setp,
1080 			    NULL, NULL, timeoutp)) >= 0)
1081 				break;
1082 			if (errno != EAGAIN && errno != EINTR)
1083 				break;
1084 			if (active_state->packet_timeout_ms == -1)
1085 				continue;
1086 			ms_subtract_diff(&start, &ms_remain);
1087 			if (ms_remain <= 0) {
1088 				ret = 0;
1089 				break;
1090 			}
1091 		}
1092 		if (ret == 0) {
1093 			logit("Connection to %.200s timed out while "
1094 			    "waiting to read", get_remote_ipaddr());
1095 			cleanup_exit(255);
1096 		}
1097 		/* Read data from the socket. */
1098 		do {
1099 			cont = 0;
1100 			len = roaming_read(active_state->connection_in, buf,
1101 			    sizeof(buf), &cont);
1102 		} while (len == 0 && cont);
1103 		if (len == 0) {
1104 			logit("Connection closed by %.200s", get_remote_ipaddr());
1105 			cleanup_exit(255);
1106 		}
1107 		if (len < 0)
1108 			fatal("Read from socket failed: %.100s", strerror(errno));
1109 		/* Append it to the buffer. */
1110 		packet_process_incoming(buf, len);
1111 	}
1112 	/* NOTREACHED */
1113 }
1114 
1115 int
1116 packet_read(void)
1117 {
1118 	return packet_read_seqnr(NULL);
1119 }
1120 
1121 /*
1122  * Waits until a packet has been received, verifies that its type matches
1123  * that given, and gives a fatal error and exits if there is a mismatch.
1124  */
1125 
1126 void
1127 packet_read_expect(int expected_type)
1128 {
1129 	int type;
1130 
1131 	type = packet_read();
1132 	if (type != expected_type)
1133 		packet_disconnect("Protocol error: expected packet type %d, got %d",
1134 		    expected_type, type);
1135 }
1136 
1137 /* Checks if a full packet is available in the data received so far via
1138  * packet_process_incoming.  If so, reads the packet; otherwise returns
1139  * SSH_MSG_NONE.  This does not wait for data from the connection.
1140  *
1141  * SSH_MSG_DISCONNECT is handled specially here.  Also,
1142  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1143  * to higher levels.
1144  */
1145 
1146 static int
1147 packet_read_poll1(void)
1148 {
1149 	u_int len, padded_len;
1150 	u_char *cp, type;
1151 	u_int checksum, stored_checksum;
1152 
1153 	/* Check if input size is less than minimum packet size. */
1154 	if (buffer_len(&active_state->input) < 4 + 8)
1155 		return SSH_MSG_NONE;
1156 	/* Get length of incoming packet. */
1157 	cp = buffer_ptr(&active_state->input);
1158 	len = get_u32(cp);
1159 	if (len < 1 + 2 + 2 || len > 256 * 1024)
1160 		packet_disconnect("Bad packet length %u.", len);
1161 	padded_len = (len + 8) & ~7;
1162 
1163 	/* Check if the packet has been entirely received. */
1164 	if (buffer_len(&active_state->input) < 4 + padded_len)
1165 		return SSH_MSG_NONE;
1166 
1167 	/* The entire packet is in buffer. */
1168 
1169 	/* Consume packet length. */
1170 	buffer_consume(&active_state->input, 4);
1171 
1172 	/*
1173 	 * Cryptographic attack detector for ssh
1174 	 * (C)1998 CORE-SDI, Buenos Aires Argentina
1175 	 * Ariel Futoransky(futo@core-sdi.com)
1176 	 */
1177 	if (!active_state->receive_context.plaintext) {
1178 		switch (detect_attack(buffer_ptr(&active_state->input),
1179 		    padded_len)) {
1180 		case DEATTACK_DETECTED:
1181 			packet_disconnect("crc32 compensation attack: "
1182 			    "network attack detected");
1183 		case DEATTACK_DOS_DETECTED:
1184 			packet_disconnect("deattack denial of "
1185 			    "service detected");
1186 		}
1187 	}
1188 
1189 	/* Decrypt data to incoming_packet. */
1190 	buffer_clear(&active_state->incoming_packet);
1191 	cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1192 	cipher_crypt(&active_state->receive_context, cp,
1193 	    buffer_ptr(&active_state->input), padded_len, 0, 0);
1194 
1195 	buffer_consume(&active_state->input, padded_len);
1196 
1197 #ifdef PACKET_DEBUG
1198 	fprintf(stderr, "read_poll plain: ");
1199 	buffer_dump(&active_state->incoming_packet);
1200 #endif
1201 
1202 	/* Compute packet checksum. */
1203 	checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1204 	    buffer_len(&active_state->incoming_packet) - 4);
1205 
1206 	/* Skip padding. */
1207 	buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1208 
1209 	/* Test check bytes. */
1210 	if (len != buffer_len(&active_state->incoming_packet))
1211 		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1212 		    len, buffer_len(&active_state->incoming_packet));
1213 
1214 	cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1215 	stored_checksum = get_u32(cp);
1216 	if (checksum != stored_checksum)
1217 		packet_disconnect("Corrupted check bytes on input.");
1218 	buffer_consume_end(&active_state->incoming_packet, 4);
1219 
1220 	if (active_state->packet_compression) {
1221 		buffer_clear(&active_state->compression_buffer);
1222 		buffer_uncompress(&active_state->incoming_packet,
1223 		    &active_state->compression_buffer);
1224 		buffer_clear(&active_state->incoming_packet);
1225 		buffer_append(&active_state->incoming_packet,
1226 		    buffer_ptr(&active_state->compression_buffer),
1227 		    buffer_len(&active_state->compression_buffer));
1228 	}
1229 	active_state->p_read.packets++;
1230 	active_state->p_read.bytes += padded_len + 4;
1231 	type = buffer_get_char(&active_state->incoming_packet);
1232 	if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1233 		packet_disconnect("Invalid ssh1 packet type: %d", type);
1234 	return type;
1235 }
1236 
1237 static int
1238 packet_read_poll2(u_int32_t *seqnr_p)
1239 {
1240 	u_int padlen, need;
1241 	u_char *macbuf = NULL, *cp, type;
1242 	u_int maclen, authlen = 0, aadlen = 0, block_size;
1243 	Enc *enc   = NULL;
1244 	Mac *mac   = NULL;
1245 	Comp *comp = NULL;
1246 
1247 	if (active_state->packet_discard)
1248 		return SSH_MSG_NONE;
1249 
1250 	if (active_state->newkeys[MODE_IN] != NULL) {
1251 		enc  = &active_state->newkeys[MODE_IN]->enc;
1252 		mac  = &active_state->newkeys[MODE_IN]->mac;
1253 		comp = &active_state->newkeys[MODE_IN]->comp;
1254 		/* disable mac for authenticated encryption */
1255 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
1256 			mac = NULL;
1257 	}
1258 	maclen = mac && mac->enabled ? mac->mac_len : 0;
1259 	block_size = enc ? enc->block_size : 8;
1260 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1261 
1262 	if (aadlen && active_state->packlen == 0) {
1263 		if (buffer_len(&active_state->input) < 4)
1264 			return SSH_MSG_NONE;
1265 		cp = buffer_ptr(&active_state->input);
1266 		active_state->packlen = get_u32(cp);
1267 		if (active_state->packlen < 1 + 4 ||
1268 		    active_state->packlen > PACKET_MAX_SIZE) {
1269 #ifdef PACKET_DEBUG
1270 			buffer_dump(&active_state->input);
1271 #endif
1272 			logit("Bad packet length %u.", active_state->packlen);
1273 			packet_disconnect("Packet corrupt");
1274 		}
1275 		buffer_clear(&active_state->incoming_packet);
1276 	} else if (active_state->packlen == 0) {
1277 		/*
1278 		 * check if input size is less than the cipher block size,
1279 		 * decrypt first block and extract length of incoming packet
1280 		 */
1281 		if (buffer_len(&active_state->input) < block_size)
1282 			return SSH_MSG_NONE;
1283 		buffer_clear(&active_state->incoming_packet);
1284 		cp = buffer_append_space(&active_state->incoming_packet,
1285 		    block_size);
1286 		cipher_crypt(&active_state->receive_context, cp,
1287 		    buffer_ptr(&active_state->input), block_size, 0, 0);
1288 		cp = buffer_ptr(&active_state->incoming_packet);
1289 		active_state->packlen = get_u32(cp);
1290 		if (active_state->packlen < 1 + 4 ||
1291 		    active_state->packlen > PACKET_MAX_SIZE) {
1292 #ifdef PACKET_DEBUG
1293 			buffer_dump(&active_state->incoming_packet);
1294 #endif
1295 			logit("Bad packet length %u.", active_state->packlen);
1296 			packet_start_discard(enc, mac, active_state->packlen,
1297 			    PACKET_MAX_SIZE);
1298 			return SSH_MSG_NONE;
1299 		}
1300 		buffer_consume(&active_state->input, block_size);
1301 	}
1302 	DBG(debug("input: packet len %u", active_state->packlen+4));
1303 	if (aadlen) {
1304 		/* only the payload is encrypted */
1305 		need = active_state->packlen;
1306 	} else {
1307 		/*
1308 		 * the payload size and the payload are encrypted, but we
1309 		 * have a partial packet of block_size bytes
1310 		 */
1311 		need = 4 + active_state->packlen - block_size;
1312 	}
1313 	DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1314 	    " aadlen %d", block_size, need, maclen, authlen, aadlen));
1315 	if (need % block_size != 0) {
1316 		logit("padding error: need %d block %d mod %d",
1317 		    need, block_size, need % block_size);
1318 		packet_start_discard(enc, mac, active_state->packlen,
1319 		    PACKET_MAX_SIZE - block_size);
1320 		return SSH_MSG_NONE;
1321 	}
1322 	/*
1323 	 * check if the entire packet has been received and
1324 	 * decrypt into incoming_packet:
1325 	 * 'aadlen' bytes are unencrypted, but authenticated.
1326 	 * 'need' bytes are encrypted, followed by either
1327 	 * 'authlen' bytes of authentication tag or
1328 	 * 'maclen' bytes of message authentication code.
1329 	 */
1330 	if (buffer_len(&active_state->input) < aadlen + need + authlen + maclen)
1331 		return SSH_MSG_NONE;
1332 #ifdef PACKET_DEBUG
1333 	fprintf(stderr, "read_poll enc/full: ");
1334 	buffer_dump(&active_state->input);
1335 #endif
1336 	/* EtM: compute mac over encrypted input */
1337 	if (mac && mac->enabled && mac->etm)
1338 		macbuf = mac_compute(mac, active_state->p_read.seqnr,
1339 		    buffer_ptr(&active_state->input), aadlen + need);
1340 	cp = buffer_append_space(&active_state->incoming_packet, aadlen + need);
1341 	cipher_crypt(&active_state->receive_context, cp,
1342 	    buffer_ptr(&active_state->input), need, aadlen, authlen);
1343 	buffer_consume(&active_state->input, aadlen + need + authlen);
1344 	/*
1345 	 * compute MAC over seqnr and packet,
1346 	 * increment sequence number for incoming packet
1347 	 */
1348 	if (mac && mac->enabled) {
1349 		if (!mac->etm)
1350 			macbuf = mac_compute(mac, active_state->p_read.seqnr,
1351 			    buffer_ptr(&active_state->incoming_packet),
1352 			    buffer_len(&active_state->incoming_packet));
1353 		if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input),
1354 		    mac->mac_len) != 0) {
1355 			logit("Corrupted MAC on input.");
1356 			if (need > PACKET_MAX_SIZE)
1357 				fatal("internal error need %d", need);
1358 			packet_start_discard(enc, mac, active_state->packlen,
1359 			    PACKET_MAX_SIZE - need);
1360 			return SSH_MSG_NONE;
1361 		}
1362 
1363 		DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1364 		buffer_consume(&active_state->input, mac->mac_len);
1365 	}
1366 	/* XXX now it's safe to use fatal/packet_disconnect */
1367 	if (seqnr_p != NULL)
1368 		*seqnr_p = active_state->p_read.seqnr;
1369 	if (++active_state->p_read.seqnr == 0)
1370 		logit("incoming seqnr wraps around");
1371 	if (++active_state->p_read.packets == 0)
1372 		if (!(datafellows & SSH_BUG_NOREKEY))
1373 			fatal("XXX too many packets with same key");
1374 	active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1375 	active_state->p_read.bytes += active_state->packlen + 4;
1376 
1377 	/* get padlen */
1378 	cp = buffer_ptr(&active_state->incoming_packet);
1379 	padlen = cp[4];
1380 	DBG(debug("input: padlen %d", padlen));
1381 	if (padlen < 4)
1382 		packet_disconnect("Corrupted padlen %d on input.", padlen);
1383 
1384 	/* skip packet size + padlen, discard padding */
1385 	buffer_consume(&active_state->incoming_packet, 4 + 1);
1386 	buffer_consume_end(&active_state->incoming_packet, padlen);
1387 
1388 	DBG(debug("input: len before de-compress %d",
1389 	    buffer_len(&active_state->incoming_packet)));
1390 	if (comp && comp->enabled) {
1391 		buffer_clear(&active_state->compression_buffer);
1392 		buffer_uncompress(&active_state->incoming_packet,
1393 		    &active_state->compression_buffer);
1394 		buffer_clear(&active_state->incoming_packet);
1395 		buffer_append(&active_state->incoming_packet,
1396 		    buffer_ptr(&active_state->compression_buffer),
1397 		    buffer_len(&active_state->compression_buffer));
1398 		DBG(debug("input: len after de-compress %d",
1399 		    buffer_len(&active_state->incoming_packet)));
1400 	}
1401 	/*
1402 	 * get packet type, implies consume.
1403 	 * return length of payload (without type field)
1404 	 */
1405 	type = buffer_get_char(&active_state->incoming_packet);
1406 	if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1407 		packet_disconnect("Invalid ssh2 packet type: %d", type);
1408 	if (type == SSH2_MSG_NEWKEYS)
1409 		set_newkeys(MODE_IN);
1410 	else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1411 	    !active_state->server_side)
1412 		packet_enable_delayed_compress();
1413 #ifdef PACKET_DEBUG
1414 	fprintf(stderr, "read/plain[%d]:\r\n", type);
1415 	buffer_dump(&active_state->incoming_packet);
1416 #endif
1417 	/* reset for next packet */
1418 	active_state->packlen = 0;
1419 	return type;
1420 }
1421 
1422 int
1423 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1424 {
1425 	u_int reason, seqnr;
1426 	u_char type;
1427 	char *msg;
1428 
1429 	for (;;) {
1430 		if (compat20) {
1431 			type = packet_read_poll2(seqnr_p);
1432 			if (type) {
1433 				active_state->keep_alive_timeouts = 0;
1434 				DBG(debug("received packet type %d", type));
1435 			}
1436 			switch (type) {
1437 			case SSH2_MSG_IGNORE:
1438 				debug3("Received SSH2_MSG_IGNORE");
1439 				break;
1440 			case SSH2_MSG_DEBUG:
1441 				packet_get_char();
1442 				msg = packet_get_string(NULL);
1443 				debug("Remote: %.900s", msg);
1444 				xfree(msg);
1445 				msg = packet_get_string(NULL);
1446 				xfree(msg);
1447 				break;
1448 			case SSH2_MSG_DISCONNECT:
1449 				reason = packet_get_int();
1450 				msg = packet_get_string(NULL);
1451 				error("Received disconnect from %s: %u: %.400s",
1452 				    get_remote_ipaddr(), reason, msg);
1453 				xfree(msg);
1454 				cleanup_exit(255);
1455 				break;
1456 			case SSH2_MSG_UNIMPLEMENTED:
1457 				seqnr = packet_get_int();
1458 				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1459 				    seqnr);
1460 				break;
1461 			default:
1462 				return type;
1463 			}
1464 		} else {
1465 			type = packet_read_poll1();
1466 			switch (type) {
1467 			case SSH_MSG_IGNORE:
1468 				break;
1469 			case SSH_MSG_DEBUG:
1470 				msg = packet_get_string(NULL);
1471 				debug("Remote: %.900s", msg);
1472 				xfree(msg);
1473 				break;
1474 			case SSH_MSG_DISCONNECT:
1475 				msg = packet_get_string(NULL);
1476 				error("Received disconnect from %s: %.400s",
1477 				    get_remote_ipaddr(), msg);
1478 				cleanup_exit(255);
1479 				break;
1480 			default:
1481 				if (type)
1482 					DBG(debug("received packet type %d", type));
1483 				return type;
1484 			}
1485 		}
1486 	}
1487 }
1488 
1489 /*
1490  * Buffers the given amount of input characters.  This is intended to be used
1491  * together with packet_read_poll.
1492  */
1493 
1494 void
1495 packet_process_incoming(const char *buf, u_int len)
1496 {
1497 	if (active_state->packet_discard) {
1498 		active_state->keep_alive_timeouts = 0; /* ?? */
1499 		if (len >= active_state->packet_discard)
1500 			packet_stop_discard();
1501 		active_state->packet_discard -= len;
1502 		return;
1503 	}
1504 	buffer_append(&active_state->input, buf, len);
1505 }
1506 
1507 /* Returns a character from the packet. */
1508 
1509 u_int
1510 packet_get_char(void)
1511 {
1512 	char ch;
1513 
1514 	buffer_get(&active_state->incoming_packet, &ch, 1);
1515 	return (u_char) ch;
1516 }
1517 
1518 /* Returns an integer from the packet data. */
1519 
1520 u_int
1521 packet_get_int(void)
1522 {
1523 	return buffer_get_int(&active_state->incoming_packet);
1524 }
1525 
1526 /* Returns an 64 bit integer from the packet data. */
1527 
1528 u_int64_t
1529 packet_get_int64(void)
1530 {
1531 	return buffer_get_int64(&active_state->incoming_packet);
1532 }
1533 
1534 /*
1535  * Returns an arbitrary precision integer from the packet data.  The integer
1536  * must have been initialized before this call.
1537  */
1538 
1539 void
1540 packet_get_bignum(BIGNUM * value)
1541 {
1542 	buffer_get_bignum(&active_state->incoming_packet, value);
1543 }
1544 
1545 void
1546 packet_get_bignum2(BIGNUM * value)
1547 {
1548 	buffer_get_bignum2(&active_state->incoming_packet, value);
1549 }
1550 
1551 void
1552 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point)
1553 {
1554 	buffer_get_ecpoint(&active_state->incoming_packet, curve, point);
1555 }
1556 
1557 void *
1558 packet_get_raw(u_int *length_ptr)
1559 {
1560 	u_int bytes = buffer_len(&active_state->incoming_packet);
1561 
1562 	if (length_ptr != NULL)
1563 		*length_ptr = bytes;
1564 	return buffer_ptr(&active_state->incoming_packet);
1565 }
1566 
1567 int
1568 packet_remaining(void)
1569 {
1570 	return buffer_len(&active_state->incoming_packet);
1571 }
1572 
1573 /*
1574  * Returns a string from the packet data.  The string is allocated using
1575  * xmalloc; it is the responsibility of the calling program to free it when
1576  * no longer needed.  The length_ptr argument may be NULL, or point to an
1577  * integer into which the length of the string is stored.
1578  */
1579 
1580 void *
1581 packet_get_string(u_int *length_ptr)
1582 {
1583 	return buffer_get_string(&active_state->incoming_packet, length_ptr);
1584 }
1585 
1586 void *
1587 packet_get_string_ptr(u_int *length_ptr)
1588 {
1589 	return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1590 }
1591 
1592 /* Ensures the returned string has no embedded \0 characters in it. */
1593 char *
1594 packet_get_cstring(u_int *length_ptr)
1595 {
1596 	return buffer_get_cstring(&active_state->incoming_packet, length_ptr);
1597 }
1598 
1599 /*
1600  * Sends a diagnostic message from the server to the client.  This message
1601  * can be sent at any time (but not while constructing another message). The
1602  * message is printed immediately, but only if the client is being executed
1603  * in verbose mode.  These messages are primarily intended to ease debugging
1604  * authentication problems.   The length of the formatted message must not
1605  * exceed 1024 bytes.  This will automatically call packet_write_wait.
1606  */
1607 
1608 void
1609 packet_send_debug(const char *fmt,...)
1610 {
1611 	char buf[1024];
1612 	va_list args;
1613 
1614 	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1615 		return;
1616 
1617 	va_start(args, fmt);
1618 	vsnprintf(buf, sizeof(buf), fmt, args);
1619 	va_end(args);
1620 
1621 	if (compat20) {
1622 		packet_start(SSH2_MSG_DEBUG);
1623 		packet_put_char(0);	/* bool: always display */
1624 		packet_put_cstring(buf);
1625 		packet_put_cstring("");
1626 	} else {
1627 		packet_start(SSH_MSG_DEBUG);
1628 		packet_put_cstring(buf);
1629 	}
1630 	packet_send();
1631 	packet_write_wait();
1632 }
1633 
1634 /*
1635  * Logs the error plus constructs and sends a disconnect packet, closes the
1636  * connection, and exits.  This function never returns. The error message
1637  * should not contain a newline.  The length of the formatted message must
1638  * not exceed 1024 bytes.
1639  */
1640 
1641 void
1642 packet_disconnect(const char *fmt,...)
1643 {
1644 	char buf[1024];
1645 	va_list args;
1646 	static int disconnecting = 0;
1647 
1648 	if (disconnecting)	/* Guard against recursive invocations. */
1649 		fatal("packet_disconnect called recursively.");
1650 	disconnecting = 1;
1651 
1652 	/*
1653 	 * Format the message.  Note that the caller must make sure the
1654 	 * message is of limited size.
1655 	 */
1656 	va_start(args, fmt);
1657 	vsnprintf(buf, sizeof(buf), fmt, args);
1658 	va_end(args);
1659 
1660 	/* Display the error locally */
1661 	logit("Disconnecting: %.100s", buf);
1662 
1663 	/* Send the disconnect message to the other side, and wait for it to get sent. */
1664 	if (compat20) {
1665 		packet_start(SSH2_MSG_DISCONNECT);
1666 		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1667 		packet_put_cstring(buf);
1668 		packet_put_cstring("");
1669 	} else {
1670 		packet_start(SSH_MSG_DISCONNECT);
1671 		packet_put_cstring(buf);
1672 	}
1673 	packet_send();
1674 	packet_write_wait();
1675 
1676 	/* Stop listening for connections. */
1677 	channel_close_all();
1678 
1679 	/* Close the connection. */
1680 	packet_close();
1681 	cleanup_exit(255);
1682 }
1683 
1684 /* Checks if there is any buffered output, and tries to write some of the output. */
1685 
1686 void
1687 packet_write_poll(void)
1688 {
1689 	int len = buffer_len(&active_state->output);
1690 	int cont;
1691 
1692 	if (len > 0) {
1693 		cont = 0;
1694 		len = roaming_write(active_state->connection_out,
1695 		    buffer_ptr(&active_state->output), len, &cont);
1696 		if (len == -1) {
1697 			if (errno == EINTR || errno == EAGAIN)
1698 				return;
1699 			fatal("Write failed: %.100s", strerror(errno));
1700 		}
1701 		if (len == 0 && !cont)
1702 			fatal("Write connection closed");
1703 		buffer_consume(&active_state->output, len);
1704 	}
1705 }
1706 
1707 /*
1708  * Calls packet_write_poll repeatedly until all pending output data has been
1709  * written.
1710  */
1711 
1712 void
1713 packet_write_wait(void)
1714 {
1715 	fd_set *setp;
1716 	int ret, ms_remain;
1717 	struct timeval start, timeout, *timeoutp = NULL;
1718 
1719 	setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1720 	    NFDBITS), sizeof(fd_mask));
1721 	packet_write_poll();
1722 	while (packet_have_data_to_write()) {
1723 		memset(setp, 0, howmany(active_state->connection_out + 1,
1724 		    NFDBITS) * sizeof(fd_mask));
1725 		FD_SET(active_state->connection_out, setp);
1726 
1727 		if (active_state->packet_timeout_ms > 0) {
1728 			ms_remain = active_state->packet_timeout_ms;
1729 			timeoutp = &timeout;
1730 		}
1731 		for (;;) {
1732 			if (active_state->packet_timeout_ms != -1) {
1733 				ms_to_timeval(&timeout, ms_remain);
1734 				gettimeofday(&start, NULL);
1735 			}
1736 			if ((ret = select(active_state->connection_out + 1,
1737 			    NULL, setp, NULL, timeoutp)) >= 0)
1738 				break;
1739 			if (errno != EAGAIN && errno != EINTR)
1740 				break;
1741 			if (active_state->packet_timeout_ms == -1)
1742 				continue;
1743 			ms_subtract_diff(&start, &ms_remain);
1744 			if (ms_remain <= 0) {
1745 				ret = 0;
1746 				break;
1747 			}
1748 		}
1749 		if (ret == 0) {
1750 			logit("Connection to %.200s timed out while "
1751 			    "waiting to write", get_remote_ipaddr());
1752 			cleanup_exit(255);
1753 		}
1754 		packet_write_poll();
1755 	}
1756 	xfree(setp);
1757 }
1758 
1759 /* Returns true if there is buffered data to write to the connection. */
1760 
1761 int
1762 packet_have_data_to_write(void)
1763 {
1764 	return buffer_len(&active_state->output) != 0;
1765 }
1766 
1767 /* Returns true if there is not too much data to write to the connection. */
1768 
1769 int
1770 packet_not_very_much_data_to_write(void)
1771 {
1772 	if (active_state->interactive_mode)
1773 		return buffer_len(&active_state->output) < 16384;
1774 	else
1775 		return buffer_len(&active_state->output) < 128 * 1024;
1776 }
1777 
1778 static void
1779 packet_set_tos(int tos)
1780 {
1781 	if (!packet_connection_is_on_socket())
1782 		return;
1783 	switch (packet_connection_af()) {
1784 	case AF_INET:
1785 		debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1786 		if (setsockopt(active_state->connection_in,
1787 		    IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
1788 			error("setsockopt IP_TOS %d: %.100s:",
1789 			    tos, strerror(errno));
1790 		break;
1791 	case AF_INET6:
1792 		debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1793 		if (setsockopt(active_state->connection_in,
1794 		    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
1795 			error("setsockopt IPV6_TCLASS %d: %.100s:",
1796 			    tos, strerror(errno));
1797 		break;
1798 	}
1799 }
1800 
1801 /* Informs that the current session is interactive.  Sets IP flags for that. */
1802 
1803 void
1804 packet_set_interactive(int interactive, int qos_interactive, int qos_bulk)
1805 {
1806 	if (active_state->set_interactive_called)
1807 		return;
1808 	active_state->set_interactive_called = 1;
1809 
1810 	/* Record that we are in interactive mode. */
1811 	active_state->interactive_mode = interactive;
1812 
1813 	/* Only set socket options if using a socket.  */
1814 	if (!packet_connection_is_on_socket())
1815 		return;
1816 	set_nodelay(active_state->connection_in);
1817 	packet_set_tos(interactive ? qos_interactive : qos_bulk);
1818 }
1819 
1820 /* Returns true if the current connection is interactive. */
1821 
1822 int
1823 packet_is_interactive(void)
1824 {
1825 	return active_state->interactive_mode;
1826 }
1827 
1828 int
1829 packet_set_maxsize(u_int s)
1830 {
1831 	if (active_state->set_maxsize_called) {
1832 		logit("packet_set_maxsize: called twice: old %d new %d",
1833 		    active_state->max_packet_size, s);
1834 		return -1;
1835 	}
1836 	if (s < 4 * 1024 || s > 1024 * 1024) {
1837 		logit("packet_set_maxsize: bad size %d", s);
1838 		return -1;
1839 	}
1840 	active_state->set_maxsize_called = 1;
1841 	debug("packet_set_maxsize: setting to %d", s);
1842 	active_state->max_packet_size = s;
1843 	return s;
1844 }
1845 
1846 int
1847 packet_inc_alive_timeouts(void)
1848 {
1849 	return ++active_state->keep_alive_timeouts;
1850 }
1851 
1852 void
1853 packet_set_alive_timeouts(int ka)
1854 {
1855 	active_state->keep_alive_timeouts = ka;
1856 }
1857 
1858 u_int
1859 packet_get_maxsize(void)
1860 {
1861 	return active_state->max_packet_size;
1862 }
1863 
1864 /* roundup current message to pad bytes */
1865 void
1866 packet_add_padding(u_char pad)
1867 {
1868 	active_state->extra_pad = pad;
1869 }
1870 
1871 /*
1872  * 9.2.  Ignored Data Message
1873  *
1874  *   byte      SSH_MSG_IGNORE
1875  *   string    data
1876  *
1877  * All implementations MUST understand (and ignore) this message at any
1878  * time (after receiving the protocol version). No implementation is
1879  * required to send them. This message can be used as an additional
1880  * protection measure against advanced traffic analysis techniques.
1881  */
1882 void
1883 packet_send_ignore(int nbytes)
1884 {
1885 	u_int32_t rnd = 0;
1886 	int i;
1887 
1888 	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1889 	packet_put_int(nbytes);
1890 	for (i = 0; i < nbytes; i++) {
1891 		if (i % 4 == 0)
1892 			rnd = arc4random();
1893 		packet_put_char((u_char)rnd & 0xff);
1894 		rnd >>= 8;
1895 	}
1896 }
1897 
1898 #define MAX_PACKETS	(1U<<31)
1899 int
1900 packet_need_rekeying(void)
1901 {
1902 	if (datafellows & SSH_BUG_NOREKEY)
1903 		return 0;
1904 	return
1905 	    (active_state->p_send.packets > MAX_PACKETS) ||
1906 	    (active_state->p_read.packets > MAX_PACKETS) ||
1907 	    (active_state->max_blocks_out &&
1908 	        (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1909 	    (active_state->max_blocks_in &&
1910 	        (active_state->p_read.blocks > active_state->max_blocks_in));
1911 }
1912 
1913 void
1914 packet_set_rekey_limit(u_int32_t bytes)
1915 {
1916 	active_state->rekey_limit = bytes;
1917 }
1918 
1919 void
1920 packet_set_server(void)
1921 {
1922 	active_state->server_side = 1;
1923 }
1924 
1925 void
1926 packet_set_authenticated(void)
1927 {
1928 	active_state->after_authentication = 1;
1929 }
1930 
1931 void *
1932 packet_get_input(void)
1933 {
1934 	return (void *)&active_state->input;
1935 }
1936 
1937 void *
1938 packet_get_output(void)
1939 {
1940 	return (void *)&active_state->output;
1941 }
1942 
1943 void *
1944 packet_get_newkeys(int mode)
1945 {
1946 	return (void *)active_state->newkeys[mode];
1947 }
1948 
1949 /*
1950  * Save the state for the real connection, and use a separate state when
1951  * resuming a suspended connection.
1952  */
1953 void
1954 packet_backup_state(void)
1955 {
1956 	struct session_state *tmp;
1957 
1958 	close(active_state->connection_in);
1959 	active_state->connection_in = -1;
1960 	close(active_state->connection_out);
1961 	active_state->connection_out = -1;
1962 	if (backup_state)
1963 		tmp = backup_state;
1964 	else
1965 		tmp = alloc_session_state();
1966 	backup_state = active_state;
1967 	active_state = tmp;
1968 }
1969 
1970 /*
1971  * Swap in the old state when resuming a connecion.
1972  */
1973 void
1974 packet_restore_state(void)
1975 {
1976 	struct session_state *tmp;
1977 	void *buf;
1978 	u_int len;
1979 
1980 	tmp = backup_state;
1981 	backup_state = active_state;
1982 	active_state = tmp;
1983 	active_state->connection_in = backup_state->connection_in;
1984 	backup_state->connection_in = -1;
1985 	active_state->connection_out = backup_state->connection_out;
1986 	backup_state->connection_out = -1;
1987 	len = buffer_len(&backup_state->input);
1988 	if (len > 0) {
1989 		buf = buffer_ptr(&backup_state->input);
1990 		buffer_append(&active_state->input, buf, len);
1991 		buffer_clear(&backup_state->input);
1992 		add_recv_bytes(len);
1993 	}
1994 }
1995