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