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