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