xref: /openbsd-src/usr.bin/ssh/packet.c (revision 43003dfe3ad45d1698bed8a37f2b0f5b14f20d4f)
1 /* $OpenBSD: packet.c,v 1.166 2009/06/27 09:29:06 andreas 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, u_int32_t *packets,
391     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 /* returns 1 if connection is via ipv4 */
422 
423 int
424 packet_connection_is_ipv4(void)
425 {
426 	struct sockaddr_storage to;
427 	socklen_t tolen = sizeof(to);
428 
429 	memset(&to, 0, sizeof(to));
430 	if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
431 	    &tolen) < 0)
432 		return 0;
433 	if (to.ss_family != AF_INET)
434 		return 0;
435 	return 1;
436 }
437 
438 /* Sets the connection into non-blocking mode. */
439 
440 void
441 packet_set_nonblocking(void)
442 {
443 	/* Set the socket into non-blocking mode. */
444 	set_nonblock(active_state->connection_in);
445 
446 	if (active_state->connection_out != active_state->connection_in)
447 		set_nonblock(active_state->connection_out);
448 }
449 
450 /* Returns the socket used for reading. */
451 
452 int
453 packet_get_connection_in(void)
454 {
455 	return active_state->connection_in;
456 }
457 
458 /* Returns the descriptor used for writing. */
459 
460 int
461 packet_get_connection_out(void)
462 {
463 	return active_state->connection_out;
464 }
465 
466 /* Closes the connection and clears and frees internal data structures. */
467 
468 void
469 packet_close(void)
470 {
471 	if (!active_state->initialized)
472 		return;
473 	active_state->initialized = 0;
474 	if (active_state->connection_in == active_state->connection_out) {
475 		shutdown(active_state->connection_out, SHUT_RDWR);
476 		close(active_state->connection_out);
477 	} else {
478 		close(active_state->connection_in);
479 		close(active_state->connection_out);
480 	}
481 	buffer_free(&active_state->input);
482 	buffer_free(&active_state->output);
483 	buffer_free(&active_state->outgoing_packet);
484 	buffer_free(&active_state->incoming_packet);
485 	if (active_state->compression_buffer_ready) {
486 		buffer_free(&active_state->compression_buffer);
487 		buffer_compress_uninit();
488 	}
489 	cipher_cleanup(&active_state->send_context);
490 	cipher_cleanup(&active_state->receive_context);
491 }
492 
493 /* Sets remote side protocol flags. */
494 
495 void
496 packet_set_protocol_flags(u_int protocol_flags)
497 {
498 	active_state->remote_protocol_flags = protocol_flags;
499 }
500 
501 /* Returns the remote protocol flags set earlier by the above function. */
502 
503 u_int
504 packet_get_protocol_flags(void)
505 {
506 	return active_state->remote_protocol_flags;
507 }
508 
509 /*
510  * Starts packet compression from the next packet on in both directions.
511  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
512  */
513 
514 static void
515 packet_init_compression(void)
516 {
517 	if (active_state->compression_buffer_ready == 1)
518 		return;
519 	active_state->compression_buffer_ready = 1;
520 	buffer_init(&active_state->compression_buffer);
521 }
522 
523 void
524 packet_start_compression(int level)
525 {
526 	if (active_state->packet_compression && !compat20)
527 		fatal("Compression already enabled.");
528 	active_state->packet_compression = 1;
529 	packet_init_compression();
530 	buffer_compress_init_send(level);
531 	buffer_compress_init_recv();
532 }
533 
534 /*
535  * Causes any further packets to be encrypted using the given key.  The same
536  * key is used for both sending and reception.  However, both directions are
537  * encrypted independently of each other.
538  */
539 
540 void
541 packet_set_encryption_key(const u_char *key, u_int keylen,
542     int number)
543 {
544 	Cipher *cipher = cipher_by_number(number);
545 
546 	if (cipher == NULL)
547 		fatal("packet_set_encryption_key: unknown cipher number %d", number);
548 	if (keylen < 20)
549 		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
550 	if (keylen > SSH_SESSION_KEY_LENGTH)
551 		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
552 	memcpy(active_state->ssh1_key, key, keylen);
553 	active_state->ssh1_keylen = keylen;
554 	cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
555 	    0, CIPHER_ENCRYPT);
556 	cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
557 	    0, CIPHER_DECRYPT);
558 }
559 
560 u_int
561 packet_get_encryption_key(u_char *key)
562 {
563 	if (key == NULL)
564 		return (active_state->ssh1_keylen);
565 	memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
566 	return (active_state->ssh1_keylen);
567 }
568 
569 /* Start constructing a packet to send. */
570 void
571 packet_start(u_char type)
572 {
573 	u_char buf[9];
574 	int len;
575 
576 	DBG(debug("packet_start[%d]", type));
577 	len = compat20 ? 6 : 9;
578 	memset(buf, 0, len - 1);
579 	buf[len - 1] = type;
580 	buffer_clear(&active_state->outgoing_packet);
581 	buffer_append(&active_state->outgoing_packet, buf, len);
582 }
583 
584 /* Append payload. */
585 void
586 packet_put_char(int value)
587 {
588 	char ch = value;
589 
590 	buffer_append(&active_state->outgoing_packet, &ch, 1);
591 }
592 
593 void
594 packet_put_int(u_int value)
595 {
596 	buffer_put_int(&active_state->outgoing_packet, value);
597 }
598 
599 void
600 packet_put_int64(u_int64_t value)
601 {
602 	buffer_put_int64(&active_state->outgoing_packet, value);
603 }
604 
605 void
606 packet_put_string(const void *buf, u_int len)
607 {
608 	buffer_put_string(&active_state->outgoing_packet, buf, len);
609 }
610 
611 void
612 packet_put_cstring(const char *str)
613 {
614 	buffer_put_cstring(&active_state->outgoing_packet, str);
615 }
616 
617 void
618 packet_put_raw(const void *buf, u_int len)
619 {
620 	buffer_append(&active_state->outgoing_packet, buf, len);
621 }
622 
623 void
624 packet_put_bignum(BIGNUM * value)
625 {
626 	buffer_put_bignum(&active_state->outgoing_packet, value);
627 }
628 
629 void
630 packet_put_bignum2(BIGNUM * value)
631 {
632 	buffer_put_bignum2(&active_state->outgoing_packet, value);
633 }
634 
635 /*
636  * Finalizes and sends the packet.  If the encryption key has been set,
637  * encrypts the packet before sending.
638  */
639 
640 static void
641 packet_send1(void)
642 {
643 	u_char buf[8], *cp;
644 	int i, padding, len;
645 	u_int checksum;
646 	u_int32_t rnd = 0;
647 
648 	/*
649 	 * If using packet compression, compress the payload of the outgoing
650 	 * packet.
651 	 */
652 	if (active_state->packet_compression) {
653 		buffer_clear(&active_state->compression_buffer);
654 		/* Skip padding. */
655 		buffer_consume(&active_state->outgoing_packet, 8);
656 		/* padding */
657 		buffer_append(&active_state->compression_buffer,
658 		    "\0\0\0\0\0\0\0\0", 8);
659 		buffer_compress(&active_state->outgoing_packet,
660 		    &active_state->compression_buffer);
661 		buffer_clear(&active_state->outgoing_packet);
662 		buffer_append(&active_state->outgoing_packet,
663 		    buffer_ptr(&active_state->compression_buffer),
664 		    buffer_len(&active_state->compression_buffer));
665 	}
666 	/* Compute packet length without padding (add checksum, remove padding). */
667 	len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
668 
669 	/* Insert padding. Initialized to zero in packet_start1() */
670 	padding = 8 - len % 8;
671 	if (!active_state->send_context.plaintext) {
672 		cp = buffer_ptr(&active_state->outgoing_packet);
673 		for (i = 0; i < padding; i++) {
674 			if (i % 4 == 0)
675 				rnd = arc4random();
676 			cp[7 - i] = rnd & 0xff;
677 			rnd >>= 8;
678 		}
679 	}
680 	buffer_consume(&active_state->outgoing_packet, 8 - padding);
681 
682 	/* Add check bytes. */
683 	checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
684 	    buffer_len(&active_state->outgoing_packet));
685 	put_u32(buf, checksum);
686 	buffer_append(&active_state->outgoing_packet, buf, 4);
687 
688 #ifdef PACKET_DEBUG
689 	fprintf(stderr, "packet_send plain: ");
690 	buffer_dump(&active_state->outgoing_packet);
691 #endif
692 
693 	/* Append to output. */
694 	put_u32(buf, len);
695 	buffer_append(&active_state->output, buf, 4);
696 	cp = buffer_append_space(&active_state->output,
697 	    buffer_len(&active_state->outgoing_packet));
698 	cipher_crypt(&active_state->send_context, cp,
699 	    buffer_ptr(&active_state->outgoing_packet),
700 	    buffer_len(&active_state->outgoing_packet));
701 
702 #ifdef PACKET_DEBUG
703 	fprintf(stderr, "encrypted: ");
704 	buffer_dump(&active_state->output);
705 #endif
706 	active_state->p_send.packets++;
707 	active_state->p_send.bytes += len +
708 	    buffer_len(&active_state->outgoing_packet);
709 	buffer_clear(&active_state->outgoing_packet);
710 
711 	/*
712 	 * Note that the packet is now only buffered in output.  It won't be
713 	 * actually sent until packet_write_wait or packet_write_poll is
714 	 * called.
715 	 */
716 }
717 
718 void
719 set_newkeys(int mode)
720 {
721 	Enc *enc;
722 	Mac *mac;
723 	Comp *comp;
724 	CipherContext *cc;
725 	u_int64_t *max_blocks;
726 	int crypt_type;
727 
728 	debug2("set_newkeys: mode %d", mode);
729 
730 	if (mode == MODE_OUT) {
731 		cc = &active_state->send_context;
732 		crypt_type = CIPHER_ENCRYPT;
733 		active_state->p_send.packets = active_state->p_send.blocks = 0;
734 		max_blocks = &active_state->max_blocks_out;
735 	} else {
736 		cc = &active_state->receive_context;
737 		crypt_type = CIPHER_DECRYPT;
738 		active_state->p_read.packets = active_state->p_read.blocks = 0;
739 		max_blocks = &active_state->max_blocks_in;
740 	}
741 	if (active_state->newkeys[mode] != NULL) {
742 		debug("set_newkeys: rekeying");
743 		cipher_cleanup(cc);
744 		enc  = &active_state->newkeys[mode]->enc;
745 		mac  = &active_state->newkeys[mode]->mac;
746 		comp = &active_state->newkeys[mode]->comp;
747 		mac_clear(mac);
748 		xfree(enc->name);
749 		xfree(enc->iv);
750 		xfree(enc->key);
751 		xfree(mac->name);
752 		xfree(mac->key);
753 		xfree(comp->name);
754 		xfree(active_state->newkeys[mode]);
755 	}
756 	active_state->newkeys[mode] = kex_get_newkeys(mode);
757 	if (active_state->newkeys[mode] == NULL)
758 		fatal("newkeys: no keys for mode %d", mode);
759 	enc  = &active_state->newkeys[mode]->enc;
760 	mac  = &active_state->newkeys[mode]->mac;
761 	comp = &active_state->newkeys[mode]->comp;
762 	if (mac_init(mac) == 0)
763 		mac->enabled = 1;
764 	DBG(debug("cipher_init_context: %d", mode));
765 	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
766 	    enc->iv, enc->block_size, crypt_type);
767 	/* Deleting the keys does not gain extra security */
768 	/* memset(enc->iv,  0, enc->block_size);
769 	   memset(enc->key, 0, enc->key_len);
770 	   memset(mac->key, 0, mac->key_len); */
771 	if ((comp->type == COMP_ZLIB ||
772 	    (comp->type == COMP_DELAYED &&
773 	     active_state->after_authentication)) && comp->enabled == 0) {
774 		packet_init_compression();
775 		if (mode == MODE_OUT)
776 			buffer_compress_init_send(6);
777 		else
778 			buffer_compress_init_recv();
779 		comp->enabled = 1;
780 	}
781 	/*
782 	 * The 2^(blocksize*2) limit is too expensive for 3DES,
783 	 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
784 	 */
785 	if (enc->block_size >= 16)
786 		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
787 	else
788 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
789 	if (active_state->rekey_limit)
790 		*max_blocks = MIN(*max_blocks,
791 		    active_state->rekey_limit / enc->block_size);
792 }
793 
794 /*
795  * Delayed compression for SSH2 is enabled after authentication:
796  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
797  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
798  */
799 static void
800 packet_enable_delayed_compress(void)
801 {
802 	Comp *comp = NULL;
803 	int mode;
804 
805 	/*
806 	 * Remember that we are past the authentication step, so rekeying
807 	 * with COMP_DELAYED will turn on compression immediately.
808 	 */
809 	active_state->after_authentication = 1;
810 	for (mode = 0; mode < MODE_MAX; mode++) {
811 		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
812 		if (active_state->newkeys[mode] == NULL)
813 			continue;
814 		comp = &active_state->newkeys[mode]->comp;
815 		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
816 			packet_init_compression();
817 			if (mode == MODE_OUT)
818 				buffer_compress_init_send(6);
819 			else
820 				buffer_compress_init_recv();
821 			comp->enabled = 1;
822 		}
823 	}
824 }
825 
826 /*
827  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
828  */
829 static void
830 packet_send2_wrapped(void)
831 {
832 	u_char type, *cp, *macbuf = NULL;
833 	u_char padlen, pad;
834 	u_int packet_length = 0;
835 	u_int i, len;
836 	u_int32_t rnd = 0;
837 	Enc *enc   = NULL;
838 	Mac *mac   = NULL;
839 	Comp *comp = NULL;
840 	int block_size;
841 
842 	if (active_state->newkeys[MODE_OUT] != NULL) {
843 		enc  = &active_state->newkeys[MODE_OUT]->enc;
844 		mac  = &active_state->newkeys[MODE_OUT]->mac;
845 		comp = &active_state->newkeys[MODE_OUT]->comp;
846 	}
847 	block_size = enc ? enc->block_size : 8;
848 
849 	cp = buffer_ptr(&active_state->outgoing_packet);
850 	type = cp[5];
851 
852 #ifdef PACKET_DEBUG
853 	fprintf(stderr, "plain:     ");
854 	buffer_dump(&active_state->outgoing_packet);
855 #endif
856 
857 	if (comp && comp->enabled) {
858 		len = buffer_len(&active_state->outgoing_packet);
859 		/* skip header, compress only payload */
860 		buffer_consume(&active_state->outgoing_packet, 5);
861 		buffer_clear(&active_state->compression_buffer);
862 		buffer_compress(&active_state->outgoing_packet,
863 		    &active_state->compression_buffer);
864 		buffer_clear(&active_state->outgoing_packet);
865 		buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
866 		buffer_append(&active_state->outgoing_packet,
867 		    buffer_ptr(&active_state->compression_buffer),
868 		    buffer_len(&active_state->compression_buffer));
869 		DBG(debug("compression: raw %d compressed %d", len,
870 		    buffer_len(&active_state->outgoing_packet)));
871 	}
872 
873 	/* sizeof (packet_len + pad_len + payload) */
874 	len = buffer_len(&active_state->outgoing_packet);
875 
876 	/*
877 	 * calc size of padding, alloc space, get random data,
878 	 * minimum padding is 4 bytes
879 	 */
880 	padlen = block_size - (len % block_size);
881 	if (padlen < 4)
882 		padlen += block_size;
883 	if (active_state->extra_pad) {
884 		/* will wrap if extra_pad+padlen > 255 */
885 		active_state->extra_pad =
886 		    roundup(active_state->extra_pad, block_size);
887 		pad = active_state->extra_pad -
888 		    ((len + padlen) % active_state->extra_pad);
889 		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
890 		    pad, len, padlen, active_state->extra_pad);
891 		padlen += pad;
892 		active_state->extra_pad = 0;
893 	}
894 	cp = buffer_append_space(&active_state->outgoing_packet, padlen);
895 	if (enc && !active_state->send_context.plaintext) {
896 		/* random padding */
897 		for (i = 0; i < padlen; i++) {
898 			if (i % 4 == 0)
899 				rnd = arc4random();
900 			cp[i] = rnd & 0xff;
901 			rnd >>= 8;
902 		}
903 	} else {
904 		/* clear padding */
905 		memset(cp, 0, padlen);
906 	}
907 	/* packet_length includes payload, padding and padding length field */
908 	packet_length = buffer_len(&active_state->outgoing_packet) - 4;
909 	cp = buffer_ptr(&active_state->outgoing_packet);
910 	put_u32(cp, packet_length);
911 	cp[4] = padlen;
912 	DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
913 
914 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
915 	if (mac && mac->enabled) {
916 		macbuf = mac_compute(mac, active_state->p_send.seqnr,
917 		    buffer_ptr(&active_state->outgoing_packet),
918 		    buffer_len(&active_state->outgoing_packet));
919 		DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
920 	}
921 	/* encrypt packet and append to output buffer. */
922 	cp = buffer_append_space(&active_state->output,
923 	    buffer_len(&active_state->outgoing_packet));
924 	cipher_crypt(&active_state->send_context, cp,
925 	    buffer_ptr(&active_state->outgoing_packet),
926 	    buffer_len(&active_state->outgoing_packet));
927 	/* append unencrypted MAC */
928 	if (mac && mac->enabled)
929 		buffer_append(&active_state->output, macbuf, mac->mac_len);
930 #ifdef PACKET_DEBUG
931 	fprintf(stderr, "encrypted: ");
932 	buffer_dump(&active_state->output);
933 #endif
934 	/* increment sequence number for outgoing packets */
935 	if (++active_state->p_send.seqnr == 0)
936 		logit("outgoing seqnr wraps around");
937 	if (++active_state->p_send.packets == 0)
938 		if (!(datafellows & SSH_BUG_NOREKEY))
939 			fatal("XXX too many packets with same key");
940 	active_state->p_send.blocks += (packet_length + 4) / block_size;
941 	active_state->p_send.bytes += packet_length + 4;
942 	buffer_clear(&active_state->outgoing_packet);
943 
944 	if (type == SSH2_MSG_NEWKEYS)
945 		set_newkeys(MODE_OUT);
946 	else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
947 		packet_enable_delayed_compress();
948 }
949 
950 static void
951 packet_send2(void)
952 {
953 	struct packet *p;
954 	u_char type, *cp;
955 
956 	cp = buffer_ptr(&active_state->outgoing_packet);
957 	type = cp[5];
958 
959 	/* during rekeying we can only send key exchange messages */
960 	if (active_state->rekeying) {
961 		if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
962 		    (type <= SSH2_MSG_TRANSPORT_MAX))) {
963 			debug("enqueue packet: %u", type);
964 			p = xmalloc(sizeof(*p));
965 			p->type = type;
966 			memcpy(&p->payload, &active_state->outgoing_packet,
967 			    sizeof(Buffer));
968 			buffer_init(&active_state->outgoing_packet);
969 			TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
970 			return;
971 		}
972 	}
973 
974 	/* rekeying starts with sending KEXINIT */
975 	if (type == SSH2_MSG_KEXINIT)
976 		active_state->rekeying = 1;
977 
978 	packet_send2_wrapped();
979 
980 	/* after a NEWKEYS message we can send the complete queue */
981 	if (type == SSH2_MSG_NEWKEYS) {
982 		active_state->rekeying = 0;
983 		while ((p = TAILQ_FIRST(&active_state->outgoing))) {
984 			type = p->type;
985 			debug("dequeue packet: %u", type);
986 			buffer_free(&active_state->outgoing_packet);
987 			memcpy(&active_state->outgoing_packet, &p->payload,
988 			    sizeof(Buffer));
989 			TAILQ_REMOVE(&active_state->outgoing, p, next);
990 			xfree(p);
991 			packet_send2_wrapped();
992 		}
993 	}
994 }
995 
996 void
997 packet_send(void)
998 {
999 	if (compat20)
1000 		packet_send2();
1001 	else
1002 		packet_send1();
1003 	DBG(debug("packet_send done"));
1004 }
1005 
1006 /*
1007  * Waits until a packet has been received, and returns its type.  Note that
1008  * no other data is processed until this returns, so this function should not
1009  * be used during the interactive session.
1010  */
1011 
1012 int
1013 packet_read_seqnr(u_int32_t *seqnr_p)
1014 {
1015 	int type, len, ret, ms_remain, cont;
1016 	fd_set *setp;
1017 	char buf[8192];
1018 	struct timeval timeout, start, *timeoutp = NULL;
1019 
1020 	DBG(debug("packet_read()"));
1021 
1022 	setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
1023 	    NFDBITS), sizeof(fd_mask));
1024 
1025 	/* Since we are blocking, ensure that all written packets have been sent. */
1026 	packet_write_wait();
1027 
1028 	/* Stay in the loop until we have received a complete packet. */
1029 	for (;;) {
1030 		/* Try to read a packet from the buffer. */
1031 		type = packet_read_poll_seqnr(seqnr_p);
1032 		if (!compat20 && (
1033 		    type == SSH_SMSG_SUCCESS
1034 		    || type == SSH_SMSG_FAILURE
1035 		    || type == SSH_CMSG_EOF
1036 		    || type == SSH_CMSG_EXIT_CONFIRMATION))
1037 			packet_check_eom();
1038 		/* If we got a packet, return it. */
1039 		if (type != SSH_MSG_NONE) {
1040 			xfree(setp);
1041 			return type;
1042 		}
1043 		/*
1044 		 * Otherwise, wait for some data to arrive, add it to the
1045 		 * buffer, and try again.
1046 		 */
1047 		memset(setp, 0, howmany(active_state->connection_in + 1,
1048 		    NFDBITS) * sizeof(fd_mask));
1049 		FD_SET(active_state->connection_in, setp);
1050 
1051 		if (active_state->packet_timeout_ms > 0) {
1052 			ms_remain = active_state->packet_timeout_ms;
1053 			timeoutp = &timeout;
1054 		}
1055 		/* Wait for some data to arrive. */
1056 		for (;;) {
1057 			if (active_state->packet_timeout_ms != -1) {
1058 				ms_to_timeval(&timeout, ms_remain);
1059 				gettimeofday(&start, NULL);
1060 			}
1061 			if ((ret = select(active_state->connection_in + 1, setp,
1062 			    NULL, NULL, timeoutp)) >= 0)
1063 				break;
1064 			if (errno != EAGAIN && errno != EINTR)
1065 				break;
1066 			if (active_state->packet_timeout_ms == -1)
1067 				continue;
1068 			ms_subtract_diff(&start, &ms_remain);
1069 			if (ms_remain <= 0) {
1070 				ret = 0;
1071 				break;
1072 			}
1073 		}
1074 		if (ret == 0) {
1075 			logit("Connection to %.200s timed out while "
1076 			    "waiting to read", get_remote_ipaddr());
1077 			cleanup_exit(255);
1078 		}
1079 		/* Read data from the socket. */
1080 		do {
1081 			cont = 0;
1082 			len = roaming_read(active_state->connection_in, buf,
1083 			    sizeof(buf), &cont);
1084 		} while (len == 0 && cont);
1085 		if (len == 0) {
1086 			logit("Connection closed by %.200s", get_remote_ipaddr());
1087 			cleanup_exit(255);
1088 		}
1089 		if (len < 0)
1090 			fatal("Read from socket failed: %.100s", strerror(errno));
1091 		/* Append it to the buffer. */
1092 		packet_process_incoming(buf, len);
1093 	}
1094 	/* NOTREACHED */
1095 }
1096 
1097 int
1098 packet_read(void)
1099 {
1100 	return packet_read_seqnr(NULL);
1101 }
1102 
1103 /*
1104  * Waits until a packet has been received, verifies that its type matches
1105  * that given, and gives a fatal error and exits if there is a mismatch.
1106  */
1107 
1108 void
1109 packet_read_expect(int expected_type)
1110 {
1111 	int type;
1112 
1113 	type = packet_read();
1114 	if (type != expected_type)
1115 		packet_disconnect("Protocol error: expected packet type %d, got %d",
1116 		    expected_type, type);
1117 }
1118 
1119 /* Checks if a full packet is available in the data received so far via
1120  * packet_process_incoming.  If so, reads the packet; otherwise returns
1121  * SSH_MSG_NONE.  This does not wait for data from the connection.
1122  *
1123  * SSH_MSG_DISCONNECT is handled specially here.  Also,
1124  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
1125  * to higher levels.
1126  */
1127 
1128 static int
1129 packet_read_poll1(void)
1130 {
1131 	u_int len, padded_len;
1132 	u_char *cp, type;
1133 	u_int checksum, stored_checksum;
1134 
1135 	/* Check if input size is less than minimum packet size. */
1136 	if (buffer_len(&active_state->input) < 4 + 8)
1137 		return SSH_MSG_NONE;
1138 	/* Get length of incoming packet. */
1139 	cp = buffer_ptr(&active_state->input);
1140 	len = get_u32(cp);
1141 	if (len < 1 + 2 + 2 || len > 256 * 1024)
1142 		packet_disconnect("Bad packet length %u.", len);
1143 	padded_len = (len + 8) & ~7;
1144 
1145 	/* Check if the packet has been entirely received. */
1146 	if (buffer_len(&active_state->input) < 4 + padded_len)
1147 		return SSH_MSG_NONE;
1148 
1149 	/* The entire packet is in buffer. */
1150 
1151 	/* Consume packet length. */
1152 	buffer_consume(&active_state->input, 4);
1153 
1154 	/*
1155 	 * Cryptographic attack detector for ssh
1156 	 * (C)1998 CORE-SDI, Buenos Aires Argentina
1157 	 * Ariel Futoransky(futo@core-sdi.com)
1158 	 */
1159 	if (!active_state->receive_context.plaintext) {
1160 		switch (detect_attack(buffer_ptr(&active_state->input),
1161 		    padded_len)) {
1162 		case DEATTACK_DETECTED:
1163 			packet_disconnect("crc32 compensation attack: "
1164 			    "network attack detected");
1165 		case DEATTACK_DOS_DETECTED:
1166 			packet_disconnect("deattack denial of "
1167 			    "service detected");
1168 		}
1169 	}
1170 
1171 	/* Decrypt data to incoming_packet. */
1172 	buffer_clear(&active_state->incoming_packet);
1173 	cp = buffer_append_space(&active_state->incoming_packet, padded_len);
1174 	cipher_crypt(&active_state->receive_context, cp,
1175 	    buffer_ptr(&active_state->input), padded_len);
1176 
1177 	buffer_consume(&active_state->input, padded_len);
1178 
1179 #ifdef PACKET_DEBUG
1180 	fprintf(stderr, "read_poll plain: ");
1181 	buffer_dump(&active_state->incoming_packet);
1182 #endif
1183 
1184 	/* Compute packet checksum. */
1185 	checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
1186 	    buffer_len(&active_state->incoming_packet) - 4);
1187 
1188 	/* Skip padding. */
1189 	buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1190 
1191 	/* Test check bytes. */
1192 	if (len != buffer_len(&active_state->incoming_packet))
1193 		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1194 		    len, buffer_len(&active_state->incoming_packet));
1195 
1196 	cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1197 	stored_checksum = get_u32(cp);
1198 	if (checksum != stored_checksum)
1199 		packet_disconnect("Corrupted check bytes on input.");
1200 	buffer_consume_end(&active_state->incoming_packet, 4);
1201 
1202 	if (active_state->packet_compression) {
1203 		buffer_clear(&active_state->compression_buffer);
1204 		buffer_uncompress(&active_state->incoming_packet,
1205 		    &active_state->compression_buffer);
1206 		buffer_clear(&active_state->incoming_packet);
1207 		buffer_append(&active_state->incoming_packet,
1208 		    buffer_ptr(&active_state->compression_buffer),
1209 		    buffer_len(&active_state->compression_buffer));
1210 	}
1211 	active_state->p_read.packets++;
1212 	active_state->p_read.bytes += padded_len + 4;
1213 	type = buffer_get_char(&active_state->incoming_packet);
1214 	if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
1215 		packet_disconnect("Invalid ssh1 packet type: %d", type);
1216 	return type;
1217 }
1218 
1219 static int
1220 packet_read_poll2(u_int32_t *seqnr_p)
1221 {
1222 	u_int padlen, need;
1223 	u_char *macbuf, *cp, type;
1224 	u_int maclen, block_size;
1225 	Enc *enc   = NULL;
1226 	Mac *mac   = NULL;
1227 	Comp *comp = NULL;
1228 
1229 	if (active_state->packet_discard)
1230 		return SSH_MSG_NONE;
1231 
1232 	if (active_state->newkeys[MODE_IN] != NULL) {
1233 		enc  = &active_state->newkeys[MODE_IN]->enc;
1234 		mac  = &active_state->newkeys[MODE_IN]->mac;
1235 		comp = &active_state->newkeys[MODE_IN]->comp;
1236 	}
1237 	maclen = mac && mac->enabled ? mac->mac_len : 0;
1238 	block_size = enc ? enc->block_size : 8;
1239 
1240 	if (active_state->packlen == 0) {
1241 		/*
1242 		 * check if input size is less than the cipher block size,
1243 		 * decrypt first block and extract length of incoming packet
1244 		 */
1245 		if (buffer_len(&active_state->input) < block_size)
1246 			return SSH_MSG_NONE;
1247 		buffer_clear(&active_state->incoming_packet);
1248 		cp = buffer_append_space(&active_state->incoming_packet,
1249 		    block_size);
1250 		cipher_crypt(&active_state->receive_context, cp,
1251 		    buffer_ptr(&active_state->input), block_size);
1252 		cp = buffer_ptr(&active_state->incoming_packet);
1253 		active_state->packlen = get_u32(cp);
1254 		if (active_state->packlen < 1 + 4 ||
1255 		    active_state->packlen > PACKET_MAX_SIZE) {
1256 #ifdef PACKET_DEBUG
1257 			buffer_dump(&active_state->incoming_packet);
1258 #endif
1259 			logit("Bad packet length %u.", active_state->packlen);
1260 			packet_start_discard(enc, mac, active_state->packlen,
1261 			    PACKET_MAX_SIZE);
1262 			return SSH_MSG_NONE;
1263 		}
1264 		DBG(debug("input: packet len %u", active_state->packlen+4));
1265 		buffer_consume(&active_state->input, block_size);
1266 	}
1267 	/* we have a partial packet of block_size bytes */
1268 	need = 4 + active_state->packlen - block_size;
1269 	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
1270 	    need, maclen));
1271 	if (need % block_size != 0) {
1272 		logit("padding error: need %d block %d mod %d",
1273 		    need, block_size, need % block_size);
1274 		packet_start_discard(enc, mac, active_state->packlen,
1275 		    PACKET_MAX_SIZE - block_size);
1276 		return SSH_MSG_NONE;
1277 	}
1278 	/*
1279 	 * check if the entire packet has been received and
1280 	 * decrypt into incoming_packet
1281 	 */
1282 	if (buffer_len(&active_state->input) < need + maclen)
1283 		return SSH_MSG_NONE;
1284 #ifdef PACKET_DEBUG
1285 	fprintf(stderr, "read_poll enc/full: ");
1286 	buffer_dump(&active_state->input);
1287 #endif
1288 	cp = buffer_append_space(&active_state->incoming_packet, need);
1289 	cipher_crypt(&active_state->receive_context, cp,
1290 	    buffer_ptr(&active_state->input), need);
1291 	buffer_consume(&active_state->input, need);
1292 	/*
1293 	 * compute MAC over seqnr and packet,
1294 	 * increment sequence number for incoming packet
1295 	 */
1296 	if (mac && mac->enabled) {
1297 		macbuf = mac_compute(mac, active_state->p_read.seqnr,
1298 		    buffer_ptr(&active_state->incoming_packet),
1299 		    buffer_len(&active_state->incoming_packet));
1300 		if (memcmp(macbuf, buffer_ptr(&active_state->input),
1301 		    mac->mac_len) != 0) {
1302 			logit("Corrupted MAC on input.");
1303 			if (need > PACKET_MAX_SIZE)
1304 				fatal("internal error need %d", need);
1305 			packet_start_discard(enc, mac, active_state->packlen,
1306 			    PACKET_MAX_SIZE - need);
1307 			return SSH_MSG_NONE;
1308 		}
1309 
1310 		DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
1311 		buffer_consume(&active_state->input, mac->mac_len);
1312 	}
1313 	/* XXX now it's safe to use fatal/packet_disconnect */
1314 	if (seqnr_p != NULL)
1315 		*seqnr_p = active_state->p_read.seqnr;
1316 	if (++active_state->p_read.seqnr == 0)
1317 		logit("incoming seqnr wraps around");
1318 	if (++active_state->p_read.packets == 0)
1319 		if (!(datafellows & SSH_BUG_NOREKEY))
1320 			fatal("XXX too many packets with same key");
1321 	active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
1322 	active_state->p_read.bytes += active_state->packlen + 4;
1323 
1324 	/* get padlen */
1325 	cp = buffer_ptr(&active_state->incoming_packet);
1326 	padlen = cp[4];
1327 	DBG(debug("input: padlen %d", padlen));
1328 	if (padlen < 4)
1329 		packet_disconnect("Corrupted padlen %d on input.", padlen);
1330 
1331 	/* skip packet size + padlen, discard padding */
1332 	buffer_consume(&active_state->incoming_packet, 4 + 1);
1333 	buffer_consume_end(&active_state->incoming_packet, padlen);
1334 
1335 	DBG(debug("input: len before de-compress %d",
1336 	    buffer_len(&active_state->incoming_packet)));
1337 	if (comp && comp->enabled) {
1338 		buffer_clear(&active_state->compression_buffer);
1339 		buffer_uncompress(&active_state->incoming_packet,
1340 		    &active_state->compression_buffer);
1341 		buffer_clear(&active_state->incoming_packet);
1342 		buffer_append(&active_state->incoming_packet,
1343 		    buffer_ptr(&active_state->compression_buffer),
1344 		    buffer_len(&active_state->compression_buffer));
1345 		DBG(debug("input: len after de-compress %d",
1346 		    buffer_len(&active_state->incoming_packet)));
1347 	}
1348 	/*
1349 	 * get packet type, implies consume.
1350 	 * return length of payload (without type field)
1351 	 */
1352 	type = buffer_get_char(&active_state->incoming_packet);
1353 	if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
1354 		packet_disconnect("Invalid ssh2 packet type: %d", type);
1355 	if (type == SSH2_MSG_NEWKEYS)
1356 		set_newkeys(MODE_IN);
1357 	else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
1358 	    !active_state->server_side)
1359 		packet_enable_delayed_compress();
1360 #ifdef PACKET_DEBUG
1361 	fprintf(stderr, "read/plain[%d]:\r\n", type);
1362 	buffer_dump(&active_state->incoming_packet);
1363 #endif
1364 	/* reset for next packet */
1365 	active_state->packlen = 0;
1366 	return type;
1367 }
1368 
1369 int
1370 packet_read_poll_seqnr(u_int32_t *seqnr_p)
1371 {
1372 	u_int reason, seqnr;
1373 	u_char type;
1374 	char *msg;
1375 
1376 	for (;;) {
1377 		if (compat20) {
1378 			type = packet_read_poll2(seqnr_p);
1379 			if (type) {
1380 				active_state->keep_alive_timeouts = 0;
1381 				DBG(debug("received packet type %d", type));
1382 			}
1383 			switch (type) {
1384 			case SSH2_MSG_IGNORE:
1385 				debug3("Received SSH2_MSG_IGNORE");
1386 				break;
1387 			case SSH2_MSG_DEBUG:
1388 				packet_get_char();
1389 				msg = packet_get_string(NULL);
1390 				debug("Remote: %.900s", msg);
1391 				xfree(msg);
1392 				msg = packet_get_string(NULL);
1393 				xfree(msg);
1394 				break;
1395 			case SSH2_MSG_DISCONNECT:
1396 				reason = packet_get_int();
1397 				msg = packet_get_string(NULL);
1398 				logit("Received disconnect from %s: %u: %.400s",
1399 				    get_remote_ipaddr(), reason, msg);
1400 				xfree(msg);
1401 				cleanup_exit(255);
1402 				break;
1403 			case SSH2_MSG_UNIMPLEMENTED:
1404 				seqnr = packet_get_int();
1405 				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1406 				    seqnr);
1407 				break;
1408 			default:
1409 				return type;
1410 			}
1411 		} else {
1412 			type = packet_read_poll1();
1413 			switch (type) {
1414 			case SSH_MSG_IGNORE:
1415 				break;
1416 			case SSH_MSG_DEBUG:
1417 				msg = packet_get_string(NULL);
1418 				debug("Remote: %.900s", msg);
1419 				xfree(msg);
1420 				break;
1421 			case SSH_MSG_DISCONNECT:
1422 				msg = packet_get_string(NULL);
1423 				logit("Received disconnect from %s: %.400s",
1424 				    get_remote_ipaddr(), msg);
1425 				cleanup_exit(255);
1426 				break;
1427 			default:
1428 				if (type)
1429 					DBG(debug("received packet type %d", type));
1430 				return type;
1431 			}
1432 		}
1433 	}
1434 }
1435 
1436 int
1437 packet_read_poll(void)
1438 {
1439 	return packet_read_poll_seqnr(NULL);
1440 }
1441 
1442 /*
1443  * Buffers the given amount of input characters.  This is intended to be used
1444  * together with packet_read_poll.
1445  */
1446 
1447 void
1448 packet_process_incoming(const char *buf, u_int len)
1449 {
1450 	if (active_state->packet_discard) {
1451 		active_state->keep_alive_timeouts = 0; /* ?? */
1452 		if (len >= active_state->packet_discard)
1453 			packet_stop_discard();
1454 		active_state->packet_discard -= len;
1455 		return;
1456 	}
1457 	buffer_append(&active_state->input, buf, len);
1458 }
1459 
1460 /* Returns a character from the packet. */
1461 
1462 u_int
1463 packet_get_char(void)
1464 {
1465 	char ch;
1466 
1467 	buffer_get(&active_state->incoming_packet, &ch, 1);
1468 	return (u_char) ch;
1469 }
1470 
1471 /* Returns an integer from the packet data. */
1472 
1473 u_int
1474 packet_get_int(void)
1475 {
1476 	return buffer_get_int(&active_state->incoming_packet);
1477 }
1478 
1479 /* Returns an 64 bit integer from the packet data. */
1480 
1481 u_int64_t
1482 packet_get_int64(void)
1483 {
1484 	return buffer_get_int64(&active_state->incoming_packet);
1485 }
1486 
1487 /*
1488  * Returns an arbitrary precision integer from the packet data.  The integer
1489  * must have been initialized before this call.
1490  */
1491 
1492 void
1493 packet_get_bignum(BIGNUM * value)
1494 {
1495 	buffer_get_bignum(&active_state->incoming_packet, value);
1496 }
1497 
1498 void
1499 packet_get_bignum2(BIGNUM * value)
1500 {
1501 	buffer_get_bignum2(&active_state->incoming_packet, value);
1502 }
1503 
1504 void *
1505 packet_get_raw(u_int *length_ptr)
1506 {
1507 	u_int bytes = buffer_len(&active_state->incoming_packet);
1508 
1509 	if (length_ptr != NULL)
1510 		*length_ptr = bytes;
1511 	return buffer_ptr(&active_state->incoming_packet);
1512 }
1513 
1514 int
1515 packet_remaining(void)
1516 {
1517 	return buffer_len(&active_state->incoming_packet);
1518 }
1519 
1520 /*
1521  * Returns a string from the packet data.  The string is allocated using
1522  * xmalloc; it is the responsibility of the calling program to free it when
1523  * no longer needed.  The length_ptr argument may be NULL, or point to an
1524  * integer into which the length of the string is stored.
1525  */
1526 
1527 void *
1528 packet_get_string(u_int *length_ptr)
1529 {
1530 	return buffer_get_string(&active_state->incoming_packet, length_ptr);
1531 }
1532 
1533 void *
1534 packet_get_string_ptr(u_int *length_ptr)
1535 {
1536 	return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1537 }
1538 
1539 /*
1540  * Sends a diagnostic message from the server to the client.  This message
1541  * can be sent at any time (but not while constructing another message). The
1542  * message is printed immediately, but only if the client is being executed
1543  * in verbose mode.  These messages are primarily intended to ease debugging
1544  * authentication problems.   The length of the formatted message must not
1545  * exceed 1024 bytes.  This will automatically call packet_write_wait.
1546  */
1547 
1548 void
1549 packet_send_debug(const char *fmt,...)
1550 {
1551 	char buf[1024];
1552 	va_list args;
1553 
1554 	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1555 		return;
1556 
1557 	va_start(args, fmt);
1558 	vsnprintf(buf, sizeof(buf), fmt, args);
1559 	va_end(args);
1560 
1561 	if (compat20) {
1562 		packet_start(SSH2_MSG_DEBUG);
1563 		packet_put_char(0);	/* bool: always display */
1564 		packet_put_cstring(buf);
1565 		packet_put_cstring("");
1566 	} else {
1567 		packet_start(SSH_MSG_DEBUG);
1568 		packet_put_cstring(buf);
1569 	}
1570 	packet_send();
1571 	packet_write_wait();
1572 }
1573 
1574 /*
1575  * Logs the error plus constructs and sends a disconnect packet, closes the
1576  * connection, and exits.  This function never returns. The error message
1577  * should not contain a newline.  The length of the formatted message must
1578  * not exceed 1024 bytes.
1579  */
1580 
1581 void
1582 packet_disconnect(const char *fmt,...)
1583 {
1584 	char buf[1024];
1585 	va_list args;
1586 	static int disconnecting = 0;
1587 
1588 	if (disconnecting)	/* Guard against recursive invocations. */
1589 		fatal("packet_disconnect called recursively.");
1590 	disconnecting = 1;
1591 
1592 	/*
1593 	 * Format the message.  Note that the caller must make sure the
1594 	 * message is of limited size.
1595 	 */
1596 	va_start(args, fmt);
1597 	vsnprintf(buf, sizeof(buf), fmt, args);
1598 	va_end(args);
1599 
1600 	/* Display the error locally */
1601 	logit("Disconnecting: %.100s", buf);
1602 
1603 	/* Send the disconnect message to the other side, and wait for it to get sent. */
1604 	if (compat20) {
1605 		packet_start(SSH2_MSG_DISCONNECT);
1606 		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1607 		packet_put_cstring(buf);
1608 		packet_put_cstring("");
1609 	} else {
1610 		packet_start(SSH_MSG_DISCONNECT);
1611 		packet_put_cstring(buf);
1612 	}
1613 	packet_send();
1614 	packet_write_wait();
1615 
1616 	/* Stop listening for connections. */
1617 	channel_close_all();
1618 
1619 	/* Close the connection. */
1620 	packet_close();
1621 	cleanup_exit(255);
1622 }
1623 
1624 /* Checks if there is any buffered output, and tries to write some of the output. */
1625 
1626 void
1627 packet_write_poll(void)
1628 {
1629 	int len = buffer_len(&active_state->output);
1630 	int cont;
1631 
1632 	if (len > 0) {
1633 		cont = 0;
1634 		len = roaming_write(active_state->connection_out,
1635 		    buffer_ptr(&active_state->output), len, &cont);
1636 		if (len == -1) {
1637 			if (errno == EINTR || errno == EAGAIN)
1638 				return;
1639 			fatal("Write failed: %.100s", strerror(errno));
1640 		}
1641 		if (len == 0 && !cont)
1642 			fatal("Write connection closed");
1643 		buffer_consume(&active_state->output, len);
1644 	}
1645 }
1646 
1647 /*
1648  * Calls packet_write_poll repeatedly until all pending output data has been
1649  * written.
1650  */
1651 
1652 void
1653 packet_write_wait(void)
1654 {
1655 	fd_set *setp;
1656 	int ret, ms_remain;
1657 	struct timeval start, timeout, *timeoutp = NULL;
1658 
1659 	setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
1660 	    NFDBITS), sizeof(fd_mask));
1661 	packet_write_poll();
1662 	while (packet_have_data_to_write()) {
1663 		memset(setp, 0, howmany(active_state->connection_out + 1,
1664 		    NFDBITS) * sizeof(fd_mask));
1665 		FD_SET(active_state->connection_out, setp);
1666 
1667 		if (active_state->packet_timeout_ms > 0) {
1668 			ms_remain = active_state->packet_timeout_ms;
1669 			timeoutp = &timeout;
1670 		}
1671 		for (;;) {
1672 			if (active_state->packet_timeout_ms != -1) {
1673 				ms_to_timeval(&timeout, ms_remain);
1674 				gettimeofday(&start, NULL);
1675 			}
1676 			if ((ret = select(active_state->connection_out + 1,
1677 			    NULL, setp, NULL, timeoutp)) >= 0)
1678 				break;
1679 			if (errno != EAGAIN && errno != EINTR)
1680 				break;
1681 			if (active_state->packet_timeout_ms == -1)
1682 				continue;
1683 			ms_subtract_diff(&start, &ms_remain);
1684 			if (ms_remain <= 0) {
1685 				ret = 0;
1686 				break;
1687 			}
1688 		}
1689 		if (ret == 0) {
1690 			logit("Connection to %.200s timed out while "
1691 			    "waiting to write", get_remote_ipaddr());
1692 			cleanup_exit(255);
1693 		}
1694 		packet_write_poll();
1695 	}
1696 	xfree(setp);
1697 }
1698 
1699 /* Returns true if there is buffered data to write to the connection. */
1700 
1701 int
1702 packet_have_data_to_write(void)
1703 {
1704 	return buffer_len(&active_state->output) != 0;
1705 }
1706 
1707 /* Returns true if there is not too much data to write to the connection. */
1708 
1709 int
1710 packet_not_very_much_data_to_write(void)
1711 {
1712 	if (active_state->interactive_mode)
1713 		return buffer_len(&active_state->output) < 16384;
1714 	else
1715 		return buffer_len(&active_state->output) < 128 * 1024;
1716 }
1717 
1718 static void
1719 packet_set_tos(int interactive)
1720 {
1721 	int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
1722 
1723 	if (!packet_connection_is_on_socket() ||
1724 	    !packet_connection_is_ipv4())
1725 		return;
1726 	if (setsockopt(active_state->connection_in, IPPROTO_IP, IP_TOS, &tos,
1727 	    sizeof(tos)) < 0)
1728 		error("setsockopt IP_TOS %d: %.100s:",
1729 		    tos, strerror(errno));
1730 }
1731 
1732 /* Informs that the current session is interactive.  Sets IP flags for that. */
1733 
1734 void
1735 packet_set_interactive(int interactive)
1736 {
1737 	if (active_state->set_interactive_called)
1738 		return;
1739 	active_state->set_interactive_called = 1;
1740 
1741 	/* Record that we are in interactive mode. */
1742 	active_state->interactive_mode = interactive;
1743 
1744 	/* Only set socket options if using a socket.  */
1745 	if (!packet_connection_is_on_socket())
1746 		return;
1747 	set_nodelay(active_state->connection_in);
1748 	packet_set_tos(interactive);
1749 }
1750 
1751 /* Returns true if the current connection is interactive. */
1752 
1753 int
1754 packet_is_interactive(void)
1755 {
1756 	return active_state->interactive_mode;
1757 }
1758 
1759 int
1760 packet_set_maxsize(u_int s)
1761 {
1762 	if (active_state->set_maxsize_called) {
1763 		logit("packet_set_maxsize: called twice: old %d new %d",
1764 		    active_state->max_packet_size, s);
1765 		return -1;
1766 	}
1767 	if (s < 4 * 1024 || s > 1024 * 1024) {
1768 		logit("packet_set_maxsize: bad size %d", s);
1769 		return -1;
1770 	}
1771 	active_state->set_maxsize_called = 1;
1772 	debug("packet_set_maxsize: setting to %d", s);
1773 	active_state->max_packet_size = s;
1774 	return s;
1775 }
1776 
1777 int
1778 packet_inc_alive_timeouts(void)
1779 {
1780 	return ++active_state->keep_alive_timeouts;
1781 }
1782 
1783 void
1784 packet_set_alive_timeouts(int ka)
1785 {
1786 	active_state->keep_alive_timeouts = ka;
1787 }
1788 
1789 u_int
1790 packet_get_maxsize(void)
1791 {
1792 	return active_state->max_packet_size;
1793 }
1794 
1795 /* roundup current message to pad bytes */
1796 void
1797 packet_add_padding(u_char pad)
1798 {
1799 	active_state->extra_pad = pad;
1800 }
1801 
1802 /*
1803  * 9.2.  Ignored Data Message
1804  *
1805  *   byte      SSH_MSG_IGNORE
1806  *   string    data
1807  *
1808  * All implementations MUST understand (and ignore) this message at any
1809  * time (after receiving the protocol version). No implementation is
1810  * required to send them. This message can be used as an additional
1811  * protection measure against advanced traffic analysis techniques.
1812  */
1813 void
1814 packet_send_ignore(int nbytes)
1815 {
1816 	u_int32_t rnd = 0;
1817 	int i;
1818 
1819 	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1820 	packet_put_int(nbytes);
1821 	for (i = 0; i < nbytes; i++) {
1822 		if (i % 4 == 0)
1823 			rnd = arc4random();
1824 		packet_put_char((u_char)rnd & 0xff);
1825 		rnd >>= 8;
1826 	}
1827 }
1828 
1829 #define MAX_PACKETS	(1U<<31)
1830 int
1831 packet_need_rekeying(void)
1832 {
1833 	if (datafellows & SSH_BUG_NOREKEY)
1834 		return 0;
1835 	return
1836 	    (active_state->p_send.packets > MAX_PACKETS) ||
1837 	    (active_state->p_read.packets > MAX_PACKETS) ||
1838 	    (active_state->max_blocks_out &&
1839 	        (active_state->p_send.blocks > active_state->max_blocks_out)) ||
1840 	    (active_state->max_blocks_in &&
1841 	        (active_state->p_read.blocks > active_state->max_blocks_in));
1842 }
1843 
1844 void
1845 packet_set_rekey_limit(u_int32_t bytes)
1846 {
1847 	active_state->rekey_limit = bytes;
1848 }
1849 
1850 void
1851 packet_set_server(void)
1852 {
1853 	active_state->server_side = 1;
1854 }
1855 
1856 void
1857 packet_set_authenticated(void)
1858 {
1859 	active_state->after_authentication = 1;
1860 }
1861 
1862 void *
1863 packet_get_input(void)
1864 {
1865 	return (void *)&active_state->input;
1866 }
1867 
1868 void *
1869 packet_get_output(void)
1870 {
1871 	return (void *)&active_state->output;
1872 }
1873 
1874 void *
1875 packet_get_newkeys(int mode)
1876 {
1877 	return (void *)active_state->newkeys[mode];
1878 }
1879 
1880 /*
1881  * Save the state for the real connection, and use a separate state when
1882  * resuming a suspended connection.
1883  */
1884 void
1885 packet_backup_state(void)
1886 {
1887 	struct session_state *tmp;
1888 
1889 	close(active_state->connection_in);
1890 	active_state->connection_in = -1;
1891 	close(active_state->connection_out);
1892 	active_state->connection_out = -1;
1893 	if (backup_state)
1894 		tmp = backup_state;
1895 	else
1896 		tmp = alloc_session_state();
1897 	backup_state = active_state;
1898 	active_state = tmp;
1899 }
1900 
1901 /*
1902  * Swap in the old state when resuming a connecion.
1903  */
1904 void
1905 packet_restore_state(void)
1906 {
1907 	struct session_state *tmp;
1908 	void *buf;
1909 	u_int len;
1910 
1911 	tmp = backup_state;
1912 	backup_state = active_state;
1913 	active_state = tmp;
1914 	active_state->connection_in = backup_state->connection_in;
1915 	backup_state->connection_in = -1;
1916 	active_state->connection_out = backup_state->connection_out;
1917 	backup_state->connection_out = -1;
1918 	len = buffer_len(&backup_state->input);
1919 	if (len > 0) {
1920 		buf = buffer_ptr(&backup_state->input);
1921 		buffer_append(&active_state->input, buf, len);
1922 		buffer_clear(&backup_state->input);
1923 		add_recv_bytes(len);
1924 	}
1925 }
1926