packet.c revision 65668
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 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.35 2000/09/07 20:27:52 deraadt Exp $");
41
42#include "xmalloc.h"
43#include "buffer.h"
44#include "packet.h"
45#include "bufaux.h"
46#include "ssh.h"
47#include "crc32.h"
48#include "cipher.h"
49#include "getput.h"
50
51#include "compress.h"
52#include "deattack.h"
53#include "channels.h"
54
55#include "compat.h"
56#include "ssh2.h"
57
58#include <openssl/bn.h>
59#include <openssl/dh.h>
60#include <openssl/hmac.h>
61#include "buffer.h"
62#include "kex.h"
63#include "hmac.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/*
81 * Cipher type.  This value is only used to determine whether to pad the
82 * packets with zeroes or random data.
83 */
84static int cipher_type = SSH_CIPHER_NONE;
85
86/* Protocol flags for the remote side. */
87static unsigned int remote_protocol_flags = 0;
88
89/* Encryption context for receiving data.  This is only used for decryption. */
90static CipherContext receive_context;
91
92/* Encryption context for sending data.  This is only used for encryption. */
93static CipherContext send_context;
94
95/* Buffer for raw input data from the socket. */
96static Buffer input;
97
98/* Buffer for raw output data going to the socket. */
99static Buffer output;
100
101/* Buffer for the partial outgoing packet being constructed. */
102static Buffer outgoing_packet;
103
104/* Buffer for the incoming packet currently being processed. */
105static Buffer incoming_packet;
106
107/* Scratch buffer for packet compression/decompression. */
108static Buffer compression_buffer;
109
110/* Flag indicating whether packet compression/decompression is enabled. */
111static int packet_compression = 0;
112
113/* default maximum packet size */
114int max_packet_size = 32768;
115
116/* Flag indicating whether this module has been initialized. */
117static int initialized = 0;
118
119/* Set to true if the connection is interactive. */
120static int interactive_mode = 0;
121
122/* True if SSH2 packet format is used */
123int use_ssh2_packet_format = 0;
124
125/* Session key information for Encryption and MAC */
126Kex	*kex = NULL;
127
128void
129packet_set_kex(Kex *k)
130{
131	if( k->mac[MODE_IN ].key == NULL ||
132	    k->enc[MODE_IN ].key == NULL ||
133	    k->enc[MODE_IN ].iv  == NULL ||
134	    k->mac[MODE_OUT].key == NULL ||
135	    k->enc[MODE_OUT].key == NULL ||
136	    k->enc[MODE_OUT].iv  == NULL)
137		fatal("bad KEX");
138	kex = k;
139}
140void
141clear_enc_keys(Enc *enc, int len)
142{
143	memset(enc->iv,  0, len);
144	memset(enc->key, 0, len);
145	xfree(enc->iv);
146	xfree(enc->key);
147	enc->iv = NULL;
148	enc->key = NULL;
149}
150void
151packet_set_ssh2_format(void)
152{
153	DBG(debug("use_ssh2_packet_format"));
154	use_ssh2_packet_format = 1;
155}
156
157/*
158 * Sets the descriptors used for communication.  Disables encryption until
159 * packet_set_encryption_key is called.
160 */
161void
162packet_set_connection(int fd_in, int fd_out)
163{
164	connection_in = fd_in;
165	connection_out = fd_out;
166	cipher_type = SSH_CIPHER_NONE;
167	cipher_set_key(&send_context, SSH_CIPHER_NONE, (unsigned char *) "", 0);
168	cipher_set_key(&receive_context, SSH_CIPHER_NONE, (unsigned char *) "", 0);
169	if (!initialized) {
170		initialized = 1;
171		buffer_init(&input);
172		buffer_init(&output);
173		buffer_init(&outgoing_packet);
174		buffer_init(&incoming_packet);
175	}
176	/* Kludge: arrange the close function to be called from fatal(). */
177	fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
178}
179
180/* Returns 1 if remote host is connected via socket, 0 if not. */
181
182int
183packet_connection_is_on_socket()
184{
185	struct sockaddr_storage from, to;
186	socklen_t fromlen, tolen;
187
188	/* filedescriptors in and out are the same, so it's a socket */
189	if (connection_in == connection_out)
190		return 1;
191	fromlen = sizeof(from);
192	memset(&from, 0, sizeof(from));
193	if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
194		return 0;
195	tolen = sizeof(to);
196	memset(&to, 0, sizeof(to));
197	if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
198		return 0;
199	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
200		return 0;
201	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
202		return 0;
203	return 1;
204}
205
206/* returns 1 if connection is via ipv4 */
207
208int
209packet_connection_is_ipv4()
210{
211	struct sockaddr_storage to;
212	socklen_t tolen = sizeof(to);
213
214	memset(&to, 0, sizeof(to));
215	if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
216		return 0;
217	if (to.ss_family != AF_INET)
218		return 0;
219	return 1;
220}
221
222/* Sets the connection into non-blocking mode. */
223
224void
225packet_set_nonblocking()
226{
227	/* Set the socket into non-blocking mode. */
228	if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
229		error("fcntl O_NONBLOCK: %.100s", strerror(errno));
230
231	if (connection_out != connection_in) {
232		if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
233			error("fcntl O_NONBLOCK: %.100s", strerror(errno));
234	}
235}
236
237/* Returns the socket used for reading. */
238
239int
240packet_get_connection_in()
241{
242	return connection_in;
243}
244
245/* Returns the descriptor used for writing. */
246
247int
248packet_get_connection_out()
249{
250	return connection_out;
251}
252
253/* Closes the connection and clears and frees internal data structures. */
254
255void
256packet_close()
257{
258	if (!initialized)
259		return;
260	initialized = 0;
261	if (connection_in == connection_out) {
262		shutdown(connection_out, SHUT_RDWR);
263		close(connection_out);
264	} else {
265		close(connection_in);
266		close(connection_out);
267	}
268	buffer_free(&input);
269	buffer_free(&output);
270	buffer_free(&outgoing_packet);
271	buffer_free(&incoming_packet);
272	if (packet_compression) {
273		buffer_free(&compression_buffer);
274		buffer_compress_uninit();
275	}
276}
277
278/* Sets remote side protocol flags. */
279
280void
281packet_set_protocol_flags(unsigned int protocol_flags)
282{
283	remote_protocol_flags = protocol_flags;
284	channel_set_options((protocol_flags & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) != 0);
285}
286
287/* Returns the remote protocol flags set earlier by the above function. */
288
289unsigned int
290packet_get_protocol_flags()
291{
292	return remote_protocol_flags;
293}
294
295/*
296 * Starts packet compression from the next packet on in both directions.
297 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
298 */
299
300/*** XXXXX todo: kex means re-init */
301void
302packet_start_compression(int level)
303{
304	if (packet_compression)
305		fatal("Compression already enabled.");
306	packet_compression = 1;
307	buffer_init(&compression_buffer);
308	buffer_compress_init(level);
309}
310
311/*
312 * Encrypts the given number of bytes, copying from src to dest. bytes is
313 * known to be a multiple of 8.
314 */
315
316void
317packet_encrypt(CipherContext * cc, void *dest, void *src,
318    unsigned int bytes)
319{
320	cipher_encrypt(cc, dest, src, bytes);
321}
322
323/*
324 * Decrypts the given number of bytes, copying from src to dest. bytes is
325 * known to be a multiple of 8.
326 */
327
328void
329packet_decrypt(CipherContext * cc, void *dest, void *src,
330    unsigned int bytes)
331{
332	int i;
333
334	if ((bytes % 8) != 0)
335		fatal("packet_decrypt: bad ciphertext length %d", bytes);
336
337	/*
338	 * Cryptographic attack detector for ssh - Modifications for packet.c
339	 * (C)1998 CORE-SDI, Buenos Aires Argentina Ariel Futoransky(futo@core-sdi.com)
340	 */
341
342	if (cc->type == SSH_CIPHER_NONE || compat20) {
343		i = DEATTACK_OK;
344	} else {
345		i = detect_attack(src, bytes, NULL);
346	}
347	if (i == DEATTACK_DETECTED)
348		packet_disconnect("crc32 compensation attack: network attack detected");
349
350	cipher_decrypt(cc, dest, src, bytes);
351}
352
353/*
354 * Causes any further packets to be encrypted using the given key.  The same
355 * key is used for both sending and reception.  However, both directions are
356 * encrypted independently of each other.
357 */
358
359void
360packet_set_encryption_key(const unsigned char *key, unsigned int keylen,
361    int cipher)
362{
363	if (keylen < 20)
364		fatal("keylen too small: %d", keylen);
365
366	/* All other ciphers use the same key in both directions for now. */
367	cipher_set_key(&receive_context, cipher, key, keylen);
368	cipher_set_key(&send_context, cipher, key, keylen);
369}
370
371/* Starts constructing a packet to send. */
372
373void
374packet_start1(int type)
375{
376	char buf[9];
377
378	buffer_clear(&outgoing_packet);
379	memset(buf, 0, 8);
380	buf[8] = type;
381	buffer_append(&outgoing_packet, buf, 9);
382}
383
384void
385packet_start2(int type)
386{
387	char buf[4+1+1];
388
389	buffer_clear(&outgoing_packet);
390	memset(buf, 0, sizeof buf);
391	/* buf[0..3] = payload_len; */
392	/* buf[4] =    pad_len; */
393	buf[5] = type & 0xff;
394	buffer_append(&outgoing_packet, buf, sizeof buf);
395}
396
397void
398packet_start(int type)
399{
400	DBG(debug("packet_start[%d]",type));
401	if (use_ssh2_packet_format)
402		packet_start2(type);
403	else
404		packet_start1(type);
405}
406
407/* Appends a character to the packet data. */
408
409void
410packet_put_char(int value)
411{
412	char ch = value;
413	buffer_append(&outgoing_packet, &ch, 1);
414}
415
416/* Appends an integer to the packet data. */
417
418void
419packet_put_int(unsigned int value)
420{
421	buffer_put_int(&outgoing_packet, value);
422}
423
424/* Appends a string to packet data. */
425
426void
427packet_put_string(const char *buf, unsigned int len)
428{
429	buffer_put_string(&outgoing_packet, buf, len);
430}
431void
432packet_put_cstring(const char *str)
433{
434	buffer_put_string(&outgoing_packet, str, strlen(str));
435}
436
437void
438packet_put_raw(const char *buf, unsigned int len)
439{
440	buffer_append(&outgoing_packet, buf, len);
441}
442
443
444/* Appends an arbitrary precision integer to packet data. */
445
446void
447packet_put_bignum(BIGNUM * value)
448{
449	buffer_put_bignum(&outgoing_packet, value);
450}
451void
452packet_put_bignum2(BIGNUM * value)
453{
454	buffer_put_bignum2(&outgoing_packet, value);
455}
456
457/*
458 * Finalizes and sends the packet.  If the encryption key has been set,
459 * encrypts the packet before sending.
460 */
461
462void
463packet_send1()
464{
465	char buf[8], *cp;
466	int i, padding, len;
467	unsigned int checksum;
468	u_int32_t rand = 0;
469
470	/*
471	 * If using packet compression, compress the payload of the outgoing
472	 * packet.
473	 */
474	if (packet_compression) {
475		buffer_clear(&compression_buffer);
476		/* Skip padding. */
477		buffer_consume(&outgoing_packet, 8);
478		/* padding */
479		buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
480		buffer_compress(&outgoing_packet, &compression_buffer);
481		buffer_clear(&outgoing_packet);
482		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
483			      buffer_len(&compression_buffer));
484	}
485	/* Compute packet length without padding (add checksum, remove padding). */
486	len = buffer_len(&outgoing_packet) + 4 - 8;
487
488	/* Insert padding. Initialized to zero in packet_start1() */
489	padding = 8 - len % 8;
490	if (cipher_type != SSH_CIPHER_NONE) {
491		cp = buffer_ptr(&outgoing_packet);
492		for (i = 0; i < padding; i++) {
493			if (i % 4 == 0)
494				rand = arc4random();
495			cp[7 - i] = rand & 0xff;
496			rand >>= 8;
497		}
498	}
499	buffer_consume(&outgoing_packet, 8 - padding);
500
501	/* Add check bytes. */
502	checksum = ssh_crc32((unsigned char *) buffer_ptr(&outgoing_packet),
503	    buffer_len(&outgoing_packet));
504	PUT_32BIT(buf, checksum);
505	buffer_append(&outgoing_packet, buf, 4);
506
507#ifdef PACKET_DEBUG
508	fprintf(stderr, "packet_send plain: ");
509	buffer_dump(&outgoing_packet);
510#endif
511
512	/* Append to output. */
513	PUT_32BIT(buf, len);
514	buffer_append(&output, buf, 4);
515	buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
516	packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
517		       buffer_len(&outgoing_packet));
518
519#ifdef PACKET_DEBUG
520	fprintf(stderr, "encrypted: ");
521	buffer_dump(&output);
522#endif
523
524	buffer_clear(&outgoing_packet);
525
526	/*
527	 * Note that the packet is now only buffered in output.  It won\'t be
528	 * actually sent until packet_write_wait or packet_write_poll is
529	 * called.
530	 */
531}
532
533/*
534 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
535 */
536void
537packet_send2()
538{
539	unsigned char *macbuf = NULL;
540	char *cp;
541	unsigned int packet_length = 0;
542	unsigned int i, padlen, len;
543	u_int32_t rand = 0;
544	static unsigned int seqnr = 0;
545	int type;
546	Enc *enc   = NULL;
547	Mac *mac   = NULL;
548	Comp *comp = NULL;
549	int block_size;
550
551	if (kex != NULL) {
552		enc  = &kex->enc[MODE_OUT];
553		mac  = &kex->mac[MODE_OUT];
554		comp = &kex->comp[MODE_OUT];
555	}
556	block_size = enc ? enc->block_size : 8;
557
558	cp = buffer_ptr(&outgoing_packet);
559	type = cp[5] & 0xff;
560
561#ifdef PACKET_DEBUG
562	fprintf(stderr, "plain:     ");
563	buffer_dump(&outgoing_packet);
564#endif
565
566	if (comp && comp->enabled) {
567		len = buffer_len(&outgoing_packet);
568		/* skip header, compress only payload */
569		buffer_consume(&outgoing_packet, 5);
570		buffer_clear(&compression_buffer);
571		buffer_compress(&outgoing_packet, &compression_buffer);
572		buffer_clear(&outgoing_packet);
573		buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
574		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
575		    buffer_len(&compression_buffer));
576		DBG(debug("compression: raw %d compressed %d", len,
577		    buffer_len(&outgoing_packet)));
578	}
579
580	/* sizeof (packet_len + pad_len + payload) */
581	len = buffer_len(&outgoing_packet);
582
583	/*
584	 * calc size of padding, alloc space, get random data,
585	 * minimum padding is 4 bytes
586	 */
587	padlen = block_size - (len % block_size);
588	if (padlen < 4)
589		padlen += block_size;
590	buffer_append_space(&outgoing_packet, &cp, padlen);
591	if (enc && enc->type != SSH_CIPHER_NONE) {
592		/* random padding */
593		for (i = 0; i < padlen; i++) {
594			if (i % 4 == 0)
595				rand = arc4random();
596			cp[i] = rand & 0xff;
597			rand <<= 8;
598		}
599	} else {
600		/* clear padding */
601		memset(cp, 0, padlen);
602	}
603	/* packet_length includes payload, padding and padding length field */
604	packet_length = buffer_len(&outgoing_packet) - 4;
605	cp = buffer_ptr(&outgoing_packet);
606	PUT_32BIT(cp, packet_length);
607	cp[4] = padlen & 0xff;
608	DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
609
610	/* compute MAC over seqnr and packet(length fields, payload, padding) */
611	if (mac && mac->enabled) {
612		macbuf = hmac( mac->md, seqnr,
613		    (unsigned char *) buffer_ptr(&outgoing_packet),
614		    buffer_len(&outgoing_packet),
615		    mac->key, mac->key_len
616		);
617		DBG(debug("done calc HMAC out #%d", seqnr));
618	}
619	/* encrypt packet and append to output buffer. */
620	buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
621	packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
622	    buffer_len(&outgoing_packet));
623	/* append unencrypted MAC */
624	if (mac && mac->enabled)
625		buffer_append(&output, (char *)macbuf, mac->mac_len);
626#ifdef PACKET_DEBUG
627	fprintf(stderr, "encrypted: ");
628	buffer_dump(&output);
629#endif
630	/* increment sequence number for outgoing packets */
631	if (++seqnr == 0)
632		log("outgoing seqnr wraps around");
633	buffer_clear(&outgoing_packet);
634
635	if (type == SSH2_MSG_NEWKEYS) {
636		if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
637			fatal("packet_send2: no KEX");
638		if (mac->md != NULL)
639			mac->enabled = 1;
640		DBG(debug("cipher_set_key_iv send_context"));
641		cipher_set_key_iv(&send_context, enc->type,
642		    enc->key, enc->key_len,
643		    enc->iv, enc->iv_len);
644		clear_enc_keys(enc, kex->we_need);
645		if (comp->type != 0 && comp->enabled == 0) {
646			comp->enabled = 1;
647			if (! packet_compression)
648				packet_start_compression(6);
649		}
650	}
651}
652
653void
654packet_send()
655{
656	if (use_ssh2_packet_format)
657		packet_send2();
658	else
659		packet_send1();
660	DBG(debug("packet_send done"));
661}
662
663/*
664 * Waits until a packet has been received, and returns its type.  Note that
665 * no other data is processed until this returns, so this function should not
666 * be used during the interactive session.
667 */
668
669int
670packet_read(int *payload_len_ptr)
671{
672	int type, len;
673	fd_set set;
674	char buf[8192];
675	DBG(debug("packet_read()"));
676
677	/* Since we are blocking, ensure that all written packets have been sent. */
678	packet_write_wait();
679
680	/* Stay in the loop until we have received a complete packet. */
681	for (;;) {
682		/* Try to read a packet from the buffer. */
683		type = packet_read_poll(payload_len_ptr);
684		if (!use_ssh2_packet_format && (
685		    type == SSH_SMSG_SUCCESS
686		    || type == SSH_SMSG_FAILURE
687		    || type == SSH_CMSG_EOF
688		    || type == SSH_CMSG_EXIT_CONFIRMATION))
689			packet_integrity_check(*payload_len_ptr, 0, type);
690		/* If we got a packet, return it. */
691		if (type != SSH_MSG_NONE)
692			return type;
693		/*
694		 * Otherwise, wait for some data to arrive, add it to the
695		 * buffer, and try again.
696		 */
697		FD_ZERO(&set);
698		FD_SET(connection_in, &set);
699
700		/* Wait for some data to arrive. */
701		select(connection_in + 1, &set, NULL, NULL, NULL);
702
703		/* Read data from the socket. */
704		len = read(connection_in, buf, sizeof(buf));
705		if (len == 0) {
706			log("Connection closed by %.200s", get_remote_ipaddr());
707			fatal_cleanup();
708		}
709		if (len < 0)
710			fatal("Read from socket failed: %.100s", strerror(errno));
711		/* Append it to the buffer. */
712		packet_process_incoming(buf, len);
713	}
714	/* NOTREACHED */
715}
716
717/*
718 * Waits until a packet has been received, verifies that its type matches
719 * that given, and gives a fatal error and exits if there is a mismatch.
720 */
721
722void
723packet_read_expect(int *payload_len_ptr, int expected_type)
724{
725	int type;
726
727	type = packet_read(payload_len_ptr);
728	if (type != expected_type)
729		packet_disconnect("Protocol error: expected packet type %d, got %d",
730		    expected_type, type);
731}
732
733/* Checks if a full packet is available in the data received so far via
734 * packet_process_incoming.  If so, reads the packet; otherwise returns
735 * SSH_MSG_NONE.  This does not wait for data from the connection.
736 *
737 * SSH_MSG_DISCONNECT is handled specially here.  Also,
738 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
739 * to higher levels.
740 *
741 * The returned payload_len does include space consumed by:
742 * 	Packet length
743 * 	Padding
744 * 	Packet type
745 * 	Check bytes
746 */
747
748int
749packet_read_poll1(int *payload_len_ptr)
750{
751	unsigned int len, padded_len;
752	unsigned char *ucp;
753	char buf[8], *cp;
754	unsigned int checksum, stored_checksum;
755
756	/* Check if input size is less than minimum packet size. */
757	if (buffer_len(&input) < 4 + 8)
758		return SSH_MSG_NONE;
759	/* Get length of incoming packet. */
760	ucp = (unsigned char *) buffer_ptr(&input);
761	len = GET_32BIT(ucp);
762	if (len < 1 + 2 + 2 || len > 256 * 1024)
763		packet_disconnect("Bad packet length %d.", len);
764	padded_len = (len + 8) & ~7;
765
766	/* Check if the packet has been entirely received. */
767	if (buffer_len(&input) < 4 + padded_len)
768		return SSH_MSG_NONE;
769
770	/* The entire packet is in buffer. */
771
772	/* Consume packet length. */
773	buffer_consume(&input, 4);
774
775	/* Copy data to incoming_packet. */
776	buffer_clear(&incoming_packet);
777	buffer_append_space(&incoming_packet, &cp, padded_len);
778	packet_decrypt(&receive_context, cp, buffer_ptr(&input), padded_len);
779	buffer_consume(&input, padded_len);
780
781#ifdef PACKET_DEBUG
782	fprintf(stderr, "read_poll plain: ");
783	buffer_dump(&incoming_packet);
784#endif
785
786	/* Compute packet checksum. */
787	checksum = ssh_crc32((unsigned char *) buffer_ptr(&incoming_packet),
788	    buffer_len(&incoming_packet) - 4);
789
790	/* Skip padding. */
791	buffer_consume(&incoming_packet, 8 - len % 8);
792
793	/* Test check bytes. */
794
795	if (len != buffer_len(&incoming_packet))
796		packet_disconnect("packet_read_poll: len %d != buffer_len %d.",
797		    len, buffer_len(&incoming_packet));
798
799	ucp = (unsigned char *) buffer_ptr(&incoming_packet) + len - 4;
800	stored_checksum = GET_32BIT(ucp);
801	if (checksum != stored_checksum)
802		packet_disconnect("Corrupted check bytes on input.");
803	buffer_consume_end(&incoming_packet, 4);
804
805	/* If using packet compression, decompress the packet. */
806	if (packet_compression) {
807		buffer_clear(&compression_buffer);
808		buffer_uncompress(&incoming_packet, &compression_buffer);
809		buffer_clear(&incoming_packet);
810		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
811		    buffer_len(&compression_buffer));
812	}
813	/* Get packet type. */
814	buffer_get(&incoming_packet, &buf[0], 1);
815
816	/* Return length of payload (without type field). */
817	*payload_len_ptr = buffer_len(&incoming_packet);
818
819	/* Return type. */
820	return (unsigned char) buf[0];
821}
822
823int
824packet_read_poll2(int *payload_len_ptr)
825{
826	unsigned int padlen, need;
827	unsigned char buf[8], *macbuf;
828	unsigned char *ucp;
829	char *cp;
830	static unsigned int packet_length = 0;
831	static unsigned int seqnr = 0;
832	int type;
833	int maclen, block_size;
834	Enc *enc   = NULL;
835	Mac *mac   = NULL;
836	Comp *comp = NULL;
837
838	if (kex != NULL) {
839		enc  = &kex->enc[MODE_IN];
840		mac  = &kex->mac[MODE_IN];
841		comp = &kex->comp[MODE_IN];
842	}
843	maclen = mac && mac->enabled ? mac->mac_len : 0;
844	block_size = enc ? enc->block_size : 8;
845
846	if (packet_length == 0) {
847		/*
848		 * check if input size is less than the cipher block size,
849		 * decrypt first block and extract length of incoming packet
850		 */
851		if (buffer_len(&input) < block_size)
852			return SSH_MSG_NONE;
853		buffer_clear(&incoming_packet);
854		buffer_append_space(&incoming_packet, &cp, block_size);
855		packet_decrypt(&receive_context, cp, buffer_ptr(&input),
856		    block_size);
857		ucp = (unsigned char *) buffer_ptr(&incoming_packet);
858		packet_length = GET_32BIT(ucp);
859		if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
860			buffer_dump(&incoming_packet);
861			packet_disconnect("Bad packet length %d.", packet_length);
862		}
863		DBG(debug("input: packet len %d", packet_length+4));
864		buffer_consume(&input, block_size);
865	}
866	/* we have a partial packet of block_size bytes */
867	need = 4 + packet_length - block_size;
868	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
869	    need, maclen));
870	if (need % block_size != 0)
871		fatal("padding error: need %d block %d mod %d",
872		    need, block_size, need % block_size);
873	/*
874	 * check if the entire packet has been received and
875	 * decrypt into incoming_packet
876	 */
877	if (buffer_len(&input) < need + maclen)
878		return SSH_MSG_NONE;
879#ifdef PACKET_DEBUG
880	fprintf(stderr, "read_poll enc/full: ");
881	buffer_dump(&input);
882#endif
883	buffer_append_space(&incoming_packet, &cp, need);
884	packet_decrypt(&receive_context, cp, buffer_ptr(&input), need);
885	buffer_consume(&input, need);
886	/*
887	 * compute MAC over seqnr and packet,
888	 * increment sequence number for incoming packet
889	 */
890	if (mac && mac->enabled) {
891		macbuf = hmac( mac->md, seqnr,
892		    (unsigned char *) buffer_ptr(&incoming_packet),
893		    buffer_len(&incoming_packet),
894		    mac->key, mac->key_len
895		);
896		if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
897			packet_disconnect("Corrupted HMAC on input.");
898		DBG(debug("HMAC #%d ok", seqnr));
899		buffer_consume(&input, mac->mac_len);
900	}
901	if (++seqnr == 0)
902		log("incoming seqnr wraps around");
903
904	/* get padlen */
905	cp = buffer_ptr(&incoming_packet) + 4;
906	padlen = *cp & 0xff;
907	DBG(debug("input: padlen %d", padlen));
908	if (padlen < 4)
909		packet_disconnect("Corrupted padlen %d on input.", padlen);
910
911	/* skip packet size + padlen, discard padding */
912	buffer_consume(&incoming_packet, 4 + 1);
913	buffer_consume_end(&incoming_packet, padlen);
914
915	DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
916	if (comp && comp->enabled) {
917		buffer_clear(&compression_buffer);
918		buffer_uncompress(&incoming_packet, &compression_buffer);
919		buffer_clear(&incoming_packet);
920		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
921		    buffer_len(&compression_buffer));
922		DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
923	}
924	/*
925	 * get packet type, implies consume.
926	 * return length of payload (without type field)
927	 */
928	buffer_get(&incoming_packet, (char *)&buf[0], 1);
929	*payload_len_ptr = buffer_len(&incoming_packet);
930
931	/* reset for next packet */
932	packet_length = 0;
933
934	/* extract packet type */
935	type = (unsigned char)buf[0];
936
937	if (type == SSH2_MSG_NEWKEYS) {
938		if (kex==NULL || mac==NULL || enc==NULL || comp==NULL)
939			fatal("packet_read_poll2: no KEX");
940		if (mac->md != NULL)
941			mac->enabled = 1;
942		DBG(debug("cipher_set_key_iv receive_context"));
943		cipher_set_key_iv(&receive_context, enc->type,
944		    enc->key, enc->key_len,
945		    enc->iv, enc->iv_len);
946		clear_enc_keys(enc, kex->we_need);
947		if (comp->type != 0 && comp->enabled == 0) {
948			comp->enabled = 1;
949			if (! packet_compression)
950				packet_start_compression(6);
951		}
952	}
953
954#ifdef PACKET_DEBUG
955	fprintf(stderr, "read/plain[%d]:\r\n",type);
956	buffer_dump(&incoming_packet);
957#endif
958	return (unsigned char)type;
959}
960
961int
962packet_read_poll(int *payload_len_ptr)
963{
964	char *msg;
965	for (;;) {
966		int type = use_ssh2_packet_format ?
967		    packet_read_poll2(payload_len_ptr):
968		    packet_read_poll1(payload_len_ptr);
969
970		if(compat20) {
971			int reason;
972			if (type != 0)
973				DBG(debug("received packet type %d", type));
974			switch(type) {
975			case SSH2_MSG_IGNORE:
976				break;
977			case SSH2_MSG_DEBUG:
978				packet_get_char();
979				msg = packet_get_string(NULL);
980				debug("Remote: %.900s", msg);
981				xfree(msg);
982				msg = packet_get_string(NULL);
983				xfree(msg);
984				break;
985			case SSH2_MSG_DISCONNECT:
986				reason = packet_get_int();
987				msg = packet_get_string(NULL);
988				log("Received disconnect: %d: %.900s", reason, msg);
989				xfree(msg);
990				fatal_cleanup();
991				break;
992			default:
993				return type;
994				break;
995			}
996		} else {
997			switch(type) {
998			case SSH_MSG_IGNORE:
999				break;
1000			case SSH_MSG_DEBUG:
1001				msg = packet_get_string(NULL);
1002				debug("Remote: %.900s", msg);
1003				xfree(msg);
1004				break;
1005			case SSH_MSG_DISCONNECT:
1006				msg = packet_get_string(NULL);
1007				log("Received disconnect: %.900s", msg);
1008				fatal_cleanup();
1009				xfree(msg);
1010				break;
1011			default:
1012				if (type != 0)
1013					DBG(debug("received packet type %d", type));
1014				return type;
1015				break;
1016			}
1017		}
1018	}
1019}
1020
1021/*
1022 * Buffers the given amount of input characters.  This is intended to be used
1023 * together with packet_read_poll.
1024 */
1025
1026void
1027packet_process_incoming(const char *buf, unsigned int len)
1028{
1029	buffer_append(&input, buf, len);
1030}
1031
1032/* Returns a character from the packet. */
1033
1034unsigned int
1035packet_get_char()
1036{
1037	char ch;
1038	buffer_get(&incoming_packet, &ch, 1);
1039	return (unsigned char) ch;
1040}
1041
1042/* Returns an integer from the packet data. */
1043
1044unsigned int
1045packet_get_int()
1046{
1047	return buffer_get_int(&incoming_packet);
1048}
1049
1050/*
1051 * Returns an arbitrary precision integer from the packet data.  The integer
1052 * must have been initialized before this call.
1053 */
1054
1055void
1056packet_get_bignum(BIGNUM * value, int *length_ptr)
1057{
1058	*length_ptr = buffer_get_bignum(&incoming_packet, value);
1059}
1060
1061void
1062packet_get_bignum2(BIGNUM * value, int *length_ptr)
1063{
1064	*length_ptr = buffer_get_bignum2(&incoming_packet, value);
1065}
1066
1067char *
1068packet_get_raw(int *length_ptr)
1069{
1070	int bytes = buffer_len(&incoming_packet);
1071	if (length_ptr != NULL)
1072		*length_ptr = bytes;
1073	return buffer_ptr(&incoming_packet);
1074}
1075
1076int
1077packet_remaining(void)
1078{
1079	return buffer_len(&incoming_packet);
1080}
1081
1082/*
1083 * Returns a string from the packet data.  The string is allocated using
1084 * xmalloc; it is the responsibility of the calling program to free it when
1085 * no longer needed.  The length_ptr argument may be NULL, or point to an
1086 * integer into which the length of the string is stored.
1087 */
1088
1089char *
1090packet_get_string(unsigned int *length_ptr)
1091{
1092	return buffer_get_string(&incoming_packet, length_ptr);
1093}
1094
1095/*
1096 * Sends a diagnostic message from the server to the client.  This message
1097 * can be sent at any time (but not while constructing another message). The
1098 * message is printed immediately, but only if the client is being executed
1099 * in verbose mode.  These messages are primarily intended to ease debugging
1100 * authentication problems.   The length of the formatted message must not
1101 * exceed 1024 bytes.  This will automatically call packet_write_wait.
1102 */
1103
1104void
1105packet_send_debug(const char *fmt,...)
1106{
1107	char buf[1024];
1108	va_list args;
1109
1110	va_start(args, fmt);
1111	vsnprintf(buf, sizeof(buf), fmt, args);
1112	va_end(args);
1113
1114	if (compat20) {
1115		packet_start(SSH2_MSG_DEBUG);
1116		packet_put_char(0);	/* bool: always display */
1117		packet_put_cstring(buf);
1118		packet_put_cstring("");
1119	} else {
1120		packet_start(SSH_MSG_DEBUG);
1121		packet_put_cstring(buf);
1122	}
1123	packet_send();
1124	packet_write_wait();
1125}
1126
1127/*
1128 * Logs the error plus constructs and sends a disconnect packet, closes the
1129 * connection, and exits.  This function never returns. The error message
1130 * should not contain a newline.  The length of the formatted message must
1131 * not exceed 1024 bytes.
1132 */
1133
1134void
1135packet_disconnect(const char *fmt,...)
1136{
1137	char buf[1024];
1138	va_list args;
1139	static int disconnecting = 0;
1140	if (disconnecting)	/* Guard against recursive invocations. */
1141		fatal("packet_disconnect called recursively.");
1142	disconnecting = 1;
1143
1144	/*
1145	 * Format the message.  Note that the caller must make sure the
1146	 * message is of limited size.
1147	 */
1148	va_start(args, fmt);
1149	vsnprintf(buf, sizeof(buf), fmt, args);
1150	va_end(args);
1151
1152	/* Send the disconnect message to the other side, and wait for it to get sent. */
1153	if (compat20) {
1154		packet_start(SSH2_MSG_DISCONNECT);
1155		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1156		packet_put_cstring(buf);
1157		packet_put_cstring("");
1158	} else {
1159		packet_start(SSH_MSG_DISCONNECT);
1160		packet_put_string(buf, strlen(buf));
1161	}
1162	packet_send();
1163	packet_write_wait();
1164
1165	/* Stop listening for connections. */
1166	channel_stop_listening();
1167
1168	/* Close the connection. */
1169	packet_close();
1170
1171	/* Display the error locally and exit. */
1172	log("Disconnecting: %.100s", buf);
1173	fatal_cleanup();
1174}
1175
1176/* Checks if there is any buffered output, and tries to write some of the output. */
1177
1178void
1179packet_write_poll()
1180{
1181	int len = buffer_len(&output);
1182	if (len > 0) {
1183		len = write(connection_out, buffer_ptr(&output), len);
1184		if (len <= 0) {
1185			if (errno == EAGAIN)
1186				return;
1187			else
1188				fatal("Write failed: %.100s", strerror(errno));
1189		}
1190		buffer_consume(&output, len);
1191	}
1192}
1193
1194/*
1195 * Calls packet_write_poll repeatedly until all pending output data has been
1196 * written.
1197 */
1198
1199void
1200packet_write_wait()
1201{
1202	packet_write_poll();
1203	while (packet_have_data_to_write()) {
1204		fd_set set;
1205		FD_ZERO(&set);
1206		FD_SET(connection_out, &set);
1207		select(connection_out + 1, NULL, &set, NULL, NULL);
1208		packet_write_poll();
1209	}
1210}
1211
1212/* Returns true if there is buffered data to write to the connection. */
1213
1214int
1215packet_have_data_to_write()
1216{
1217	return buffer_len(&output) != 0;
1218}
1219
1220/* Returns true if there is not too much data to write to the connection. */
1221
1222int
1223packet_not_very_much_data_to_write()
1224{
1225	if (interactive_mode)
1226		return buffer_len(&output) < 16384;
1227	else
1228		return buffer_len(&output) < 128 * 1024;
1229}
1230
1231/* Informs that the current session is interactive.  Sets IP flags for that. */
1232
1233void
1234packet_set_interactive(int interactive, int keepalives)
1235{
1236	int on = 1;
1237
1238	/* Record that we are in interactive mode. */
1239	interactive_mode = interactive;
1240
1241	/* Only set socket options if using a socket.  */
1242	if (!packet_connection_is_on_socket())
1243		return;
1244	if (keepalives) {
1245		/* Set keepalives if requested. */
1246		if (setsockopt(connection_in, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,
1247		    sizeof(on)) < 0)
1248			error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1249	}
1250	/*
1251	 * IPTOS_LOWDELAY, TCP_NODELAY and IPTOS_THROUGHPUT are IPv4 only
1252	 */
1253	if (!packet_connection_is_ipv4())
1254		return;
1255	if (interactive) {
1256		/*
1257		 * Set IP options for an interactive connection.  Use
1258		 * IPTOS_LOWDELAY and TCP_NODELAY.
1259		 */
1260		int lowdelay = IPTOS_LOWDELAY;
1261		if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &lowdelay,
1262		    sizeof(lowdelay)) < 0)
1263			error("setsockopt IPTOS_LOWDELAY: %.100s", strerror(errno));
1264		if (setsockopt(connection_in, IPPROTO_TCP, TCP_NODELAY, (void *) &on,
1265		    sizeof(on)) < 0)
1266			error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
1267	} else {
1268		/*
1269		 * Set IP options for a non-interactive connection.  Use
1270		 * IPTOS_THROUGHPUT.
1271		 */
1272		int throughput = IPTOS_THROUGHPUT;
1273		if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &throughput,
1274		    sizeof(throughput)) < 0)
1275			error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1276	}
1277}
1278
1279/* Returns true if the current connection is interactive. */
1280
1281int
1282packet_is_interactive()
1283{
1284	return interactive_mode;
1285}
1286
1287int
1288packet_set_maxsize(int s)
1289{
1290	static int called = 0;
1291	if (called) {
1292		log("packet_set_maxsize: called twice: old %d new %d",
1293		    max_packet_size, s);
1294		return -1;
1295	}
1296	if (s < 4 * 1024 || s > 1024 * 1024) {
1297		log("packet_set_maxsize: bad size %d", s);
1298		return -1;
1299	}
1300	log("packet_set_maxsize: setting to %d", s);
1301	max_packet_size = s;
1302	return s;
1303}
1304