packet.c revision 92555
1139804Simp/*
2116660Siedowse * Author: Tatu Ylonen <ylo@cs.hut.fi>
3116660Siedowse * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4116660Siedowse *                    All rights reserved
5116660Siedowse * This file contains code implementing the packet protocol and communication
6116660Siedowse * with the other side.  This same code is used both on client and server side.
7116660Siedowse *
8116660Siedowse * As far as I am concerned, the code I have written for this software
9116660Siedowse * can be used freely for any purpose.  Any derived versions of this
10116660Siedowse * software must be clearly marked as such, and if the derived work is
11116660Siedowse * incompatible with the protocol description in the RFC file, it must be
12116660Siedowse * called by a name other than "ssh" or "Secure Shell".
13116660Siedowse *
14116660Siedowse *
15116660Siedowse * SSH2 packet format added by Markus Friedl.
16116660Siedowse * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
17116660Siedowse *
18116660Siedowse * Redistribution and use in source and binary forms, with or without
19116660Siedowse * modification, are permitted provided that the following conditions
20116660Siedowse * are met:
21116660Siedowse * 1. Redistributions of source code must retain the above copyright
22116660Siedowse *    notice, this list of conditions and the following disclaimer.
23116660Siedowse * 2. Redistributions in binary form must reproduce the above copyright
24116660Siedowse *    notice, this list of conditions and the following disclaimer in the
25116660Siedowse *    documentation and/or other materials provided with the distribution.
26116660Siedowse *
27116660Siedowse * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28116660Siedowse * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29116660Siedowse * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30116660Siedowse * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31116660Siedowse * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32116660Siedowse * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33116660Siedowse * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34222537Sken * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35234075Seadler * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36222537Sken * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37116660Siedowse */
38234075Seadler
39116660Siedowse#include "includes.h"
40222537SkenRCSID("$OpenBSD: packet.c,v 1.90 2002/02/27 21:23:13 stevesk Exp $");
41222537Sken
42222537Sken#include "xmalloc.h"
43222537Sken#include "buffer.h"
44222537Sken#include "packet.h"
45222537Sken#include "bufaux.h"
46116660Siedowse#include "crc32.h"
47116660Siedowse#include "getput.h"
48116660Siedowse
49116660Siedowse#include "compress.h"
50116660Siedowse#include "deattack.h"
51116660Siedowse#include "channels.h"
52234075Seadler
53234075Seadler#include "compat.h"
54234075Seadler#include "ssh1.h"
55234075Seadler#include "ssh2.h"
56234075Seadler
57234075Seadler#include "cipher.h"
58234075Seadler#include "kex.h"
59234075Seadler#include "mac.h"
60234075Seadler#include "log.h"
61116660Siedowse#include "canohost.h"
62116660Siedowse#include "misc.h"
63116660Siedowse
64116660Siedowse#ifdef PACKET_DEBUG
65116660Siedowse#define DBG(x) x
66116660Siedowse#else
67116660Siedowse#define DBG(x)
68116660Siedowse#endif
69116660Siedowse
70116660Siedowse/*
71116660Siedowse * This variable contains the file descriptors used for communicating with
72116660Siedowse * the other side.  connection_in is used for reading; connection_out for
73222537Sken * writing.  These can be the same descriptor, in which case it is assumed to
74234075Seadler * be a socket.
75222550Sken */
76222537Skenstatic int connection_in = -1;
77116660Siedowsestatic int connection_out = -1;
78116660Siedowse
79116660Siedowse/* Protocol flags for the remote side. */
80116660Siedowsestatic u_int remote_protocol_flags = 0;
81116660Siedowse
82116660Siedowse/* Encryption context for receiving data.  This is only used for decryption. */
83116660Siedowsestatic CipherContext receive_context;
84116660Siedowse
85116660Siedowse/* Encryption context for sending data.  This is only used for encryption. */
86116660Siedowsestatic CipherContext send_context;
87116660Siedowse
88116660Siedowse/* Buffer for raw input data from the socket. */
89116660Siedowsestatic Buffer input;
90116660Siedowse
91116660Siedowse/* Buffer for raw output data going to the socket. */
92116660Siedowsestatic Buffer output;
93116660Siedowse
94116660Siedowse/* Buffer for the partial outgoing packet being constructed. */
95116660Siedowsestatic Buffer outgoing_packet;
96116660Siedowse
97116660Siedowse/* Buffer for the incoming packet currently being processed. */
98116660Siedowsestatic Buffer incoming_packet;
99119765Sphk
100119765Sphk/* Scratch buffer for packet compression/decompression. */
101119765Sphkstatic Buffer compression_buffer;
102119765Sphkstatic int compression_buffer_ready = 0;
103119765Sphk
104116660Siedowse/* Flag indicating whether packet compression/decompression is enabled. */
105116660Siedowsestatic int packet_compression = 0;
106222537Sken
107222537Sken/* default maximum packet size */
108222537Skenint max_packet_size = 32768;
109234075Seadler
110222550Sken/* Flag indicating whether this module has been initialized. */
111222537Skenstatic int initialized = 0;
112116660Siedowse
113116660Siedowse/* Set to true if the connection is interactive. */
114116660Siedowsestatic int interactive_mode = 0;
115116660Siedowse
116116660Siedowse/* Session key information for Encryption and MAC */
117116660SiedowseNewkeys *newkeys[MODE_MAX];
118116660Siedowse
119116660Siedowse/* roundup current message to extra_pad bytes */
120116660Siedowsestatic u_char extra_pad = 0;
121116660Siedowse
122116660Siedowse/*
123116660Siedowse * Sets the descriptors used for communication.  Disables encryption until
124116660Siedowse * packet_set_encryption_key is called.
125116660Siedowse */
126116660Siedowsevoid
127116660Siedowsepacket_set_connection(int fd_in, int fd_out)
128116660Siedowse{
129116660Siedowse	Cipher *none = cipher_by_name("none");
130116660Siedowse	if (none == NULL)
131116660Siedowse		fatal("packet_set_connection: cannot load cipher 'none'");
132116660Siedowse	connection_in = fd_in;
133116660Siedowse	connection_out = fd_out;
134116660Siedowse	cipher_init(&send_context, none, "", 0, NULL, 0, CIPHER_ENCRYPT);
135116660Siedowse	cipher_init(&receive_context, none, "", 0, NULL, 0, CIPHER_DECRYPT);
136116660Siedowse	newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
137116660Siedowse	if (!initialized) {
138116660Siedowse		initialized = 1;
139116660Siedowse		buffer_init(&input);
140116660Siedowse		buffer_init(&output);
141116660Siedowse		buffer_init(&outgoing_packet);
142222537Sken		buffer_init(&incoming_packet);
143222537Sken	}
144222537Sken	/* Kludge: arrange the close function to be called from fatal(). */
145222537Sken	fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
146116660Siedowse}
147234075Seadler
148234075Seadler/* Returns 1 if remote host is connected via socket, 0 if not. */
149234075Seadler
150222537Skenint
151222537Skenpacket_connection_is_on_socket(void)
152222537Sken{
153222537Sken	struct sockaddr_storage from, to;
154222537Sken	socklen_t fromlen, tolen;
155234075Seadler
156222537Sken	/* filedescriptors in and out are the same, so it's a socket */
157222537Sken	if (connection_in == connection_out)
158222537Sken		return 1;
159222537Sken	fromlen = sizeof(from);
160222537Sken	memset(&from, 0, sizeof(from));
161222537Sken	if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
162222537Sken		return 0;
163222537Sken	tolen = sizeof(to);
164116660Siedowse	memset(&to, 0, sizeof(to));
165116660Siedowse	if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
166116660Siedowse		return 0;
167222537Sken	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
168116660Siedowse		return 0;
169222537Sken	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
170222537Sken		return 0;
171222537Sken	return 1;
172116660Siedowse}
173116660Siedowse
174116660Siedowse/* returns 1 if connection is via ipv4 */
175222537Sken
176222537Skenint
177222537Skenpacket_connection_is_ipv4(void)
178222537Sken{
179222537Sken	struct sockaddr_storage to;
180222537Sken	socklen_t tolen = sizeof(to);
181222537Sken
182222537Sken	memset(&to, 0, sizeof(to));
183222537Sken	if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
184222537Sken		return 0;
185222537Sken	if (to.ss_family != AF_INET)
186222537Sken		return 0;
187222537Sken	return 1;
188234075Seadler}
189234075Seadler
190222537Sken/* Sets the connection into non-blocking mode. */
191222537Sken
192222537Skenvoid
193222537Skenpacket_set_nonblocking(void)
194222537Sken{
195222537Sken	/* Set the socket into non-blocking mode. */
196222537Sken	if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
197222537Sken		error("fcntl O_NONBLOCK: %.100s", strerror(errno));
198222537Sken
199222537Sken	if (connection_out != connection_in) {
200222537Sken		if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
201222537Sken			error("fcntl O_NONBLOCK: %.100s", strerror(errno));
202222537Sken	}
203222537Sken}
204222537Sken
205222537Sken/* Returns the socket used for reading. */
206222537Sken
207222537Skenint
208222537Skenpacket_get_connection_in(void)
209222537Sken{
210222537Sken	return connection_in;
211222537Sken}
212222537Sken
213222537Sken/* Returns the descriptor used for writing. */
214222537Sken
215222537Skenint
216222537Skenpacket_get_connection_out(void)
217222537Sken{
218222537Sken	return connection_out;
219222537Sken}
220234075Seadler
221222537Sken/* Closes the connection and clears and frees internal data structures. */
222222537Sken
223234075Seadlervoid
224222537Skenpacket_close(void)
225222537Sken{
226234075Seadler	if (!initialized)
227222537Sken		return;
228222537Sken	initialized = 0;
229222537Sken	if (connection_in == connection_out) {
230222537Sken		shutdown(connection_out, SHUT_RDWR);
231222537Sken		close(connection_out);
232222537Sken	} else {
233234075Seadler		close(connection_in);
234222537Sken		close(connection_out);
235222537Sken	}
236222537Sken	buffer_free(&input);
237222537Sken	buffer_free(&output);
238222537Sken	buffer_free(&outgoing_packet);
239222537Sken	buffer_free(&incoming_packet);
240234075Seadler	if (compression_buffer_ready) {
241234075Seadler		buffer_free(&compression_buffer);
242234075Seadler		buffer_compress_uninit();
243234075Seadler	}
244234075Seadler	cipher_cleanup(&send_context);
245234075Seadler	cipher_cleanup(&receive_context);
246234075Seadler}
247234075Seadler
248234075Seadler/* Sets remote side protocol flags. */
249234075Seadler
250222537Skenvoid
251222537Skenpacket_set_protocol_flags(u_int protocol_flags)
252222537Sken{
253222537Sken	remote_protocol_flags = protocol_flags;
254222537Sken}
255222537Sken
256222537Sken/* Returns the remote protocol flags set earlier by the above function. */
257222537Sken
258222537Skenu_int
259222537Skenpacket_get_protocol_flags(void)
260222537Sken{
261222537Sken	return remote_protocol_flags;
262222537Sken}
263222537Sken
264222537Sken/*
265222537Sken * Starts packet compression from the next packet on in both directions.
266234075Seadler * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
267222537Sken */
268234075Seadler
269222537Skenstatic void
270222537Skenpacket_init_compression(void)
271222537Sken{
272222537Sken	if (compression_buffer_ready == 1)
273222537Sken		return;
274222537Sken	compression_buffer_ready = 1;
275222537Sken	buffer_init(&compression_buffer);
276222537Sken}
277222537Sken
278222537Skenvoid
279222537Skenpacket_start_compression(int level)
280222537Sken{
281222537Sken	if (packet_compression && !compat20)
282222537Sken		fatal("Compression already enabled.");
283222537Sken	packet_compression = 1;
284222537Sken	packet_init_compression();
285222537Sken	buffer_compress_init_send(level);
286222537Sken	buffer_compress_init_recv();
287222537Sken}
288222537Sken
289116660Siedowse/*
290116660Siedowse * Causes any further packets to be encrypted using the given key.  The same
291116660Siedowse * key is used for both sending and reception.  However, both directions are
292116660Siedowse * encrypted independently of each other.
293116660Siedowse */
294116660Siedowsevoid
295116660Siedowsepacket_set_encryption_key(const u_char *key, u_int keylen,
296116660Siedowse    int number)
297116660Siedowse{
298222537Sken	Cipher *cipher = cipher_by_number(number);
299222537Sken	if (cipher == NULL)
300116660Siedowse		fatal("packet_set_encryption_key: unknown cipher number %d", number);
301116660Siedowse	if (keylen < 20)
302222537Sken		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
303222537Sken	cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
304116660Siedowse	cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
305222537Sken}
306116660Siedowse
307116660Siedowse/* Start constructing a packet to send. */
308116660Siedowsevoid
309116660Siedowsepacket_start(u_char type)
310222537Sken{
311222537Sken	u_char buf[9];
312222537Sken	int len;
313116660Siedowse
314116660Siedowse	DBG(debug("packet_start[%d]", type));
315116660Siedowse	len = compat20 ? 6 : 9;
316116660Siedowse	memset(buf, 0, len - 1);
317116660Siedowse	buf[len - 1] = type;
318116660Siedowse	buffer_clear(&outgoing_packet);
319116660Siedowse	buffer_append(&outgoing_packet, buf, len);
320116660Siedowse}
321116660Siedowse
322116660Siedowse/* Append payload. */
323116660Siedowsevoid
324116660Siedowsepacket_put_char(int value)
325222537Sken{
326222537Sken	char ch = value;
327116660Siedowse	buffer_append(&outgoing_packet, &ch, 1);
328116660Siedowse}
329222537Skenvoid
330222537Skenpacket_put_int(u_int value)
331116660Siedowse{
332222537Sken	buffer_put_int(&outgoing_packet, value);
333116660Siedowse}
334116660Siedowsevoid
335116660Siedowsepacket_put_string(const void *buf, u_int len)
336116660Siedowse{
337116660Siedowse	buffer_put_string(&outgoing_packet, buf, len);
338116660Siedowse}
339116660Siedowsevoid
340116660Siedowsepacket_put_cstring(const char *str)
341116660Siedowse{
342116660Siedowse	buffer_put_cstring(&outgoing_packet, str);
343222537Sken}
344222537Skenvoid
345222537Skenpacket_put_raw(const void *buf, u_int len)
346116660Siedowse{
347116660Siedowse	buffer_append(&outgoing_packet, buf, len);
348116660Siedowse}
349116660Siedowsevoid
350116660Siedowsepacket_put_bignum(BIGNUM * value)
351116660Siedowse{
352116660Siedowse	buffer_put_bignum(&outgoing_packet, value);
353116660Siedowse}
354116660Siedowsevoid
355116660Siedowsepacket_put_bignum2(BIGNUM * value)
356116660Siedowse{
357116660Siedowse	buffer_put_bignum2(&outgoing_packet, value);
358116660Siedowse}
359116660Siedowse
360116660Siedowse/*
361116660Siedowse * Finalizes and sends the packet.  If the encryption key has been set,
362116660Siedowse * encrypts the packet before sending.
363116660Siedowse */
364222537Sken
365222537Skenstatic void
366116660Siedowsepacket_send1(void)
367116660Siedowse{
368116660Siedowse	u_char buf[8], *cp;
369222537Sken	int i, padding, len;
370116660Siedowse	u_int checksum;
371116660Siedowse	u_int32_t rand = 0;
372116660Siedowse
373116660Siedowse	/*
374116660Siedowse	 * If using packet compression, compress the payload of the outgoing
375222537Sken	 * packet.
376222537Sken	 */
377116660Siedowse	if (packet_compression) {
378222537Sken		buffer_clear(&compression_buffer);
379116660Siedowse		/* Skip padding. */
380116660Siedowse		buffer_consume(&outgoing_packet, 8);
381116660Siedowse		/* padding */
382116660Siedowse		buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
383116660Siedowse		buffer_compress(&outgoing_packet, &compression_buffer);
384116660Siedowse		buffer_clear(&outgoing_packet);
385116660Siedowse		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
386116660Siedowse		    buffer_len(&compression_buffer));
387116660Siedowse	}
388222537Sken	/* Compute packet length without padding (add checksum, remove padding). */
389222537Sken	len = buffer_len(&outgoing_packet) + 4 - 8;
390222537Sken
391116660Siedowse	/* Insert padding. Initialized to zero in packet_start1() */
392116660Siedowse	padding = 8 - len % 8;
393116660Siedowse	if (!send_context.plaintext) {
394116660Siedowse		cp = buffer_ptr(&outgoing_packet);
395116660Siedowse		for (i = 0; i < padding; i++) {
396116660Siedowse			if (i % 4 == 0)
397116660Siedowse				rand = arc4random();
398116660Siedowse			cp[7 - i] = rand & 0xff;
399116660Siedowse			rand >>= 8;
400116660Siedowse		}
401116660Siedowse	}
402116660Siedowse	buffer_consume(&outgoing_packet, 8 - padding);
403116660Siedowse
404116660Siedowse	/* Add check bytes. */
405116660Siedowse	checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
406116660Siedowse	    buffer_len(&outgoing_packet));
407116660Siedowse	PUT_32BIT(buf, checksum);
408116660Siedowse	buffer_append(&outgoing_packet, buf, 4);
409116660Siedowse
410116660Siedowse#ifdef PACKET_DEBUG
411116660Siedowse	fprintf(stderr, "packet_send plain: ");
412116660Siedowse	buffer_dump(&outgoing_packet);
413116660Siedowse#endif
414116660Siedowse
415116660Siedowse	/* Append to output. */
416116660Siedowse	PUT_32BIT(buf, len);
417116660Siedowse	buffer_append(&output, buf, 4);
418116660Siedowse	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
419	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
420	    buffer_len(&outgoing_packet));
421
422#ifdef PACKET_DEBUG
423	fprintf(stderr, "encrypted: ");
424	buffer_dump(&output);
425#endif
426
427	buffer_clear(&outgoing_packet);
428
429	/*
430	 * Note that the packet is now only buffered in output.  It won\'t be
431	 * actually sent until packet_write_wait or packet_write_poll is
432	 * called.
433	 */
434}
435
436static void
437set_newkeys(int mode)
438{
439	Enc *enc;
440	Mac *mac;
441	Comp *comp;
442	CipherContext *cc;
443	int encrypt;
444
445	debug("newkeys: mode %d", mode);
446
447	if (mode == MODE_OUT) {
448		cc = &send_context;
449		encrypt = CIPHER_ENCRYPT;
450	} else {
451		cc = &receive_context;
452		encrypt = CIPHER_DECRYPT;
453	}
454	if (newkeys[mode] != NULL) {
455		debug("newkeys: rekeying");
456		cipher_cleanup(cc);
457		enc  = &newkeys[mode]->enc;
458		mac  = &newkeys[mode]->mac;
459		comp = &newkeys[mode]->comp;
460		memset(mac->key, 0, mac->key_len);
461		xfree(enc->name);
462		xfree(enc->iv);
463		xfree(enc->key);
464		xfree(mac->name);
465		xfree(mac->key);
466		xfree(comp->name);
467		xfree(newkeys[mode]);
468	}
469	newkeys[mode] = kex_get_newkeys(mode);
470	if (newkeys[mode] == NULL)
471		fatal("newkeys: no keys for mode %d", mode);
472	enc  = &newkeys[mode]->enc;
473	mac  = &newkeys[mode]->mac;
474	comp = &newkeys[mode]->comp;
475	if (mac->md != NULL)
476		mac->enabled = 1;
477	DBG(debug("cipher_init_context: %d", mode));
478	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
479	    enc->iv, enc->block_size, encrypt);
480	memset(enc->iv,  0, enc->block_size);
481	memset(enc->key, 0, enc->key_len);
482	if (comp->type != 0 && comp->enabled == 0) {
483		packet_init_compression();
484		if (mode == MODE_OUT)
485			buffer_compress_init_send(6);
486		else
487			buffer_compress_init_recv();
488		comp->enabled = 1;
489	}
490}
491
492/*
493 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
494 */
495static void
496packet_send2(void)
497{
498	static u_int32_t seqnr = 0;
499	u_char type, *cp, *macbuf = NULL;
500	u_char padlen, pad;
501	u_int packet_length = 0;
502	u_int i, len;
503	u_int32_t rand = 0;
504	Enc *enc   = NULL;
505	Mac *mac   = NULL;
506	Comp *comp = NULL;
507	int block_size;
508
509	if (newkeys[MODE_OUT] != NULL) {
510		enc  = &newkeys[MODE_OUT]->enc;
511		mac  = &newkeys[MODE_OUT]->mac;
512		comp = &newkeys[MODE_OUT]->comp;
513	}
514	block_size = enc ? enc->block_size : 8;
515
516	cp = buffer_ptr(&outgoing_packet);
517	type = cp[5];
518
519#ifdef PACKET_DEBUG
520	fprintf(stderr, "plain:     ");
521	buffer_dump(&outgoing_packet);
522#endif
523
524	if (comp && comp->enabled) {
525		len = buffer_len(&outgoing_packet);
526		/* skip header, compress only payload */
527		buffer_consume(&outgoing_packet, 5);
528		buffer_clear(&compression_buffer);
529		buffer_compress(&outgoing_packet, &compression_buffer);
530		buffer_clear(&outgoing_packet);
531		buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
532		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
533		    buffer_len(&compression_buffer));
534		DBG(debug("compression: raw %d compressed %d", len,
535		    buffer_len(&outgoing_packet)));
536	}
537
538	/* sizeof (packet_len + pad_len + payload) */
539	len = buffer_len(&outgoing_packet);
540
541	/*
542	 * calc size of padding, alloc space, get random data,
543	 * minimum padding is 4 bytes
544	 */
545	padlen = block_size - (len % block_size);
546	if (padlen < 4)
547		padlen += block_size;
548	if (extra_pad) {
549		/* will wrap if extra_pad+padlen > 255 */
550		extra_pad  = roundup(extra_pad, block_size);
551		pad = extra_pad - ((len + padlen) % extra_pad);
552		debug("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
553		    pad, len, padlen, extra_pad);
554		padlen += pad;
555		extra_pad = 0;
556	}
557	cp = buffer_append_space(&outgoing_packet, padlen);
558	if (enc && !send_context.plaintext) {
559		/* random padding */
560		for (i = 0; i < padlen; i++) {
561			if (i % 4 == 0)
562				rand = arc4random();
563			cp[i] = rand & 0xff;
564			rand >>= 8;
565		}
566	} else {
567		/* clear padding */
568		memset(cp, 0, padlen);
569	}
570	/* packet_length includes payload, padding and padding length field */
571	packet_length = buffer_len(&outgoing_packet) - 4;
572	cp = buffer_ptr(&outgoing_packet);
573	PUT_32BIT(cp, packet_length);
574	cp[4] = padlen;
575	DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
576
577	/* compute MAC over seqnr and packet(length fields, payload, padding) */
578	if (mac && mac->enabled) {
579		macbuf = mac_compute(mac, seqnr,
580		    buffer_ptr(&outgoing_packet),
581		    buffer_len(&outgoing_packet));
582		DBG(debug("done calc MAC out #%d", seqnr));
583	}
584	/* encrypt packet and append to output buffer. */
585	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
586	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
587	    buffer_len(&outgoing_packet));
588	/* append unencrypted MAC */
589	if (mac && mac->enabled)
590		buffer_append(&output, (char *)macbuf, mac->mac_len);
591#ifdef PACKET_DEBUG
592	fprintf(stderr, "encrypted: ");
593	buffer_dump(&output);
594#endif
595	/* increment sequence number for outgoing packets */
596	if (++seqnr == 0)
597		log("outgoing seqnr wraps around");
598	buffer_clear(&outgoing_packet);
599
600	if (type == SSH2_MSG_NEWKEYS)
601		set_newkeys(MODE_OUT);
602}
603
604void
605packet_send(void)
606{
607	if (compat20)
608		packet_send2();
609	else
610		packet_send1();
611	DBG(debug("packet_send done"));
612}
613
614/*
615 * Waits until a packet has been received, and returns its type.  Note that
616 * no other data is processed until this returns, so this function should not
617 * be used during the interactive session.
618 */
619
620int
621packet_read_seqnr(u_int32_t *seqnr_p)
622{
623	int type, len;
624	fd_set *setp;
625	char buf[8192];
626	DBG(debug("packet_read()"));
627
628	setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
629	    sizeof(fd_mask));
630
631	/* Since we are blocking, ensure that all written packets have been sent. */
632	packet_write_wait();
633
634	/* Stay in the loop until we have received a complete packet. */
635	for (;;) {
636		/* Try to read a packet from the buffer. */
637		type = packet_read_poll_seqnr(seqnr_p);
638		if (!compat20 && (
639		    type == SSH_SMSG_SUCCESS
640		    || type == SSH_SMSG_FAILURE
641		    || type == SSH_CMSG_EOF
642		    || type == SSH_CMSG_EXIT_CONFIRMATION))
643			packet_check_eom();
644		/* If we got a packet, return it. */
645		if (type != SSH_MSG_NONE) {
646			xfree(setp);
647			return type;
648		}
649		/*
650		 * Otherwise, wait for some data to arrive, add it to the
651		 * buffer, and try again.
652		 */
653		memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
654		    sizeof(fd_mask));
655		FD_SET(connection_in, setp);
656
657		/* Wait for some data to arrive. */
658		while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
659		    (errno == EAGAIN || errno == EINTR))
660			;
661
662		/* Read data from the socket. */
663		len = read(connection_in, buf, sizeof(buf));
664		if (len == 0) {
665			log("Connection closed by %.200s", get_remote_ipaddr());
666			fatal_cleanup();
667		}
668		if (len < 0)
669			fatal("Read from socket failed: %.100s", strerror(errno));
670		/* Append it to the buffer. */
671		packet_process_incoming(buf, len);
672	}
673	/* NOTREACHED */
674}
675
676int
677packet_read(void)
678{
679	return packet_read_seqnr(NULL);
680}
681
682/*
683 * Waits until a packet has been received, verifies that its type matches
684 * that given, and gives a fatal error and exits if there is a mismatch.
685 */
686
687void
688packet_read_expect(int expected_type)
689{
690	int type;
691
692	type = packet_read();
693	if (type != expected_type)
694		packet_disconnect("Protocol error: expected packet type %d, got %d",
695		    expected_type, type);
696}
697
698/* Checks if a full packet is available in the data received so far via
699 * packet_process_incoming.  If so, reads the packet; otherwise returns
700 * SSH_MSG_NONE.  This does not wait for data from the connection.
701 *
702 * SSH_MSG_DISCONNECT is handled specially here.  Also,
703 * SSH_MSG_IGNORE messages are skipped by this function and are never returned
704 * to higher levels.
705 */
706
707static int
708packet_read_poll1(void)
709{
710	u_int len, padded_len;
711	u_char *cp, type;
712	u_int checksum, stored_checksum;
713
714	/* Check if input size is less than minimum packet size. */
715	if (buffer_len(&input) < 4 + 8)
716		return SSH_MSG_NONE;
717	/* Get length of incoming packet. */
718	cp = buffer_ptr(&input);
719	len = GET_32BIT(cp);
720	if (len < 1 + 2 + 2 || len > 256 * 1024)
721		packet_disconnect("Bad packet length %d.", len);
722	padded_len = (len + 8) & ~7;
723
724	/* Check if the packet has been entirely received. */
725	if (buffer_len(&input) < 4 + padded_len)
726		return SSH_MSG_NONE;
727
728	/* The entire packet is in buffer. */
729
730	/* Consume packet length. */
731	buffer_consume(&input, 4);
732
733	/*
734	 * Cryptographic attack detector for ssh
735	 * (C)1998 CORE-SDI, Buenos Aires Argentina
736	 * Ariel Futoransky(futo@core-sdi.com)
737	 */
738	if (!receive_context.plaintext &&
739	    detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
740		packet_disconnect("crc32 compensation attack: network attack detected");
741
742	/* Decrypt data to incoming_packet. */
743	buffer_clear(&incoming_packet);
744	cp = buffer_append_space(&incoming_packet, padded_len);
745	cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
746
747	buffer_consume(&input, padded_len);
748
749#ifdef PACKET_DEBUG
750	fprintf(stderr, "read_poll plain: ");
751	buffer_dump(&incoming_packet);
752#endif
753
754	/* Compute packet checksum. */
755	checksum = ssh_crc32(buffer_ptr(&incoming_packet),
756	    buffer_len(&incoming_packet) - 4);
757
758	/* Skip padding. */
759	buffer_consume(&incoming_packet, 8 - len % 8);
760
761	/* Test check bytes. */
762	if (len != buffer_len(&incoming_packet))
763		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
764		    len, buffer_len(&incoming_packet));
765
766	cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
767	stored_checksum = GET_32BIT(cp);
768	if (checksum != stored_checksum)
769		packet_disconnect("Corrupted check bytes on input.");
770	buffer_consume_end(&incoming_packet, 4);
771
772	if (packet_compression) {
773		buffer_clear(&compression_buffer);
774		buffer_uncompress(&incoming_packet, &compression_buffer);
775		buffer_clear(&incoming_packet);
776		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
777		    buffer_len(&compression_buffer));
778	}
779	type = buffer_get_char(&incoming_packet);
780	return type;
781}
782
783static int
784packet_read_poll2(u_int32_t *seqnr_p)
785{
786	static u_int32_t seqnr = 0;
787	static u_int packet_length = 0;
788	u_int padlen, need;
789	u_char *macbuf, *cp, type;
790	int maclen, block_size;
791	Enc *enc   = NULL;
792	Mac *mac   = NULL;
793	Comp *comp = NULL;
794
795	if (newkeys[MODE_IN] != NULL) {
796		enc  = &newkeys[MODE_IN]->enc;
797		mac  = &newkeys[MODE_IN]->mac;
798		comp = &newkeys[MODE_IN]->comp;
799	}
800	maclen = mac && mac->enabled ? mac->mac_len : 0;
801	block_size = enc ? enc->block_size : 8;
802
803	if (packet_length == 0) {
804		/*
805		 * check if input size is less than the cipher block size,
806		 * decrypt first block and extract length of incoming packet
807		 */
808		if (buffer_len(&input) < block_size)
809			return SSH_MSG_NONE;
810		buffer_clear(&incoming_packet);
811		cp = buffer_append_space(&incoming_packet, block_size);
812		cipher_crypt(&receive_context, cp, buffer_ptr(&input),
813		    block_size);
814		cp = buffer_ptr(&incoming_packet);
815		packet_length = GET_32BIT(cp);
816		if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
817			buffer_dump(&incoming_packet);
818			packet_disconnect("Bad packet length %d.", packet_length);
819		}
820		DBG(debug("input: packet len %d", packet_length+4));
821		buffer_consume(&input, block_size);
822	}
823	/* we have a partial packet of block_size bytes */
824	need = 4 + packet_length - block_size;
825	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
826	    need, maclen));
827	if (need % block_size != 0)
828		fatal("padding error: need %d block %d mod %d",
829		    need, block_size, need % block_size);
830	/*
831	 * check if the entire packet has been received and
832	 * decrypt into incoming_packet
833	 */
834	if (buffer_len(&input) < need + maclen)
835		return SSH_MSG_NONE;
836#ifdef PACKET_DEBUG
837	fprintf(stderr, "read_poll enc/full: ");
838	buffer_dump(&input);
839#endif
840	cp = buffer_append_space(&incoming_packet, need);
841	cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
842	buffer_consume(&input, need);
843	/*
844	 * compute MAC over seqnr and packet,
845	 * increment sequence number for incoming packet
846	 */
847	if (mac && mac->enabled) {
848		macbuf = mac_compute(mac, seqnr,
849		    buffer_ptr(&incoming_packet),
850		    buffer_len(&incoming_packet));
851		if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
852			packet_disconnect("Corrupted MAC on input.");
853		DBG(debug("MAC #%d ok", seqnr));
854		buffer_consume(&input, mac->mac_len);
855	}
856	if (seqnr_p != NULL)
857		*seqnr_p = seqnr;
858	if (++seqnr == 0)
859		log("incoming seqnr wraps around");
860
861	/* get padlen */
862	cp = buffer_ptr(&incoming_packet);
863	padlen = cp[4];
864	DBG(debug("input: padlen %d", padlen));
865	if (padlen < 4)
866		packet_disconnect("Corrupted padlen %d on input.", padlen);
867
868	/* skip packet size + padlen, discard padding */
869	buffer_consume(&incoming_packet, 4 + 1);
870	buffer_consume_end(&incoming_packet, padlen);
871
872	DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
873	if (comp && comp->enabled) {
874		buffer_clear(&compression_buffer);
875		buffer_uncompress(&incoming_packet, &compression_buffer);
876		buffer_clear(&incoming_packet);
877		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
878		    buffer_len(&compression_buffer));
879		DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
880	}
881	/*
882	 * get packet type, implies consume.
883	 * return length of payload (without type field)
884	 */
885	type = buffer_get_char(&incoming_packet);
886	if (type == SSH2_MSG_NEWKEYS)
887		set_newkeys(MODE_IN);
888#ifdef PACKET_DEBUG
889	fprintf(stderr, "read/plain[%d]:\r\n", type);
890	buffer_dump(&incoming_packet);
891#endif
892	/* reset for next packet */
893	packet_length = 0;
894	return type;
895}
896
897int
898packet_read_poll_seqnr(u_int32_t *seqnr_p)
899{
900	int reason, seqnr;
901	u_char type;
902	char *msg;
903
904	for (;;) {
905		if (compat20) {
906			type = packet_read_poll2(seqnr_p);
907			if (type)
908				DBG(debug("received packet type %d", type));
909			switch (type) {
910			case SSH2_MSG_IGNORE:
911				break;
912			case SSH2_MSG_DEBUG:
913				packet_get_char();
914				msg = packet_get_string(NULL);
915				debug("Remote: %.900s", msg);
916				xfree(msg);
917				msg = packet_get_string(NULL);
918				xfree(msg);
919				break;
920			case SSH2_MSG_DISCONNECT:
921				reason = packet_get_int();
922				msg = packet_get_string(NULL);
923				log("Received disconnect from %s: %d: %.400s", get_remote_ipaddr(),
924					reason, msg);
925				xfree(msg);
926				fatal_cleanup();
927				break;
928			case SSH2_MSG_UNIMPLEMENTED:
929				seqnr = packet_get_int();
930				debug("Received SSH2_MSG_UNIMPLEMENTED for %d", seqnr);
931				break;
932			default:
933				return type;
934				break;
935			}
936		} else {
937			type = packet_read_poll1();
938			switch (type) {
939			case SSH_MSG_IGNORE:
940				break;
941			case SSH_MSG_DEBUG:
942				msg = packet_get_string(NULL);
943				debug("Remote: %.900s", msg);
944				xfree(msg);
945				break;
946			case SSH_MSG_DISCONNECT:
947				msg = packet_get_string(NULL);
948				log("Received disconnect from %s: %.400s", get_remote_ipaddr(),
949					msg);
950				fatal_cleanup();
951				xfree(msg);
952				break;
953			default:
954				if (type)
955					DBG(debug("received packet type %d", type));
956				return type;
957				break;
958			}
959		}
960	}
961}
962
963int
964packet_read_poll(void)
965{
966	return packet_read_poll_seqnr(NULL);
967}
968
969/*
970 * Buffers the given amount of input characters.  This is intended to be used
971 * together with packet_read_poll.
972 */
973
974void
975packet_process_incoming(const char *buf, u_int len)
976{
977	buffer_append(&input, buf, len);
978}
979
980/* Returns a character from the packet. */
981
982u_int
983packet_get_char(void)
984{
985	char ch;
986	buffer_get(&incoming_packet, &ch, 1);
987	return (u_char) ch;
988}
989
990/* Returns an integer from the packet data. */
991
992u_int
993packet_get_int(void)
994{
995	return buffer_get_int(&incoming_packet);
996}
997
998/*
999 * Returns an arbitrary precision integer from the packet data.  The integer
1000 * must have been initialized before this call.
1001 */
1002
1003void
1004packet_get_bignum(BIGNUM * value)
1005{
1006	buffer_get_bignum(&incoming_packet, value);
1007}
1008
1009void
1010packet_get_bignum2(BIGNUM * value)
1011{
1012	buffer_get_bignum2(&incoming_packet, value);
1013}
1014
1015void *
1016packet_get_raw(int *length_ptr)
1017{
1018	int bytes = buffer_len(&incoming_packet);
1019	if (length_ptr != NULL)
1020		*length_ptr = bytes;
1021	return buffer_ptr(&incoming_packet);
1022}
1023
1024int
1025packet_remaining(void)
1026{
1027	return buffer_len(&incoming_packet);
1028}
1029
1030/*
1031 * Returns a string from the packet data.  The string is allocated using
1032 * xmalloc; it is the responsibility of the calling program to free it when
1033 * no longer needed.  The length_ptr argument may be NULL, or point to an
1034 * integer into which the length of the string is stored.
1035 */
1036
1037void *
1038packet_get_string(u_int *length_ptr)
1039{
1040	return buffer_get_string(&incoming_packet, length_ptr);
1041}
1042
1043/*
1044 * Sends a diagnostic message from the server to the client.  This message
1045 * can be sent at any time (but not while constructing another message). The
1046 * message is printed immediately, but only if the client is being executed
1047 * in verbose mode.  These messages are primarily intended to ease debugging
1048 * authentication problems.   The length of the formatted message must not
1049 * exceed 1024 bytes.  This will automatically call packet_write_wait.
1050 */
1051
1052void
1053packet_send_debug(const char *fmt,...)
1054{
1055	char buf[1024];
1056	va_list args;
1057
1058	if (compat20 && (datafellows & SSH_BUG_DEBUG))
1059		return;
1060
1061	va_start(args, fmt);
1062	vsnprintf(buf, sizeof(buf), fmt, args);
1063	va_end(args);
1064
1065	if (compat20) {
1066		packet_start(SSH2_MSG_DEBUG);
1067		packet_put_char(0);	/* bool: always display */
1068		packet_put_cstring(buf);
1069		packet_put_cstring("");
1070	} else {
1071		packet_start(SSH_MSG_DEBUG);
1072		packet_put_cstring(buf);
1073	}
1074	packet_send();
1075	packet_write_wait();
1076}
1077
1078/*
1079 * Logs the error plus constructs and sends a disconnect packet, closes the
1080 * connection, and exits.  This function never returns. The error message
1081 * should not contain a newline.  The length of the formatted message must
1082 * not exceed 1024 bytes.
1083 */
1084
1085void
1086packet_disconnect(const char *fmt,...)
1087{
1088	char buf[1024];
1089	va_list args;
1090	static int disconnecting = 0;
1091	if (disconnecting)	/* Guard against recursive invocations. */
1092		fatal("packet_disconnect called recursively.");
1093	disconnecting = 1;
1094
1095	/*
1096	 * Format the message.  Note that the caller must make sure the
1097	 * message is of limited size.
1098	 */
1099	va_start(args, fmt);
1100	vsnprintf(buf, sizeof(buf), fmt, args);
1101	va_end(args);
1102
1103	/* Send the disconnect message to the other side, and wait for it to get sent. */
1104	if (compat20) {
1105		packet_start(SSH2_MSG_DISCONNECT);
1106		packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1107		packet_put_cstring(buf);
1108		packet_put_cstring("");
1109	} else {
1110		packet_start(SSH_MSG_DISCONNECT);
1111		packet_put_cstring(buf);
1112	}
1113	packet_send();
1114	packet_write_wait();
1115
1116	/* Stop listening for connections. */
1117	channel_close_all();
1118
1119	/* Close the connection. */
1120	packet_close();
1121
1122	/* Display the error locally and exit. */
1123	log("Disconnecting: %.100s", buf);
1124	fatal_cleanup();
1125}
1126
1127/* Checks if there is any buffered output, and tries to write some of the output. */
1128
1129void
1130packet_write_poll(void)
1131{
1132	int len = buffer_len(&output);
1133	if (len > 0) {
1134		len = write(connection_out, buffer_ptr(&output), len);
1135		if (len <= 0) {
1136			if (errno == EAGAIN)
1137				return;
1138			else
1139				fatal("Write failed: %.100s", strerror(errno));
1140		}
1141		buffer_consume(&output, len);
1142	}
1143}
1144
1145/*
1146 * Calls packet_write_poll repeatedly until all pending output data has been
1147 * written.
1148 */
1149
1150void
1151packet_write_wait(void)
1152{
1153	fd_set *setp;
1154
1155	setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1156	    sizeof(fd_mask));
1157	packet_write_poll();
1158	while (packet_have_data_to_write()) {
1159		memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1160		    sizeof(fd_mask));
1161		FD_SET(connection_out, setp);
1162		while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1163		    (errno == EAGAIN || errno == EINTR))
1164			;
1165		packet_write_poll();
1166	}
1167	xfree(setp);
1168}
1169
1170/* Returns true if there is buffered data to write to the connection. */
1171
1172int
1173packet_have_data_to_write(void)
1174{
1175	return buffer_len(&output) != 0;
1176}
1177
1178/* Returns true if there is not too much data to write to the connection. */
1179
1180int
1181packet_not_very_much_data_to_write(void)
1182{
1183	if (interactive_mode)
1184		return buffer_len(&output) < 16384;
1185	else
1186		return buffer_len(&output) < 128 * 1024;
1187}
1188
1189/* Informs that the current session is interactive.  Sets IP flags for that. */
1190
1191void
1192packet_set_interactive(int interactive)
1193{
1194	static int called = 0;
1195	int lowdelay = IPTOS_LOWDELAY;
1196	int throughput = IPTOS_THROUGHPUT;
1197
1198	if (called)
1199		return;
1200	called = 1;
1201
1202	/* Record that we are in interactive mode. */
1203	interactive_mode = interactive;
1204
1205	/* Only set socket options if using a socket.  */
1206	if (!packet_connection_is_on_socket())
1207		return;
1208	/*
1209	 * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1210	 */
1211	if (interactive) {
1212		/*
1213		 * Set IP options for an interactive connection.  Use
1214		 * IPTOS_LOWDELAY and TCP_NODELAY.
1215		 */
1216		if (packet_connection_is_ipv4()) {
1217			if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1218			    &lowdelay, sizeof(lowdelay)) < 0)
1219				error("setsockopt IPTOS_LOWDELAY: %.100s",
1220				    strerror(errno));
1221		}
1222		set_nodelay(connection_in);
1223	} else if (packet_connection_is_ipv4()) {
1224		/*
1225		 * Set IP options for a non-interactive connection.  Use
1226		 * IPTOS_THROUGHPUT.
1227		 */
1228		if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &throughput,
1229		    sizeof(throughput)) < 0)
1230			error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1231	}
1232}
1233
1234/* Returns true if the current connection is interactive. */
1235
1236int
1237packet_is_interactive(void)
1238{
1239	return interactive_mode;
1240}
1241
1242int
1243packet_set_maxsize(int s)
1244{
1245	static int called = 0;
1246	if (called) {
1247		log("packet_set_maxsize: called twice: old %d new %d",
1248		    max_packet_size, s);
1249		return -1;
1250	}
1251	if (s < 4 * 1024 || s > 1024 * 1024) {
1252		log("packet_set_maxsize: bad size %d", s);
1253		return -1;
1254	}
1255	called = 1;
1256	debug("packet_set_maxsize: setting to %d", s);
1257	max_packet_size = s;
1258	return s;
1259}
1260
1261/* roundup current message to pad bytes */
1262void
1263packet_add_padding(u_char pad)
1264{
1265	extra_pad = pad;
1266}
1267
1268/*
1269 * 9.2.  Ignored Data Message
1270 *
1271 *   byte      SSH_MSG_IGNORE
1272 *   string    data
1273 *
1274 * All implementations MUST understand (and ignore) this message at any
1275 * time (after receiving the protocol version). No implementation is
1276 * required to send them. This message can be used as an additional
1277 * protection measure against advanced traffic analysis techniques.
1278 */
1279void
1280packet_send_ignore(int nbytes)
1281{
1282	u_int32_t rand = 0;
1283	int i;
1284
1285	packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1286	packet_put_int(nbytes);
1287	for (i = 0; i < nbytes; i++) {
1288		if (i % 4 == 0)
1289			rand = arc4random();
1290		packet_put_char(rand & 0xff);
1291		rand >>= 8;
1292	}
1293}
1294