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