packet.c revision 98937
1/*
2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 *                    All rights reserved
5 * This file contains code implementing the packet protocol and communication
6 * with the other side.  This same code is used both on client and server side.
7 *
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose.  Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
13 *
14 *
15 * SSH2 packet format added by Markus Friedl.
16 * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
20 * are met:
21 * 1. Redistributions of source code must retain the above copyright
22 *    notice, this list of conditions and the following disclaimer.
23 * 2. Redistributions in binary form must reproduce the above copyright
24 *    notice, this list of conditions and the following disclaimer in the
25 *    documentation and/or other materials provided with the distribution.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38
39#include "includes.h"
40RCSID("$OpenBSD: packet.c,v 1.95 2002/06/19 18:01:00 markus Exp $");
41
42#include "xmalloc.h"
43#include "buffer.h"
44#include "packet.h"
45#include "bufaux.h"
46#include "crc32.h"
47#include "getput.h"
48
49#include "compress.h"
50#include "deattack.h"
51#include "channels.h"
52
53#include "compat.h"
54#include "ssh1.h"
55#include "ssh2.h"
56
57#include "cipher.h"
58#include "kex.h"
59#include "mac.h"
60#include "log.h"
61#include "canohost.h"
62#include "misc.h"
63#include "ssh.h"
64
65#ifdef PACKET_DEBUG
66#define DBG(x) x
67#else
68#define DBG(x)
69#endif
70
71/*
72 * This variable contains the file descriptors used for communicating with
73 * the other side.  connection_in is used for reading; connection_out for
74 * writing.  These can be the same descriptor, in which case it is assumed to
75 * be a socket.
76 */
77static int connection_in = -1;
78static int connection_out = -1;
79
80/* Protocol flags for the remote side. */
81static u_int remote_protocol_flags = 0;
82
83/* Encryption context for receiving data.  This is only used for decryption. */
84static CipherContext receive_context;
85
86/* Encryption context for sending data.  This is only used for encryption. */
87static CipherContext send_context;
88
89/* Buffer for raw input data from the socket. */
90Buffer input;
91
92/* Buffer for raw output data going to the socket. */
93Buffer output;
94
95/* Buffer for the partial outgoing packet being constructed. */
96static Buffer outgoing_packet;
97
98/* Buffer for the incoming packet currently being processed. */
99static Buffer incoming_packet;
100
101/* Scratch buffer for packet compression/decompression. */
102static Buffer compression_buffer;
103static int compression_buffer_ready = 0;
104
105/* Flag indicating whether packet compression/decompression is enabled. */
106static int packet_compression = 0;
107
108/* default maximum packet size */
109int max_packet_size = 32768;
110
111/* Flag indicating whether this module has been initialized. */
112static int initialized = 0;
113
114/* Set to true if the connection is interactive. */
115static int interactive_mode = 0;
116
117/* Session key information for Encryption and MAC */
118Newkeys *newkeys[MODE_MAX];
119static u_int32_t read_seqnr = 0;
120static u_int32_t send_seqnr = 0;
121
122/* Session key for protocol v1 */
123static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
124static u_int ssh1_keylen;
125
126/* roundup current message to extra_pad bytes */
127static u_char extra_pad = 0;
128
129/*
130 * Sets the descriptors used for communication.  Disables encryption until
131 * packet_set_encryption_key is called.
132 */
133void
134packet_set_connection(int fd_in, int fd_out)
135{
136	Cipher *none = cipher_by_name("none");
137	if (none == NULL)
138		fatal("packet_set_connection: cannot load cipher 'none'");
139	connection_in = fd_in;
140	connection_out = fd_out;
141	cipher_init(&send_context, none, "", 0, NULL, 0, CIPHER_ENCRYPT);
142	cipher_init(&receive_context, none, "", 0, NULL, 0, CIPHER_DECRYPT);
143	newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
144	if (!initialized) {
145		initialized = 1;
146		buffer_init(&input);
147		buffer_init(&output);
148		buffer_init(&outgoing_packet);
149		buffer_init(&incoming_packet);
150	}
151	/* Kludge: arrange the close function to be called from fatal(). */
152	fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
153}
154
155/* Returns 1 if remote host is connected via socket, 0 if not. */
156
157int
158packet_connection_is_on_socket(void)
159{
160	struct sockaddr_storage from, to;
161	socklen_t fromlen, tolen;
162
163	/* filedescriptors in and out are the same, so it's a socket */
164	if (connection_in == connection_out)
165		return 1;
166	fromlen = sizeof(from);
167	memset(&from, 0, sizeof(from));
168	if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
169		return 0;
170	tolen = sizeof(to);
171	memset(&to, 0, sizeof(to));
172	if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
173		return 0;
174	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
175		return 0;
176	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
177		return 0;
178	return 1;
179}
180
181/*
182 * Exports an IV from the CipherContext required to export the key
183 * state back from the unprivileged child to the privileged parent
184 * process.
185 */
186
187void
188packet_get_keyiv(int mode, u_char *iv, u_int len)
189{
190	CipherContext *cc;
191
192	if (mode == MODE_OUT)
193		cc = &send_context;
194	else
195		cc = &receive_context;
196
197	cipher_get_keyiv(cc, iv, len);
198}
199
200int
201packet_get_keycontext(int mode, u_char *dat)
202{
203	CipherContext *cc;
204
205	if (mode == MODE_OUT)
206		cc = &send_context;
207	else
208		cc = &receive_context;
209
210	return (cipher_get_keycontext(cc, dat));
211}
212
213void
214packet_set_keycontext(int mode, u_char *dat)
215{
216	CipherContext *cc;
217
218	if (mode == MODE_OUT)
219		cc = &send_context;
220	else
221		cc = &receive_context;
222
223	cipher_set_keycontext(cc, dat);
224}
225
226int
227packet_get_keyiv_len(int mode)
228{
229	CipherContext *cc;
230
231	if (mode == MODE_OUT)
232		cc = &send_context;
233	else
234		cc = &receive_context;
235
236	return (cipher_get_keyiv_len(cc));
237}
238void
239packet_set_iv(int mode, u_char *dat)
240{
241	CipherContext *cc;
242
243	if (mode == MODE_OUT)
244		cc = &send_context;
245	else
246		cc = &receive_context;
247
248	cipher_set_keyiv(cc, dat);
249}
250int
251packet_get_ssh1_cipher()
252{
253	return (cipher_get_number(receive_context.cipher));
254}
255
256
257u_int32_t
258packet_get_seqnr(int mode)
259{
260	return (mode == MODE_IN ? read_seqnr : send_seqnr);
261}
262
263void
264packet_set_seqnr(int mode, u_int32_t seqnr)
265{
266	if (mode == MODE_IN)
267		read_seqnr = seqnr;
268	else if (mode == MODE_OUT)
269		send_seqnr = seqnr;
270	else
271		fatal("packet_set_seqnr: bad mode %d", mode);
272}
273
274/* returns 1 if connection is via ipv4 */
275
276int
277packet_connection_is_ipv4(void)
278{
279	struct sockaddr_storage to;
280	socklen_t tolen = sizeof(to);
281
282	memset(&to, 0, sizeof(to));
283	if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
284		return 0;
285	if (to.ss_family == AF_INET)
286		return 1;
287#ifdef IPV4_IN_IPV6
288	if (to.ss_family == AF_INET6 &&
289	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
290		return 1;
291#endif
292	return 0;
293}
294
295/* Sets the connection into non-blocking mode. */
296
297void
298packet_set_nonblocking(void)
299{
300	/* Set the socket into non-blocking mode. */
301	if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
302		error("fcntl O_NONBLOCK: %.100s", strerror(errno));
303
304	if (connection_out != connection_in) {
305		if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
306			error("fcntl O_NONBLOCK: %.100s", strerror(errno));
307	}
308}
309
310/* Returns the socket used for reading. */
311
312int
313packet_get_connection_in(void)
314{
315	return connection_in;
316}
317
318/* Returns the descriptor used for writing. */
319
320int
321packet_get_connection_out(void)
322{
323	return connection_out;
324}
325
326/* Closes the connection and clears and frees internal data structures. */
327
328void
329packet_close(void)
330{
331	if (!initialized)
332		return;
333	initialized = 0;
334	if (connection_in == connection_out) {
335		shutdown(connection_out, SHUT_RDWR);
336		close(connection_out);
337	} else {
338		close(connection_in);
339		close(connection_out);
340	}
341	buffer_free(&input);
342	buffer_free(&output);
343	buffer_free(&outgoing_packet);
344	buffer_free(&incoming_packet);
345	if (compression_buffer_ready) {
346		buffer_free(&compression_buffer);
347		buffer_compress_uninit();
348	}
349	cipher_cleanup(&send_context);
350	cipher_cleanup(&receive_context);
351}
352
353/* Sets remote side protocol flags. */
354
355void
356packet_set_protocol_flags(u_int protocol_flags)
357{
358	remote_protocol_flags = protocol_flags;
359}
360
361/* Returns the remote protocol flags set earlier by the above function. */
362
363u_int
364packet_get_protocol_flags(void)
365{
366	return remote_protocol_flags;
367}
368
369/*
370 * Starts packet compression from the next packet on in both directions.
371 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
372 */
373
374static void
375packet_init_compression(void)
376{
377	if (compression_buffer_ready == 1)
378		return;
379	compression_buffer_ready = 1;
380	buffer_init(&compression_buffer);
381}
382
383void
384packet_start_compression(int level)
385{
386	if (packet_compression && !compat20)
387		fatal("Compression already enabled.");
388	packet_compression = 1;
389	packet_init_compression();
390	buffer_compress_init_send(level);
391	buffer_compress_init_recv();
392}
393
394/*
395 * Causes any further packets to be encrypted using the given key.  The same
396 * key is used for both sending and reception.  However, both directions are
397 * encrypted independently of each other.
398 */
399
400void
401packet_set_encryption_key(const u_char *key, u_int keylen,
402    int number)
403{
404	Cipher *cipher = cipher_by_number(number);
405	if (cipher == NULL)
406		fatal("packet_set_encryption_key: unknown cipher number %d", number);
407	if (keylen < 20)
408		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
409	if (keylen > SSH_SESSION_KEY_LENGTH)
410		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
411	memcpy(ssh1_key, key, keylen);
412	ssh1_keylen = keylen;
413	cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
414	cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
415}
416
417u_int
418packet_get_encryption_key(u_char *key)
419{
420	if (key == NULL)
421		return (ssh1_keylen);
422	memcpy(key, ssh1_key, ssh1_keylen);
423	return (ssh1_keylen);
424}
425
426/* Start constructing a packet to send. */
427void
428packet_start(u_char type)
429{
430	u_char buf[9];
431	int len;
432
433	DBG(debug("packet_start[%d]", type));
434	len = compat20 ? 6 : 9;
435	memset(buf, 0, len - 1);
436	buf[len - 1] = type;
437	buffer_clear(&outgoing_packet);
438	buffer_append(&outgoing_packet, buf, len);
439}
440
441/* Append payload. */
442void
443packet_put_char(int value)
444{
445	char ch = value;
446	buffer_append(&outgoing_packet, &ch, 1);
447}
448void
449packet_put_int(u_int value)
450{
451	buffer_put_int(&outgoing_packet, value);
452}
453void
454packet_put_string(const void *buf, u_int len)
455{
456	buffer_put_string(&outgoing_packet, buf, len);
457}
458void
459packet_put_cstring(const char *str)
460{
461	buffer_put_cstring(&outgoing_packet, str);
462}
463void
464packet_put_raw(const void *buf, u_int len)
465{
466	buffer_append(&outgoing_packet, buf, len);
467}
468void
469packet_put_bignum(BIGNUM * value)
470{
471	buffer_put_bignum(&outgoing_packet, value);
472}
473void
474packet_put_bignum2(BIGNUM * value)
475{
476	buffer_put_bignum2(&outgoing_packet, value);
477}
478
479/*
480 * Finalizes and sends the packet.  If the encryption key has been set,
481 * encrypts the packet before sending.
482 */
483
484static void
485packet_send1(void)
486{
487	u_char buf[8], *cp;
488	int i, padding, len;
489	u_int checksum;
490	u_int32_t rand = 0;
491
492	/*
493	 * If using packet compression, compress the payload of the outgoing
494	 * packet.
495	 */
496	if (packet_compression) {
497		buffer_clear(&compression_buffer);
498		/* Skip padding. */
499		buffer_consume(&outgoing_packet, 8);
500		/* padding */
501		buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
502		buffer_compress(&outgoing_packet, &compression_buffer);
503		buffer_clear(&outgoing_packet);
504		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
505		    buffer_len(&compression_buffer));
506	}
507	/* Compute packet length without padding (add checksum, remove padding). */
508	len = buffer_len(&outgoing_packet) + 4 - 8;
509
510	/* Insert padding. Initialized to zero in packet_start1() */
511	padding = 8 - len % 8;
512	if (!send_context.plaintext) {
513		cp = buffer_ptr(&outgoing_packet);
514		for (i = 0; i < padding; i++) {
515			if (i % 4 == 0)
516				rand = arc4random();
517			cp[7 - i] = rand & 0xff;
518			rand >>= 8;
519		}
520	}
521	buffer_consume(&outgoing_packet, 8 - padding);
522
523	/* Add check bytes. */
524	checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
525	    buffer_len(&outgoing_packet));
526	PUT_32BIT(buf, checksum);
527	buffer_append(&outgoing_packet, buf, 4);
528
529#ifdef PACKET_DEBUG
530	fprintf(stderr, "packet_send plain: ");
531	buffer_dump(&outgoing_packet);
532#endif
533
534	/* Append to output. */
535	PUT_32BIT(buf, len);
536	buffer_append(&output, buf, 4);
537	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
538	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
539	    buffer_len(&outgoing_packet));
540
541#ifdef PACKET_DEBUG
542	fprintf(stderr, "encrypted: ");
543	buffer_dump(&output);
544#endif
545
546	buffer_clear(&outgoing_packet);
547
548	/*
549	 * Note that the packet is now only buffered in output.  It won\'t be
550	 * actually sent until packet_write_wait or packet_write_poll is
551	 * called.
552	 */
553}
554
555void
556set_newkeys(int mode)
557{
558	Enc *enc;
559	Mac *mac;
560	Comp *comp;
561	CipherContext *cc;
562	int encrypt;
563
564	debug("newkeys: mode %d", mode);
565
566	if (mode == MODE_OUT) {
567		cc = &send_context;
568		encrypt = CIPHER_ENCRYPT;
569	} else {
570		cc = &receive_context;
571		encrypt = CIPHER_DECRYPT;
572	}
573	if (newkeys[mode] != NULL) {
574		debug("newkeys: rekeying");
575		cipher_cleanup(cc);
576		enc  = &newkeys[mode]->enc;
577		mac  = &newkeys[mode]->mac;
578		comp = &newkeys[mode]->comp;
579		memset(mac->key, 0, mac->key_len);
580		xfree(enc->name);
581		xfree(enc->iv);
582		xfree(enc->key);
583		xfree(mac->name);
584		xfree(mac->key);
585		xfree(comp->name);
586		xfree(newkeys[mode]);
587	}
588	newkeys[mode] = kex_get_newkeys(mode);
589	if (newkeys[mode] == NULL)
590		fatal("newkeys: no keys for mode %d", mode);
591	enc  = &newkeys[mode]->enc;
592	mac  = &newkeys[mode]->mac;
593	comp = &newkeys[mode]->comp;
594	if (mac->md != NULL)
595		mac->enabled = 1;
596	DBG(debug("cipher_init_context: %d", mode));
597	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
598	    enc->iv, enc->block_size, encrypt);
599	/* Deleting the keys does not gain extra security */
600	/* memset(enc->iv,  0, enc->block_size);
601	   memset(enc->key, 0, enc->key_len); */
602	if (comp->type != 0 && comp->enabled == 0) {
603		packet_init_compression();
604		if (mode == MODE_OUT)
605			buffer_compress_init_send(6);
606		else
607			buffer_compress_init_recv();
608		comp->enabled = 1;
609	}
610}
611
612/*
613 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
614 */
615static void
616packet_send2(void)
617{
618	u_char type, *cp, *macbuf = NULL;
619	u_char padlen, pad;
620	u_int packet_length = 0;
621	u_int i, len;
622	u_int32_t rand = 0;
623	Enc *enc   = NULL;
624	Mac *mac   = NULL;
625	Comp *comp = NULL;
626	int block_size;
627
628	if (newkeys[MODE_OUT] != NULL) {
629		enc  = &newkeys[MODE_OUT]->enc;
630		mac  = &newkeys[MODE_OUT]->mac;
631		comp = &newkeys[MODE_OUT]->comp;
632	}
633	block_size = enc ? enc->block_size : 8;
634
635	cp = buffer_ptr(&outgoing_packet);
636	type = cp[5];
637
638#ifdef PACKET_DEBUG
639	fprintf(stderr, "plain:     ");
640	buffer_dump(&outgoing_packet);
641#endif
642
643	if (comp && comp->enabled) {
644		len = buffer_len(&outgoing_packet);
645		/* skip header, compress only payload */
646		buffer_consume(&outgoing_packet, 5);
647		buffer_clear(&compression_buffer);
648		buffer_compress(&outgoing_packet, &compression_buffer);
649		buffer_clear(&outgoing_packet);
650		buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
651		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
652		    buffer_len(&compression_buffer));
653		DBG(debug("compression: raw %d compressed %d", len,
654		    buffer_len(&outgoing_packet)));
655	}
656
657	/* sizeof (packet_len + pad_len + payload) */
658	len = buffer_len(&outgoing_packet);
659
660	/*
661	 * calc size of padding, alloc space, get random data,
662	 * minimum padding is 4 bytes
663	 */
664	padlen = block_size - (len % block_size);
665	if (padlen < 4)
666		padlen += block_size;
667	if (extra_pad) {
668		/* will wrap if extra_pad+padlen > 255 */
669		extra_pad  = roundup(extra_pad, block_size);
670		pad = extra_pad - ((len + padlen) % extra_pad);
671		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
672		    pad, len, padlen, extra_pad);
673		padlen += pad;
674		extra_pad = 0;
675	}
676	cp = buffer_append_space(&outgoing_packet, padlen);
677	if (enc && !send_context.plaintext) {
678		/* random padding */
679		for (i = 0; i < padlen; i++) {
680			if (i % 4 == 0)
681				rand = arc4random();
682			cp[i] = rand & 0xff;
683			rand >>= 8;
684		}
685	} else {
686		/* clear padding */
687		memset(cp, 0, padlen);
688	}
689	/* packet_length includes payload, padding and padding length field */
690	packet_length = buffer_len(&outgoing_packet) - 4;
691	cp = buffer_ptr(&outgoing_packet);
692	PUT_32BIT(cp, packet_length);
693	cp[4] = padlen;
694	DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
695
696	/* compute MAC over seqnr and packet(length fields, payload, padding) */
697	if (mac && mac->enabled) {
698		macbuf = mac_compute(mac, send_seqnr,
699		    buffer_ptr(&outgoing_packet),
700		    buffer_len(&outgoing_packet));
701		DBG(debug("done calc MAC out #%d", send_seqnr));
702	}
703	/* encrypt packet and append to output buffer. */
704	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
705	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
706	    buffer_len(&outgoing_packet));
707	/* append unencrypted MAC */
708	if (mac && mac->enabled)
709		buffer_append(&output, (char *)macbuf, mac->mac_len);
710#ifdef PACKET_DEBUG
711	fprintf(stderr, "encrypted: ");
712	buffer_dump(&output);
713#endif
714	/* increment sequence number for outgoing packets */
715	if (++send_seqnr == 0)
716		log("outgoing seqnr wraps around");
717	buffer_clear(&outgoing_packet);
718
719	if (type == SSH2_MSG_NEWKEYS)
720		set_newkeys(MODE_OUT);
721}
722
723void
724packet_send(void)
725{
726	if (compat20)
727		packet_send2();
728	else
729		packet_send1();
730	DBG(debug("packet_send done"));
731}
732
733/*
734 * Waits until a packet has been received, and returns its type.  Note that
735 * no other data is processed until this returns, so this function should not
736 * be used during the interactive session.
737 */
738
739int
740packet_read_seqnr(u_int32_t *seqnr_p)
741{
742	int type, len;
743	fd_set *setp;
744	char buf[8192];
745	DBG(debug("packet_read()"));
746
747	setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
748	    sizeof(fd_mask));
749
750	/* Since we are blocking, ensure that all written packets have been sent. */
751	packet_write_wait();
752
753	/* Stay in the loop until we have received a complete packet. */
754	for (;;) {
755		/* Try to read a packet from the buffer. */
756		type = packet_read_poll_seqnr(seqnr_p);
757		if (!compat20 && (
758		    type == SSH_SMSG_SUCCESS
759		    || type == SSH_SMSG_FAILURE
760		    || type == SSH_CMSG_EOF
761		    || type == SSH_CMSG_EXIT_CONFIRMATION))
762			packet_check_eom();
763		/* If we got a packet, return it. */
764		if (type != SSH_MSG_NONE) {
765			xfree(setp);
766			return type;
767		}
768		/*
769		 * Otherwise, wait for some data to arrive, add it to the
770		 * buffer, and try again.
771		 */
772		memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
773		    sizeof(fd_mask));
774		FD_SET(connection_in, setp);
775
776		/* Wait for some data to arrive. */
777		while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
778		    (errno == EAGAIN || errno == EINTR))
779			;
780
781		/* Read data from the socket. */
782		len = read(connection_in, buf, sizeof(buf));
783		if (len == 0) {
784			log("Connection closed by %.200s", get_remote_ipaddr());
785			fatal_cleanup();
786		}
787		if (len < 0)
788			fatal("Read from socket failed: %.100s", strerror(errno));
789		/* Append it to the buffer. */
790		packet_process_incoming(buf, len);
791	}
792	/* NOTREACHED */
793}
794
795int
796packet_read(void)
797{
798	return packet_read_seqnr(NULL);
799}
800
801/*
802 * Waits until a packet has been received, verifies that its type matches
803 * that given, and gives a fatal error and exits if there is a mismatch.
804 */
805
806void
807packet_read_expect(int expected_type)
808{
809	int type;
810
811	type = packet_read();
812	if (type != expected_type)
813		packet_disconnect("Protocol error: expected packet type %d, got %d",
814		    expected_type, type);
815}
816
817/* Checks if a full packet is available in the data received so far via
818 * packet_process_incoming.  If so, reads the packet; otherwise returns
819 * SSH_MSG_NONE.  This does not wait for data from the connection.
820 *
821 * SSH_MSG_DISCONNECT is handled specially here.  Also,
822 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
823 * to higher levels.
824 */
825
826static int
827packet_read_poll1(void)
828{
829	u_int len, padded_len;
830	u_char *cp, type;
831	u_int checksum, stored_checksum;
832
833	/* Check if input size is less than minimum packet size. */
834	if (buffer_len(&input) < 4 + 8)
835		return SSH_MSG_NONE;
836	/* Get length of incoming packet. */
837	cp = buffer_ptr(&input);
838	len = GET_32BIT(cp);
839	if (len < 1 + 2 + 2 || len > 256 * 1024)
840		packet_disconnect("Bad packet length %d.", len);
841	padded_len = (len + 8) & ~7;
842
843	/* Check if the packet has been entirely received. */
844	if (buffer_len(&input) < 4 + padded_len)
845		return SSH_MSG_NONE;
846
847	/* The entire packet is in buffer. */
848
849	/* Consume packet length. */
850	buffer_consume(&input, 4);
851
852	/*
853	 * Cryptographic attack detector for ssh
854	 * (C)1998 CORE-SDI, Buenos Aires Argentina
855	 * Ariel Futoransky(futo@core-sdi.com)
856	 */
857	if (!receive_context.plaintext &&
858	    detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
859		packet_disconnect("crc32 compensation attack: network attack detected");
860
861	/* Decrypt data to incoming_packet. */
862	buffer_clear(&incoming_packet);
863	cp = buffer_append_space(&incoming_packet, padded_len);
864	cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
865
866	buffer_consume(&input, padded_len);
867
868#ifdef PACKET_DEBUG
869	fprintf(stderr, "read_poll plain: ");
870	buffer_dump(&incoming_packet);
871#endif
872
873	/* Compute packet checksum. */
874	checksum = ssh_crc32(buffer_ptr(&incoming_packet),
875	    buffer_len(&incoming_packet) - 4);
876
877	/* Skip padding. */
878	buffer_consume(&incoming_packet, 8 - len % 8);
879
880	/* Test check bytes. */
881	if (len != buffer_len(&incoming_packet))
882		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
883		    len, buffer_len(&incoming_packet));
884
885	cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
886	stored_checksum = GET_32BIT(cp);
887	if (checksum != stored_checksum)
888		packet_disconnect("Corrupted check bytes on input.");
889	buffer_consume_end(&incoming_packet, 4);
890
891	if (packet_compression) {
892		buffer_clear(&compression_buffer);
893		buffer_uncompress(&incoming_packet, &compression_buffer);
894		buffer_clear(&incoming_packet);
895		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
896		    buffer_len(&compression_buffer));
897	}
898	type = buffer_get_char(&incoming_packet);
899	return type;
900}
901
902static int
903packet_read_poll2(u_int32_t *seqnr_p)
904{
905	static u_int packet_length = 0;
906	u_int padlen, need;
907	u_char *macbuf, *cp, type;
908	int maclen, block_size;
909	Enc *enc   = NULL;
910	Mac *mac   = NULL;
911	Comp *comp = NULL;
912
913	if (newkeys[MODE_IN] != NULL) {
914		enc  = &newkeys[MODE_IN]->enc;
915		mac  = &newkeys[MODE_IN]->mac;
916		comp = &newkeys[MODE_IN]->comp;
917	}
918	maclen = mac && mac->enabled ? mac->mac_len : 0;
919	block_size = enc ? enc->block_size : 8;
920
921	if (packet_length == 0) {
922		/*
923		 * check if input size is less than the cipher block size,
924		 * decrypt first block and extract length of incoming packet
925		 */
926		if (buffer_len(&input) < block_size)
927			return SSH_MSG_NONE;
928		buffer_clear(&incoming_packet);
929		cp = buffer_append_space(&incoming_packet, block_size);
930		cipher_crypt(&receive_context, cp, buffer_ptr(&input),
931		    block_size);
932		cp = buffer_ptr(&incoming_packet);
933		packet_length = GET_32BIT(cp);
934		if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
935			buffer_dump(&incoming_packet);
936			packet_disconnect("Bad packet length %d.", packet_length);
937		}
938		DBG(debug("input: packet len %d", packet_length+4));
939		buffer_consume(&input, block_size);
940	}
941	/* we have a partial packet of block_size bytes */
942	need = 4 + packet_length - block_size;
943	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
944	    need, maclen));
945	if (need % block_size != 0)
946		fatal("padding error: need %d block %d mod %d",
947		    need, block_size, need % block_size);
948	/*
949	 * check if the entire packet has been received and
950	 * decrypt into incoming_packet
951	 */
952	if (buffer_len(&input) < need + maclen)
953		return SSH_MSG_NONE;
954#ifdef PACKET_DEBUG
955	fprintf(stderr, "read_poll enc/full: ");
956	buffer_dump(&input);
957#endif
958	cp = buffer_append_space(&incoming_packet, need);
959	cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
960	buffer_consume(&input, need);
961	/*
962	 * compute MAC over seqnr and packet,
963	 * increment sequence number for incoming packet
964	 */
965	if (mac && mac->enabled) {
966		macbuf = mac_compute(mac, read_seqnr,
967		    buffer_ptr(&incoming_packet),
968		    buffer_len(&incoming_packet));
969		if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
970			packet_disconnect("Corrupted MAC on input.");
971		DBG(debug("MAC #%d ok", read_seqnr));
972		buffer_consume(&input, mac->mac_len);
973	}
974	if (seqnr_p != NULL)
975		*seqnr_p = read_seqnr;
976	if (++read_seqnr == 0)
977		log("incoming seqnr wraps around");
978
979	/* get padlen */
980	cp = buffer_ptr(&incoming_packet);
981	padlen = cp[4];
982	DBG(debug("input: padlen %d", padlen));
983	if (padlen < 4)
984		packet_disconnect("Corrupted padlen %d on input.", padlen);
985
986	/* skip packet size + padlen, discard padding */
987	buffer_consume(&incoming_packet, 4 + 1);
988	buffer_consume_end(&incoming_packet, padlen);
989
990	DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
991	if (comp && comp->enabled) {
992		buffer_clear(&compression_buffer);
993		buffer_uncompress(&incoming_packet, &compression_buffer);
994		buffer_clear(&incoming_packet);
995		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
996		    buffer_len(&compression_buffer));
997		DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
998	}
999	/*
1000	 * get packet type, implies consume.
1001	 * return length of payload (without type field)
1002	 */
1003	type = buffer_get_char(&incoming_packet);
1004	if (type == SSH2_MSG_NEWKEYS)
1005		set_newkeys(MODE_IN);
1006#ifdef PACKET_DEBUG
1007	fprintf(stderr, "read/plain[%d]:\r\n", type);
1008	buffer_dump(&incoming_packet);
1009#endif
1010	/* reset for next packet */
1011	packet_length = 0;
1012	return type;
1013}
1014
1015int
1016packet_read_poll_seqnr(u_int32_t *seqnr_p)
1017{
1018	int reason, seqnr;
1019	u_char type;
1020	char *msg;
1021
1022	for (;;) {
1023		if (compat20) {
1024			type = packet_read_poll2(seqnr_p);
1025			if (type)
1026				DBG(debug("received packet type %d", type));
1027			switch (type) {
1028			case SSH2_MSG_IGNORE:
1029				break;
1030			case SSH2_MSG_DEBUG:
1031				packet_get_char();
1032				msg = packet_get_string(NULL);
1033				debug("Remote: %.900s", msg);
1034				xfree(msg);
1035				msg = packet_get_string(NULL);
1036				xfree(msg);
1037				break;
1038			case SSH2_MSG_DISCONNECT:
1039				reason = packet_get_int();
1040				msg = packet_get_string(NULL);
1041				log("Received disconnect from %s: %d: %.400s", get_remote_ipaddr(),
1042					reason, msg);
1043				xfree(msg);
1044				fatal_cleanup();
1045				break;
1046			case SSH2_MSG_UNIMPLEMENTED:
1047				seqnr = packet_get_int();
1048				debug("Received SSH2_MSG_UNIMPLEMENTED for %d", seqnr);
1049				break;
1050			default:
1051				return type;
1052				break;
1053			}
1054		} else {
1055			type = packet_read_poll1();
1056			switch (type) {
1057			case SSH_MSG_IGNORE:
1058				break;
1059			case SSH_MSG_DEBUG:
1060				msg = packet_get_string(NULL);
1061				debug("Remote: %.900s", msg);
1062				xfree(msg);
1063				break;
1064			case SSH_MSG_DISCONNECT:
1065				msg = packet_get_string(NULL);
1066				log("Received disconnect from %s: %.400s", get_remote_ipaddr(),
1067					msg);
1068				fatal_cleanup();
1069				xfree(msg);
1070				break;
1071			default:
1072				if (type)
1073					DBG(debug("received packet type %d", type));
1074				return type;
1075				break;
1076			}
1077		}
1078	}
1079}
1080
1081int
1082packet_read_poll(void)
1083{
1084	return packet_read_poll_seqnr(NULL);
1085}
1086
1087/*
1088 * Buffers the given amount of input characters.  This is intended to be used
1089 * together with packet_read_poll.
1090 */
1091
1092void
1093packet_process_incoming(const char *buf, u_int len)
1094{
1095	buffer_append(&input, buf, len);
1096}
1097
1098/* Returns a character from the packet. */
1099
1100u_int
1101packet_get_char(void)
1102{
1103	char ch;
1104	buffer_get(&incoming_packet, &ch, 1);
1105	return (u_char) ch;
1106}
1107
1108/* Returns an integer from the packet data. */
1109
1110u_int
1111packet_get_int(void)
1112{
1113	return buffer_get_int(&incoming_packet);
1114}
1115
1116/*
1117 * Returns an arbitrary precision integer from the packet data.  The integer
1118 * must have been initialized before this call.
1119 */
1120
1121void
1122packet_get_bignum(BIGNUM * value)
1123{
1124	buffer_get_bignum(&incoming_packet, value);
1125}
1126
1127void
1128packet_get_bignum2(BIGNUM * value)
1129{
1130	buffer_get_bignum2(&incoming_packet, value);
1131}
1132
1133void *
1134packet_get_raw(int *length_ptr)
1135{
1136	int bytes = buffer_len(&incoming_packet);
1137	if (length_ptr != NULL)
1138		*length_ptr = bytes;
1139	return buffer_ptr(&incoming_packet);
1140}
1141
1142int
1143packet_remaining(void)
1144{
1145	return buffer_len(&incoming_packet);
1146}
1147
1148/*
1149 * Returns a string from the packet data.  The string is allocated using
1150 * xmalloc; it is the responsibility of the calling program to free it when
1151 * no longer needed.  The length_ptr argument may be NULL, or point to an
1152 * integer into which the length of the string is stored.
1153 */
1154
1155void *
1156packet_get_string(u_int *length_ptr)
1157{
1158	return buffer_get_string(&incoming_packet, length_ptr);
1159}
1160
1161/*
1162 * Sends a diagnostic message from the server to the client.  This message
1163 * can be sent at any time (but not while constructing another message). The
1164 * message is printed immediately, but only if the client is being executed
1165 * in verbose mode.  These messages are primarily intended to ease debugging
1166 * authentication problems.   The length of the formatted message must not
1167 * exceed 1024 bytes.  This will automatically call packet_write_wait.
1168 */
1169
1170void
1171packet_send_debug(const char *fmt,...)
1172{
1173	char buf[1024];
1174	va_list args;
1175
1176	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1177		return;
1178
1179	va_start(args, fmt);
1180	vsnprintf(buf, sizeof(buf), fmt, args);
1181	va_end(args);
1182
1183	if (compat20) {
1184		packet_start(SSH2_MSG_DEBUG);
1185		packet_put_char(0);	/* bool: always display */
1186		packet_put_cstring(buf);
1187		packet_put_cstring("");
1188	} else {
1189		packet_start(SSH_MSG_DEBUG);
1190		packet_put_cstring(buf);
1191	}
1192	packet_send();
1193	packet_write_wait();
1194}
1195
1196/*
1197 * Logs the error plus constructs and sends a disconnect packet, closes the
1198 * connection, and exits.  This function never returns. The error message
1199 * should not contain a newline.  The length of the formatted message must
1200 * not exceed 1024 bytes.
1201 */
1202
1203void
1204packet_disconnect(const char *fmt,...)
1205{
1206	char buf[1024];
1207	va_list args;
1208	static int disconnecting = 0;
1209	if (disconnecting)	/* Guard against recursive invocations. */
1210		fatal("packet_disconnect called recursively.");
1211	disconnecting = 1;
1212
1213	/*
1214	 * Format the message.  Note that the caller must make sure the
1215	 * message is of limited size.
1216	 */
1217	va_start(args, fmt);
1218	vsnprintf(buf, sizeof(buf), fmt, args);
1219	va_end(args);
1220
1221	/* Send the disconnect message to the other side, and wait for it to get sent. */
1222	if (compat20) {
1223		packet_start(SSH2_MSG_DISCONNECT);
1224		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1225		packet_put_cstring(buf);
1226		packet_put_cstring("");
1227	} else {
1228		packet_start(SSH_MSG_DISCONNECT);
1229		packet_put_cstring(buf);
1230	}
1231	packet_send();
1232	packet_write_wait();
1233
1234	/* Stop listening for connections. */
1235	channel_close_all();
1236
1237	/* Close the connection. */
1238	packet_close();
1239
1240	/* Display the error locally and exit. */
1241	log("Disconnecting: %.100s", buf);
1242	fatal_cleanup();
1243}
1244
1245/* Checks if there is any buffered output, and tries to write some of the output. */
1246
1247void
1248packet_write_poll(void)
1249{
1250	int len = buffer_len(&output);
1251	if (len > 0) {
1252		len = write(connection_out, buffer_ptr(&output), len);
1253		if (len <= 0) {
1254			if (errno == EAGAIN)
1255				return;
1256			else
1257				fatal("Write failed: %.100s", strerror(errno));
1258		}
1259		buffer_consume(&output, len);
1260	}
1261}
1262
1263/*
1264 * Calls packet_write_poll repeatedly until all pending output data has been
1265 * written.
1266 */
1267
1268void
1269packet_write_wait(void)
1270{
1271	fd_set *setp;
1272
1273	setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1274	    sizeof(fd_mask));
1275	packet_write_poll();
1276	while (packet_have_data_to_write()) {
1277		memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1278		    sizeof(fd_mask));
1279		FD_SET(connection_out, setp);
1280		while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1281		    (errno == EAGAIN || errno == EINTR))
1282			;
1283		packet_write_poll();
1284	}
1285	xfree(setp);
1286}
1287
1288/* Returns true if there is buffered data to write to the connection. */
1289
1290int
1291packet_have_data_to_write(void)
1292{
1293	return buffer_len(&output) != 0;
1294}
1295
1296/* Returns true if there is not too much data to write to the connection. */
1297
1298int
1299packet_not_very_much_data_to_write(void)
1300{
1301	if (interactive_mode)
1302		return buffer_len(&output) < 16384;
1303	else
1304		return buffer_len(&output) < 128 * 1024;
1305}
1306
1307/* Informs that the current session is interactive.  Sets IP flags for that. */
1308
1309void
1310packet_set_interactive(int interactive)
1311{
1312	static int called = 0;
1313#if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1314	int lowdelay = IPTOS_LOWDELAY;
1315	int throughput = IPTOS_THROUGHPUT;
1316#endif
1317
1318	if (called)
1319		return;
1320	called = 1;
1321
1322	/* Record that we are in interactive mode. */
1323	interactive_mode = interactive;
1324
1325	/* Only set socket options if using a socket.  */
1326	if (!packet_connection_is_on_socket())
1327		return;
1328	/*
1329	 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1330	 */
1331	if (interactive) {
1332		/*
1333		 * Set IP options for an interactive connection.  Use
1334		 * IPTOS_LOWDELAY and TCP_NODELAY.
1335		 */
1336#if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1337		if (packet_connection_is_ipv4()) {
1338			if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1339			    &lowdelay, sizeof(lowdelay)) < 0)
1340				error("setsockopt IPTOS_LOWDELAY: %.100s",
1341				    strerror(errno));
1342		}
1343#endif
1344		set_nodelay(connection_in);
1345	} else if (packet_connection_is_ipv4()) {
1346		/*
1347		 * Set IP options for a non-interactive connection.  Use
1348		 * IPTOS_THROUGHPUT.
1349		 */
1350#if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1351		if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &throughput,
1352		    sizeof(throughput)) < 0)
1353			error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1354#endif
1355	}
1356}
1357
1358/* Returns true if the current connection is interactive. */
1359
1360int
1361packet_is_interactive(void)
1362{
1363	return interactive_mode;
1364}
1365
1366int
1367packet_set_maxsize(int s)
1368{
1369	static int called = 0;
1370	if (called) {
1371		log("packet_set_maxsize: called twice: old %d new %d",
1372		    max_packet_size, s);
1373		return -1;
1374	}
1375	if (s < 4 * 1024 || s > 1024 * 1024) {
1376		log("packet_set_maxsize: bad size %d", s);
1377		return -1;
1378	}
1379	called = 1;
1380	debug("packet_set_maxsize: setting to %d", s);
1381	max_packet_size = s;
1382	return s;
1383}
1384
1385/* roundup current message to pad bytes */
1386void
1387packet_add_padding(u_char pad)
1388{
1389	extra_pad = pad;
1390}
1391
1392/*
1393 * 9.2.  Ignored Data Message
1394 *
1395 *   byte      SSH_MSG_IGNORE
1396 *   string    data
1397 *
1398 * All implementations MUST understand (and ignore) this message at any
1399 * time (after receiving the protocol version). No implementation is
1400 * required to send them. This message can be used as an additional
1401 * protection measure against advanced traffic analysis techniques.
1402 */
1403void
1404packet_send_ignore(int nbytes)
1405{
1406	u_int32_t rand = 0;
1407	int i;
1408
1409	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1410	packet_put_int(nbytes);
1411	for (i = 0; i < nbytes; i++) {
1412		if (i % 4 == 0)
1413			rand = arc4random();
1414		packet_put_char(rand & 0xff);
1415		rand >>= 8;
1416	}
1417}
1418