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