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