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