Home | History | Annotate | Download | only in common
      1 /*
      2  * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
      3  * Copyright (c) 1995 Tatu Ylonen <ylo (at) cs.hut.fi>, Espoo, Finland
      4  *                    All rights reserved
      5  * This file contains code implementing the packet protocol and communication
      6  * with the other side.  This same code is used both on client and server side.
      7  *
      8  * As far as I am concerned, the code I have written for this software
      9  * can be used freely for any purpose.  Any derived versions of this
     10  * software must be clearly marked as such, and if the derived work is
     11  * incompatible with the protocol description in the RFC file, it must be
     12  * called by a name other than "ssh" or "Secure Shell".
     13  *
     14  *
     15  * SSH2 packet format added by Markus Friedl.
     16  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
     17  *
     18  * Redistribution and use in source and binary forms, with or without
     19  * modification, are permitted provided that the following conditions
     20  * are met:
     21  * 1. Redistributions of source code must retain the above copyright
     22  *    notice, this list of conditions and the following disclaimer.
     23  * 2. Redistributions in binary form must reproduce the above copyright
     24  *    notice, this list of conditions and the following disclaimer in the
     25  *    documentation and/or other materials provided with the distribution.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     28  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     29  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     30  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     31  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     32  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     33  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     34  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     36  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 /*
     39  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
     40  * Use is subject to license terms.
     41  */
     42 
     43 /* $OpenBSD: packet.c,v 1.148 2007/06/07 19:37:34 pvalchev Exp $ */
     44 
     45 #pragma ident	"%Z%%M%	%I%	%E% SMI"
     46 
     47 #include "includes.h"
     48 
     49 #include "sys-queue.h"
     50 #include "xmalloc.h"
     51 #include "buffer.h"
     52 #include "packet.h"
     53 #include "bufaux.h"
     54 #include "crc32.h"
     55 #include "getput.h"
     56 #include "compress.h"
     57 #include "deattack.h"
     58 #include "channels.h"
     59 #include "compat.h"
     60 #include "ssh1.h"
     61 #include "ssh2.h"
     62 #include "cipher.h"
     63 #include "kex.h"
     64 #include "mac.h"
     65 #include "log.h"
     66 #include "canohost.h"
     67 #include "misc.h"
     68 #include "ssh.h"
     69 
     70 #ifdef ALTPRIVSEP
     71 static int packet_server = 0;
     72 static int packet_monitor = 0;
     73 #endif /* ALTPRIVSEP */
     74 
     75 #ifdef PACKET_DEBUG
     76 #define DBG(x) x
     77 #else
     78 #define DBG(x)
     79 #endif
     80 
     81 /*
     82  * This variable contains the file descriptors used for communicating with
     83  * the other side.  connection_in is used for reading; connection_out for
     84  * writing.  These can be the same descriptor, in which case it is assumed to
     85  * be a socket.
     86  */
     87 static int connection_in = -1;
     88 static int connection_out = -1;
     89 
     90 /* Protocol flags for the remote side. */
     91 static u_int remote_protocol_flags = 0;
     92 
     93 /* Encryption context for receiving data.  This is only used for decryption. */
     94 static CipherContext receive_context;
     95 
     96 /* Encryption context for sending data.  This is only used for encryption. */
     97 static CipherContext send_context;
     98 
     99 /* Buffer for raw input data from the socket. */
    100 Buffer input;
    101 
    102 /* Buffer for raw output data going to the socket. */
    103 Buffer output;
    104 
    105 /* Buffer for the partial outgoing packet being constructed. */
    106 static Buffer outgoing_packet;
    107 
    108 /* Buffer for the incoming packet currently being processed. */
    109 static Buffer incoming_packet;
    110 
    111 /* Scratch buffer for packet compression/decompression. */
    112 static Buffer compression_buffer;
    113 static int compression_buffer_ready = 0;
    114 
    115 /* Flag indicating whether packet compression/decompression is enabled. */
    116 static int packet_compression = 0;
    117 
    118 /* default maximum packet size */
    119 int max_packet_size = 32768;
    120 
    121 /* Flag indicating whether this module has been initialized. */
    122 static int initialized = 0;
    123 
    124 /* Set to true if the connection is interactive. */
    125 static int interactive_mode = 0;
    126 
    127 /* Session key information for Encryption and MAC */
    128 Newkeys *newkeys[MODE_MAX];
    129 static struct packet_state {
    130 	u_int32_t seqnr;
    131 	u_int32_t packets;
    132 	u_int64_t blocks;
    133 } p_read, p_send;
    134 
    135 static u_int64_t max_blocks_in, max_blocks_out;
    136 static u_int32_t rekey_limit;
    137 
    138 /* Session key for protocol v1 */
    139 static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
    140 static u_int ssh1_keylen;
    141 
    142 /* roundup current message to extra_pad bytes */
    143 static u_char extra_pad = 0;
    144 
    145 struct packet {
    146 	TAILQ_ENTRY(packet) next;
    147 	u_char type;
    148 	Buffer payload;
    149 };
    150 TAILQ_HEAD(, packet) outgoing;
    151 
    152 /*
    153  * Sets the descriptors used for communication.  Disables encryption until
    154  * packet_set_encryption_key is called.
    155  */
    156 void
    157 packet_set_connection(int fd_in, int fd_out)
    158 {
    159 	Cipher *none = cipher_by_name("none");
    160 
    161 	if (none == NULL)
    162 		fatal("packet_set_connection: cannot load cipher 'none'");
    163 	connection_in = fd_in;
    164 	connection_out = fd_out;
    165 	cipher_init(&send_context, none, (unsigned char *) "", 0, NULL, 0, CIPHER_ENCRYPT);
    166 	cipher_init(&receive_context, none, (unsigned char *) "", 0, NULL, 0, CIPHER_DECRYPT);
    167 	newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
    168 	if (!initialized) {
    169 		initialized = 1;
    170 		buffer_init(&input);
    171 		buffer_init(&output);
    172 		buffer_init(&outgoing_packet);
    173 		buffer_init(&incoming_packet);
    174 		TAILQ_INIT(&outgoing);
    175 	} else {
    176 		buffer_clear(&input);
    177 		buffer_clear(&output);
    178 		buffer_clear(&outgoing_packet);
    179 		buffer_clear(&incoming_packet);
    180 	}
    181 
    182 	/*
    183 	 * Prime the cache for get_remote_ipaddr() while we have a
    184 	 * socket on which to do a getpeername().
    185 	 */
    186 	(void) get_remote_ipaddr();
    187 
    188 	/* Kludge: arrange the close function to be called from fatal(). */
    189 	fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
    190 }
    191 
    192 /* Returns 1 if remote host is connected via socket, 0 if not. */
    193 
    194 int
    195 packet_connection_is_on_socket(void)
    196 {
    197 	struct sockaddr_storage from, to;
    198 	socklen_t fromlen, tolen;
    199 
    200 	/* filedescriptors in and out are the same, so it's a socket */
    201 	if (connection_in != -1 && connection_in == connection_out)
    202 		return 1;
    203 	fromlen = sizeof(from);
    204 	memset(&from, 0, sizeof(from));
    205 	if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
    206 		return 0;
    207 	tolen = sizeof(to);
    208 	memset(&to, 0, sizeof(to));
    209 	if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
    210 		return 0;
    211 	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
    212 		return 0;
    213 	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
    214 		return 0;
    215 	return 1;
    216 }
    217 
    218 /* returns 1 if connection is via ipv4 */
    219 
    220 int
    221 packet_connection_is_ipv4(void)
    222 {
    223 	struct sockaddr_storage to;
    224 	socklen_t tolen = sizeof(to);
    225 
    226 	memset(&to, 0, sizeof(to));
    227 	if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
    228 		return 0;
    229 	if (to.ss_family == AF_INET)
    230 		return 1;
    231 #ifdef IPV4_IN_IPV6
    232 	if (to.ss_family == AF_INET6 &&
    233 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
    234 		return 1;
    235 #endif
    236 	return 0;
    237 }
    238 
    239 /* Sets the connection into non-blocking mode. */
    240 
    241 void
    242 packet_set_nonblocking(void)
    243 {
    244 	/* Set the socket into non-blocking mode. */
    245 	if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
    246 		error("fcntl O_NONBLOCK: %.100s", strerror(errno));
    247 
    248 	if (connection_out != connection_in) {
    249 		if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
    250 			error("fcntl O_NONBLOCK: %.100s", strerror(errno));
    251 	}
    252 }
    253 
    254 /* Returns the socket used for reading. */
    255 
    256 int
    257 packet_get_connection_in(void)
    258 {
    259 	return connection_in;
    260 }
    261 
    262 /* Returns the descriptor used for writing. */
    263 
    264 int
    265 packet_get_connection_out(void)
    266 {
    267 	return connection_out;
    268 }
    269 
    270 /* Closes the connection and clears and frees internal data structures. */
    271 
    272 void
    273 packet_close(void)
    274 {
    275 	if (!initialized)
    276 		return;
    277 	initialized = 0;
    278 	if (connection_in == connection_out) {
    279 		shutdown(connection_out, SHUT_RDWR);
    280 		close(connection_out);
    281 	} else {
    282 		close(connection_in);
    283 		close(connection_out);
    284 	}
    285 	buffer_free(&input);
    286 	buffer_free(&output);
    287 	buffer_free(&outgoing_packet);
    288 	buffer_free(&incoming_packet);
    289 	if (compression_buffer_ready) {
    290 		buffer_free(&compression_buffer);
    291 		buffer_compress_uninit();
    292 		compression_buffer_ready = 0;
    293 	}
    294 	cipher_cleanup(&send_context);
    295 	cipher_cleanup(&receive_context);
    296 }
    297 
    298 /* Sets remote side protocol flags. */
    299 
    300 void
    301 packet_set_protocol_flags(u_int protocol_flags)
    302 {
    303 	remote_protocol_flags = protocol_flags;
    304 }
    305 
    306 /* Returns the remote protocol flags set earlier by the above function. */
    307 
    308 u_int
    309 packet_get_protocol_flags(void)
    310 {
    311 	return remote_protocol_flags;
    312 }
    313 
    314 /*
    315  * Starts packet compression from the next packet on in both directions.
    316  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
    317  */
    318 
    319 static void
    320 packet_init_compression(void)
    321 {
    322 	if (compression_buffer_ready == 1)
    323 		return;
    324 	compression_buffer_ready = 1;
    325 	buffer_init(&compression_buffer);
    326 }
    327 
    328 void
    329 packet_start_compression(int level)
    330 {
    331 #ifdef ALTPRIVSEP
    332 	/* shouldn't happen! */
    333 	if (packet_monitor)
    334 		fatal("INTERNAL ERROR: The monitor cannot compress.");
    335 #endif /* ALTPRIVSEP */
    336 
    337 	if (packet_compression && !compat20)
    338 		fatal("Compression already enabled.");
    339 	packet_compression = 1;
    340 	packet_init_compression();
    341 	buffer_compress_init_send(level);
    342 	buffer_compress_init_recv();
    343 }
    344 
    345 /*
    346  * Causes any further packets to be encrypted using the given key.  The same
    347  * key is used for both sending and reception.  However, both directions are
    348  * encrypted independently of each other.
    349  */
    350 
    351 void
    352 packet_set_encryption_key(const u_char *key, u_int keylen,
    353     int number)
    354 {
    355 	Cipher *cipher = cipher_by_number(number);
    356 
    357 	if (cipher == NULL)
    358 		fatal("packet_set_encryption_key: unknown cipher number %d", number);
    359 	if (keylen < 20)
    360 		fatal("packet_set_encryption_key: keylen too small: %d", keylen);
    361 	if (keylen > SSH_SESSION_KEY_LENGTH)
    362 		fatal("packet_set_encryption_key: keylen too big: %d", keylen);
    363 	memcpy(ssh1_key, key, keylen);
    364 	ssh1_keylen = keylen;
    365 	cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
    366 	cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
    367 }
    368 
    369 u_int
    370 packet_get_encryption_key(u_char *key)
    371 {
    372 	if (key == NULL)
    373 		return (ssh1_keylen);
    374 	memcpy(key, ssh1_key, ssh1_keylen);
    375 	return (ssh1_keylen);
    376 }
    377 
    378 /* Start constructing a packet to send. */
    379 void
    380 packet_start(u_char type)
    381 {
    382 	u_char buf[9];
    383 	int len;
    384 
    385 	DBG(debug("packet_start[%d]", type));
    386 	len = compat20 ? 6 : 9;
    387 	memset(buf, 0, len - 1);
    388 	buf[len - 1] = type;
    389 	buffer_clear(&outgoing_packet);
    390 	buffer_append(&outgoing_packet, buf, len);
    391 }
    392 
    393 /* Append payload. */
    394 void
    395 packet_put_char(int value)
    396 {
    397 	char ch = value;
    398 
    399 	buffer_append(&outgoing_packet, &ch, 1);
    400 }
    401 
    402 void
    403 packet_put_int(u_int value)
    404 {
    405 	buffer_put_int(&outgoing_packet, value);
    406 }
    407 
    408 void
    409 packet_put_string(const void *buf, u_int len)
    410 {
    411 	buffer_put_string(&outgoing_packet, buf, len);
    412 }
    413 
    414 void
    415 packet_put_cstring(const char *str)
    416 {
    417 	buffer_put_cstring(&outgoing_packet, str);
    418 }
    419 
    420 void
    421 packet_put_ascii_cstring(const char *str)
    422 {
    423 	buffer_put_ascii_cstring(&outgoing_packet, str);
    424 }
    425 void
    426 packet_put_utf8_cstring(const u_char *str)
    427 {
    428 	buffer_put_utf8_cstring(&outgoing_packet, str);
    429 }
    430 #if 0
    431 void
    432 packet_put_ascii_string(const void *buf, u_int len)
    433 {
    434 	buffer_put_ascii_string(&outgoing_packet, buf, len);
    435 }
    436 void
    437 packet_put_utf8_string(const void *buf, u_int len)
    438 {
    439 	buffer_put_utf8_string(&outgoing_packet, buf, len);
    440 }
    441 #endif
    442 void
    443 packet_put_raw(const void *buf, u_int len)
    444 {
    445 	buffer_append(&outgoing_packet, buf, len);
    446 }
    447 
    448 void
    449 packet_put_bignum(BIGNUM * value)
    450 {
    451 	buffer_put_bignum(&outgoing_packet, value);
    452 }
    453 
    454 void
    455 packet_put_bignum2(BIGNUM * value)
    456 {
    457 	buffer_put_bignum2(&outgoing_packet, value);
    458 }
    459 
    460 /*
    461  * Finalizes and sends the packet.  If the encryption key has been set,
    462  * encrypts the packet before sending.
    463  */
    464 
    465 static void
    466 packet_send1(void)
    467 {
    468 	u_char buf[8], *cp;
    469 	int i, padding, len;
    470 	u_int checksum;
    471 	u_int32_t rnd = 0;
    472 
    473 	/*
    474 	 * If using packet compression, compress the payload of the outgoing
    475 	 * packet.
    476 	 */
    477 	if (packet_compression) {
    478 		buffer_clear(&compression_buffer);
    479 		/* Skip padding. */
    480 		buffer_consume(&outgoing_packet, 8);
    481 		/* padding */
    482 		buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
    483 		buffer_compress(&outgoing_packet, &compression_buffer);
    484 		buffer_clear(&outgoing_packet);
    485 		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
    486 		    buffer_len(&compression_buffer));
    487 	}
    488 	/* Compute packet length without padding (add checksum, remove padding). */
    489 	len = buffer_len(&outgoing_packet) + 4 - 8;
    490 
    491 	/* Insert padding. Initialized to zero in packet_start1() */
    492 	padding = 8 - len % 8;
    493 	if (!send_context.plaintext) {
    494 		cp = buffer_ptr(&outgoing_packet);
    495 		for (i = 0; i < padding; i++) {
    496 			if (i % 4 == 0)
    497 				rnd = arc4random();
    498 			cp[7 - i] = rnd & 0xff;
    499 			rnd >>= 8;
    500 		}
    501 	}
    502 	buffer_consume(&outgoing_packet, 8 - padding);
    503 
    504 	/* Add check bytes. */
    505 	checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
    506 	    buffer_len(&outgoing_packet));
    507 	PUT_32BIT(buf, checksum);
    508 	buffer_append(&outgoing_packet, buf, 4);
    509 
    510 #ifdef PACKET_DEBUG
    511 	fprintf(stderr, "packet_send plain: ");
    512 	buffer_dump(&outgoing_packet);
    513 #endif
    514 
    515 	/* Append to output. */
    516 	PUT_32BIT(buf, len);
    517 	buffer_append(&output, buf, 4);
    518 	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
    519 	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
    520 	    buffer_len(&outgoing_packet));
    521 
    522 #ifdef PACKET_DEBUG
    523 	fprintf(stderr, "encrypted: ");
    524 	buffer_dump(&output);
    525 #endif
    526 
    527 	buffer_clear(&outgoing_packet);
    528 
    529 	/*
    530 	 * Note that the packet is now only buffered in output.  It won\'t be
    531 	 * actually sent until packet_write_wait or packet_write_poll is
    532 	 * called.
    533 	 */
    534 }
    535 
    536 void
    537 set_newkeys(int mode)
    538 {
    539 	Enc *enc;
    540 	Mac *mac;
    541 	Comp *comp;
    542 	CipherContext *cc;
    543 	u_int64_t *max_blocks;
    544 	int crypt_type;
    545 
    546 	debug2("set_newkeys: mode %d", mode);
    547 
    548 	if (mode == MODE_OUT) {
    549 		cc = &send_context;
    550 		crypt_type = CIPHER_ENCRYPT;
    551 		p_send.packets = p_send.blocks = 0;
    552 		max_blocks = &max_blocks_out;
    553 	} else {
    554 		cc = &receive_context;
    555 		crypt_type = CIPHER_DECRYPT;
    556 		p_read.packets = p_read.blocks = 0;
    557 		max_blocks = &max_blocks_in;
    558 	}
    559 	if (newkeys[mode] != NULL) {
    560 		debug("set_newkeys: setting new keys for '%s' mode",
    561 		    mode == MODE_IN ? "in" : "out");
    562 		cipher_cleanup(cc);
    563 		free_keys(newkeys[mode]);
    564 	}
    565 	newkeys[mode] = kex_get_newkeys(mode);
    566 	if (newkeys[mode] == NULL)
    567 		fatal("newkeys: no keys for mode %d", mode);
    568 	enc  = &newkeys[mode]->enc;
    569 	mac  = &newkeys[mode]->mac;
    570 	comp = &newkeys[mode]->comp;
    571 	if (mac->md != NULL)
    572 		mac->enabled = 1;
    573 	DBG(debug("cipher_init_context: %d", mode));
    574 	cipher_init(cc, enc->cipher, enc->key, enc->key_len,
    575 	    enc->iv, enc->block_size, crypt_type);
    576 	/* Deleting the keys does not gain extra security */
    577 	/* memset(enc->iv,  0, enc->block_size);
    578 	   memset(enc->key, 0, enc->key_len); */
    579 	if (comp->type != 0 && comp->enabled == 0) {
    580 		packet_init_compression();
    581 		if (mode == MODE_OUT)
    582 			buffer_compress_init_send(6);
    583 		else
    584 			buffer_compress_init_recv();
    585 		comp->enabled = 1;
    586 	}
    587 
    588 	/*
    589 	 * In accordance to the RFCs listed below we enforce the key
    590 	 * re-exchange for:
    591 	 *
    592 	 * - every 1GB of transmitted data if the selected cipher block size
    593 	 *   is less than 16 bytes (3DES, Blowfish)
    594 	 * - every 2^(2*B) cipher blocks transmitted (B is block size in bytes)
    595 	 *   if the cipher block size is greater than or equal to 16 bytes (AES)
    596 	 * - and we never send more than 2^32 SSH packets using the same keys.
    597 	 *   The recommendation of 2^31 packets is not enforced here but in
    598 	 *   packet_need_rekeying(). There is also a hard check in
    599 	 *   packet_send2_wrapped() that we don't send more than 2^32 packets.
    600 	 *
    601 	 * Note that if the SSH_BUG_NOREKEY compatibility flag is set then no
    602 	 * automatic rekeying is performed nor do we enforce the 3rd rule.
    603 	 * This means that we can be always forced by the opposite side to never
    604 	 * initiate automatic key re-exchange. This might change in the future.
    605 	 *
    606 	 * The RekeyLimit option keyword may only enforce more frequent key
    607 	 * renegotiation, never less. For more information on key renegotiation,
    608 	 * see:
    609 	 *
    610 	 * - RFC 4253 (SSH Transport Layer Protocol), section "9. Key
    611 	 *   Re-Exchange"
    612 	 * - RFC 4344 (SSH Transport Layer Encryption Modes), sections "3.
    613 	 *   Rekeying" and "6.1 Rekeying Considerations"
    614 	 */
    615 	if (enc->block_size >= 16)
    616 		*max_blocks = (u_int64_t)1 << (enc->block_size * 2);
    617 	else
    618 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
    619 
    620 	if (rekey_limit)
    621 		*max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
    622 }
    623 
    624 void
    625 free_keys(Newkeys *keys)
    626 {
    627 	Enc *enc;
    628 	Mac *mac;
    629 	Comp *comp;
    630 
    631 	enc  = &keys->enc;
    632 	mac  = &keys->mac;
    633 	comp = &keys->comp;
    634 	memset(mac->key, 0, mac->key_len);
    635 	xfree(enc->name);
    636 	xfree(enc->iv);
    637 	xfree(enc->key);
    638 	xfree(mac->name);
    639 	xfree(mac->key);
    640 	xfree(comp->name);
    641 	xfree(keys);
    642 }
    643 
    644 /*
    645  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
    646  */
    647 static void
    648 packet_send2_wrapped(void)
    649 {
    650 	u_char type, *cp, *macbuf = NULL;
    651 	u_char padlen, pad;
    652 	u_int packet_length = 0;
    653 	u_int i, len;
    654 	u_int32_t rnd = 0;
    655 	Enc *enc   = NULL;
    656 	Mac *mac   = NULL;
    657 	Comp *comp = NULL;
    658 	int block_size;
    659 
    660 	if (newkeys[MODE_OUT] != NULL) {
    661 		enc  = &newkeys[MODE_OUT]->enc;
    662 		mac  = &newkeys[MODE_OUT]->mac;
    663 		comp = &newkeys[MODE_OUT]->comp;
    664 	}
    665 	block_size = enc ? enc->block_size : 8;
    666 
    667 	cp = buffer_ptr(&outgoing_packet);
    668 	type = cp[5];
    669 
    670 #ifdef PACKET_DEBUG
    671 	fprintf(stderr, "plain:     ");
    672 	buffer_dump(&outgoing_packet);
    673 #endif
    674 
    675 	if (comp && comp->enabled) {
    676 		len = buffer_len(&outgoing_packet);
    677 		/* skip header, compress only payload */
    678 		buffer_consume(&outgoing_packet, 5);
    679 		buffer_clear(&compression_buffer);
    680 		buffer_compress(&outgoing_packet, &compression_buffer);
    681 		buffer_clear(&outgoing_packet);
    682 		buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
    683 		buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
    684 		    buffer_len(&compression_buffer));
    685 		DBG(debug("compression: raw %d compressed %d", len,
    686 		    buffer_len(&outgoing_packet)));
    687 	}
    688 
    689 	/* sizeof (packet_len + pad_len + payload) */
    690 	len = buffer_len(&outgoing_packet);
    691 
    692 	/*
    693 	 * calc size of padding, alloc space, get random data,
    694 	 * minimum padding is 4 bytes
    695 	 */
    696 	padlen = block_size - (len % block_size);
    697 	if (padlen < 4)
    698 		padlen += block_size;
    699 	if (extra_pad) {
    700 		/* will wrap if extra_pad+padlen > 255 */
    701 		extra_pad  = roundup(extra_pad, block_size);
    702 		pad = extra_pad - ((len + padlen) % extra_pad);
    703 		debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
    704 		    pad, len, padlen, extra_pad);
    705 		padlen += pad;
    706 		extra_pad = 0;
    707 	}
    708 	cp = buffer_append_space(&outgoing_packet, padlen);
    709 	if (enc && !send_context.plaintext) {
    710 		/* random padding */
    711 		for (i = 0; i < padlen; i++) {
    712 			if (i % 4 == 0)
    713 				rnd = arc4random();
    714 			cp[i] = rnd & 0xff;
    715 			rnd >>= 8;
    716 		}
    717 	} else {
    718 		/* clear padding */
    719 		memset(cp, 0, padlen);
    720 	}
    721 	/* packet_length includes payload, padding and padding length field */
    722 	packet_length = buffer_len(&outgoing_packet) - 4;
    723 	cp = buffer_ptr(&outgoing_packet);
    724 	PUT_32BIT(cp, packet_length);
    725 	cp[4] = padlen;
    726 	DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
    727 
    728 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
    729 	if (mac && mac->enabled) {
    730 		macbuf = mac_compute(mac, p_send.seqnr,
    731 		    buffer_ptr(&outgoing_packet),
    732 		    buffer_len(&outgoing_packet));
    733 		DBG(debug("done calc MAC out #%d", p_send.seqnr));
    734 	}
    735 	/* encrypt packet and append to output buffer. */
    736 	cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
    737 	cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
    738 	    buffer_len(&outgoing_packet));
    739 	/* append unencrypted MAC */
    740 	if (mac && mac->enabled)
    741 		buffer_append(&output, (char *)macbuf, mac->mac_len);
    742 #ifdef PACKET_DEBUG
    743 	fprintf(stderr, "encrypted: ");
    744 	buffer_dump(&output);
    745 #endif
    746 	/* increment sequence number for outgoing packets */
    747 	if (++p_send.seqnr == 0)
    748 		log("outgoing seqnr wraps around");
    749 
    750 	/*
    751 	 * RFC 4344: 3.1. First Rekeying Recommendation
    752 	 *
    753 	 * "Because of possible information leakage through the MAC tag after a
    754 	 * key exchange, .... an SSH implementation SHOULD NOT send more than
    755 	 * 2**32 packets before rekeying again."
    756 	 *
    757 	 * The code below is a hard check so that we are sure we don't go across
    758 	 * the suggestion. However, since the largest cipher block size we have
    759 	 * (AES) is 16 bytes we can't reach 2^32 SSH packets encrypted with the
    760 	 * same key while performing periodic rekeying.
    761 	 */
    762 	if (++p_send.packets == 0)
    763 		if (!(datafellows & SSH_BUG_NOREKEY))
    764 			fatal("too many packets encrypted with same key");
    765 	p_send.blocks += (packet_length + 4) / block_size;
    766 	buffer_clear(&outgoing_packet);
    767 
    768 	if (type == SSH2_MSG_NEWKEYS)
    769 #ifdef ALTPRIVSEP
    770 		/* set_newkeys(MODE_OUT) in client, server, but not monitor */
    771 		if (!packet_is_server() && !packet_is_monitor())
    772 #endif /* ALTPRIVSEP */
    773 		set_newkeys(MODE_OUT);
    774 }
    775 
    776 static void
    777 packet_send2(void)
    778 {
    779 	static int rekeying = 0;
    780 	struct packet *p;
    781 	u_char type, *cp;
    782 
    783 	cp = buffer_ptr(&outgoing_packet);
    784 	type = cp[5];
    785 
    786 	/* during rekeying we can only send key exchange messages */
    787 	if (rekeying) {
    788 		if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
    789 		    (type <= SSH2_MSG_TRANSPORT_MAX))) {
    790 			debug("enqueue packet: %u", type);
    791 			p = xmalloc(sizeof(*p));
    792 			p->type = type;
    793 			memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
    794 			buffer_init(&outgoing_packet);
    795 			TAILQ_INSERT_TAIL(&outgoing, p, next);
    796 			return;
    797 		}
    798 	}
    799 
    800 	/* rekeying starts with sending KEXINIT */
    801 	if (type == SSH2_MSG_KEXINIT)
    802 		rekeying = 1;
    803 
    804 	packet_send2_wrapped();
    805 
    806 	/* after a NEWKEYS message we can send the complete queue */
    807 	if (type == SSH2_MSG_NEWKEYS) {
    808 		rekeying = 0;
    809 		while ((p = TAILQ_FIRST(&outgoing)) != NULL) {
    810 			type = p->type;
    811 			debug("dequeue packet: %u", type);
    812 			buffer_free(&outgoing_packet);
    813 			memcpy(&outgoing_packet, &p->payload, sizeof(Buffer));
    814 			TAILQ_REMOVE(&outgoing, p, next);
    815 			xfree(p);
    816 			packet_send2_wrapped();
    817 		}
    818 	}
    819 }
    820 
    821 void
    822 packet_send(void)
    823 {
    824 	if (compat20)
    825 		packet_send2();
    826 	else
    827 		packet_send1();
    828 	DBG(debug("packet_send done"));
    829 }
    830 
    831 /*
    832  * Waits until a packet has been received, and returns its type.  Note that
    833  * no other data is processed until this returns, so this function should not
    834  * be used during the interactive session.
    835  */
    836 
    837 int
    838 packet_read_seqnr(u_int32_t *seqnr_p)
    839 {
    840 	int type, len;
    841 	fd_set *setp;
    842 	char buf[8192];
    843 	DBG(debug("packet_read()"));
    844 
    845 	setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
    846 	    sizeof(fd_mask));
    847 
    848 	/* Since we are blocking, ensure that all written packets have been sent. */
    849 	packet_write_wait();
    850 
    851 	/* Stay in the loop until we have received a complete packet. */
    852 	for (;;) {
    853 		/* Try to read a packet from the buffer. */
    854 		type = packet_read_poll_seqnr(seqnr_p);
    855 		if (!compat20 && (
    856 		    type == SSH_SMSG_SUCCESS
    857 		    || type == SSH_SMSG_FAILURE
    858 		    || type == SSH_CMSG_EOF
    859 		    || type == SSH_CMSG_EXIT_CONFIRMATION))
    860 			packet_check_eom();
    861 		/* If we got a packet, return it. */
    862 		if (type != SSH_MSG_NONE) {
    863 			xfree(setp);
    864 			return type;
    865 		}
    866 		/*
    867 		 * Otherwise, wait for some data to arrive, add it to the
    868 		 * buffer, and try again.
    869 		 */
    870 		memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
    871 		    sizeof(fd_mask));
    872 		FD_SET(connection_in, setp);
    873 
    874 		/* Wait for some data to arrive. */
    875 		while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
    876 		    (errno == EAGAIN || errno == EINTR))
    877 			;
    878 
    879 		/* Read data from the socket. */
    880 		len = read(connection_in, buf, sizeof(buf));
    881 		if (len == 0) {
    882 			log("Connection closed by %.200s", get_remote_ipaddr());
    883 			fatal_cleanup();
    884 		}
    885 		if (len < 0)
    886 			fatal("Read from socket failed: %.100s", strerror(errno));
    887 		/* Append it to the buffer. */
    888 		packet_process_incoming(buf, len);
    889 	}
    890 	/* NOTREACHED */
    891 }
    892 
    893 int
    894 packet_read(void)
    895 {
    896 	return packet_read_seqnr(NULL);
    897 }
    898 
    899 /*
    900  * Waits until a packet has been received, verifies that its type matches
    901  * that given, and gives a fatal error and exits if there is a mismatch.
    902  */
    903 
    904 void
    905 packet_read_expect(int expected_type)
    906 {
    907 	int type;
    908 
    909 	type = packet_read();
    910 	if (type != expected_type)
    911 		packet_disconnect("Protocol error: expected packet type %d, got %d",
    912 		    expected_type, type);
    913 }
    914 
    915 /* Checks if a full packet is available in the data received so far via
    916  * packet_process_incoming.  If so, reads the packet; otherwise returns
    917  * SSH_MSG_NONE.  This does not wait for data from the connection.
    918  *
    919  * SSH_MSG_DISCONNECT is handled specially here.  Also,
    920  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
    921  * to higher levels.
    922  */
    923 
    924 static int
    925 packet_read_poll1(void)
    926 {
    927 	u_int len, padded_len;
    928 	u_char *cp, type;
    929 	u_int checksum, stored_checksum;
    930 
    931 	/* Check if input size is less than minimum packet size. */
    932 	if (buffer_len(&input) < 4 + 8)
    933 		return SSH_MSG_NONE;
    934 	/* Get length of incoming packet. */
    935 	cp = buffer_ptr(&input);
    936 	len = GET_32BIT(cp);
    937 	if (len < 1 + 2 + 2 || len > 256 * 1024)
    938 		packet_disconnect("Bad packet length %d.", len);
    939 	padded_len = (len + 8) & ~7;
    940 
    941 	/* Check if the packet has been entirely received. */
    942 	if (buffer_len(&input) < 4 + padded_len)
    943 		return SSH_MSG_NONE;
    944 
    945 	/* The entire packet is in buffer. */
    946 
    947 	/* Consume packet length. */
    948 	buffer_consume(&input, 4);
    949 
    950 	/*
    951 	 * Cryptographic attack detector for ssh
    952 	 * (C)1998 CORE-SDI, Buenos Aires Argentina
    953 	 * Ariel Futoransky(futo (at) core-sdi.com)
    954 	 */
    955 	if (!receive_context.plaintext) {
    956 		switch (detect_attack(buffer_ptr(&input), padded_len, NULL)) {
    957 		case DEATTACK_DETECTED:
    958 			packet_disconnect("crc32 compensation attack: "
    959 			    "network attack detected");
    960 			break;
    961 		case DEATTACK_DOS_DETECTED:
    962 			packet_disconnect("deattack denial of "
    963 			    "service detected");
    964 			break;
    965 		}
    966 	}
    967 
    968 	/* Decrypt data to incoming_packet. */
    969 	buffer_clear(&incoming_packet);
    970 	cp = buffer_append_space(&incoming_packet, padded_len);
    971 	cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
    972 
    973 	buffer_consume(&input, padded_len);
    974 
    975 #ifdef PACKET_DEBUG
    976 	fprintf(stderr, "read_poll plain: ");
    977 	buffer_dump(&incoming_packet);
    978 #endif
    979 
    980 	/* Compute packet checksum. */
    981 	checksum = ssh_crc32(buffer_ptr(&incoming_packet),
    982 	    buffer_len(&incoming_packet) - 4);
    983 
    984 	/* Skip padding. */
    985 	buffer_consume(&incoming_packet, 8 - len % 8);
    986 
    987 	/* Test check bytes. */
    988 	if (len != buffer_len(&incoming_packet))
    989 		packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
    990 		    len, buffer_len(&incoming_packet));
    991 
    992 	cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
    993 	stored_checksum = GET_32BIT(cp);
    994 	if (checksum != stored_checksum)
    995 		packet_disconnect("Corrupted check bytes on input.");
    996 	buffer_consume_end(&incoming_packet, 4);
    997 
    998 	if (packet_compression) {
    999 		buffer_clear(&compression_buffer);
   1000 		buffer_uncompress(&incoming_packet, &compression_buffer);
   1001 		buffer_clear(&incoming_packet);
   1002 		buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
   1003 		    buffer_len(&compression_buffer));
   1004 	}
   1005 	type = buffer_get_char(&incoming_packet);
   1006 	return type;
   1007 }
   1008 
   1009 static int
   1010 packet_read_poll2(u_int32_t *seqnr_p)
   1011 {
   1012 	static u_int packet_length = 0;
   1013 	u_int padlen, need;
   1014 	u_char *macbuf, *cp, type;
   1015 	int maclen, block_size;
   1016 	Enc *enc   = NULL;
   1017 	Mac *mac   = NULL;
   1018 	Comp *comp = NULL;
   1019 
   1020 	if (newkeys[MODE_IN] != NULL) {
   1021 		enc  = &newkeys[MODE_IN]->enc;
   1022 		mac  = &newkeys[MODE_IN]->mac;
   1023 		comp = &newkeys[MODE_IN]->comp;
   1024 	}
   1025 	maclen = mac && mac->enabled ? mac->mac_len : 0;
   1026 	block_size = enc ? enc->block_size : 8;
   1027 
   1028 	if (packet_length == 0) {
   1029 		/*
   1030 		 * check if input size is less than the cipher block size,
   1031 		 * decrypt first block and extract length of incoming packet
   1032 		 */
   1033 		if (buffer_len(&input) < block_size)
   1034 			return SSH_MSG_NONE;
   1035 		buffer_clear(&incoming_packet);
   1036 		cp = buffer_append_space(&incoming_packet, block_size);
   1037 		cipher_crypt(&receive_context, cp, buffer_ptr(&input),
   1038 		    block_size);
   1039 		cp = buffer_ptr(&incoming_packet);
   1040 		packet_length = GET_32BIT(cp);
   1041 		if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
   1042 			buffer_dump(&incoming_packet);
   1043 			packet_disconnect("Bad packet length %d.", packet_length);
   1044 		}
   1045 		DBG(debug("input: packet len %u", packet_length + 4));
   1046 		buffer_consume(&input, block_size);
   1047 	}
   1048 	/* we have a partial packet of block_size bytes */
   1049 	need = 4 + packet_length - block_size;
   1050 	DBG(debug("partial packet %d, need %d, maclen %d", block_size,
   1051 	    need, maclen));
   1052 	if (need % block_size != 0)
   1053 		fatal("padding error: need %d block %d mod %d",
   1054 		    need, block_size, need % block_size);
   1055 	/*
   1056 	 * check if the entire packet has been received and
   1057 	 * decrypt into incoming_packet
   1058 	 */
   1059 	if (buffer_len(&input) < need + maclen)
   1060 		return SSH_MSG_NONE;
   1061 #ifdef PACKET_DEBUG
   1062 	fprintf(stderr, "read_poll enc/full: ");