Home | History | Annotate | Download | only in openssh
      1 /* $OpenBSD: packet.c,v 1.214 2015/08/20 22:32:42 deraadt Exp $ */
      2 /*
      3  * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
      4  * Copyright (c) 1995 Tatu Ylonen <ylo (at) cs.hut.fi>, Espoo, Finland
      5  *                    All rights reserved
      6  * This file contains code implementing the packet protocol and communication
      7  * with the other side.  This same code is used both on client and server side.
      8  *
      9  * As far as I am concerned, the code I have written for this software
     10  * can be used freely for any purpose.  Any derived versions of this
     11  * software must be clearly marked as such, and if the derived work is
     12  * incompatible with the protocol description in the RFC file, it must be
     13  * called by a name other than "ssh" or "Secure Shell".
     14  *
     15  *
     16  * SSH2 packet format added by Markus Friedl.
     17  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
     18  *
     19  * Redistribution and use in source and binary forms, with or without
     20  * modification, are permitted provided that the following conditions
     21  * are met:
     22  * 1. Redistributions of source code must retain the above copyright
     23  *    notice, this list of conditions and the following disclaimer.
     24  * 2. Redistributions in binary form must reproduce the above copyright
     25  *    notice, this list of conditions and the following disclaimer in the
     26  *    documentation and/or other materials provided with the distribution.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     31  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     33  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     37  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 #include "includes.h"
     41 
     42 #include <sys/param.h>	/* MIN roundup */
     43 #include <sys/types.h>
     44 #include "openbsd-compat/sys-queue.h"
     45 #include <sys/socket.h>
     46 #ifdef HAVE_SYS_TIME_H
     47 # include <sys/time.h>
     48 #endif
     49 
     50 #include <netinet/in.h>
     51 #include <netinet/ip.h>
     52 #include <arpa/inet.h>
     53 
     54 #include <errno.h>
     55 #include <stdarg.h>
     56 #include <stdio.h>
     57 #include <stdlib.h>
     58 #include <string.h>
     59 #include <unistd.h>
     60 #include <limits.h>
     61 #include <signal.h>
     62 #include <time.h>
     63 
     64 #include <zlib.h>
     65 
     66 #include "buffer.h"	/* typedefs XXX */
     67 #include "key.h"	/* typedefs XXX */
     68 
     69 #include "xmalloc.h"
     70 #include "crc32.h"
     71 #include "deattack.h"
     72 #include "compat.h"
     73 #include "ssh1.h"
     74 #include "ssh2.h"
     75 #include "cipher.h"
     76 #include "sshkey.h"
     77 #include "kex.h"
     78 #include "digest.h"
     79 #include "mac.h"
     80 #include "log.h"
     81 #include "canohost.h"
     82 #include "misc.h"
     83 #include "channels.h"
     84 #include "ssh.h"
     85 #include "packet.h"
     86 #include "roaming.h"
     87 #include "ssherr.h"
     88 #include "sshbuf.h"
     89 
     90 #ifdef PACKET_DEBUG
     91 #define DBG(x) x
     92 #else
     93 #define DBG(x)
     94 #endif
     95 
     96 #define PACKET_MAX_SIZE (256 * 1024)
     97 
     98 struct packet_state {
     99 	u_int32_t seqnr;
    100 	u_int32_t packets;
    101 	u_int64_t blocks;
    102 	u_int64_t bytes;
    103 };
    104 
    105 struct packet {
    106 	TAILQ_ENTRY(packet) next;
    107 	u_char type;
    108 	struct sshbuf *payload;
    109 };
    110 
    111 struct session_state {
    112 	/*
    113 	 * This variable contains the file descriptors used for
    114 	 * communicating with the other side.  connection_in is used for
    115 	 * reading; connection_out for writing.  These can be the same
    116 	 * descriptor, in which case it is assumed to be a socket.
    117 	 */
    118 	int connection_in;
    119 	int connection_out;
    120 
    121 	/* Protocol flags for the remote side. */
    122 	u_int remote_protocol_flags;
    123 
    124 	/* Encryption context for receiving data.  Only used for decryption. */
    125 	struct sshcipher_ctx receive_context;
    126 
    127 	/* Encryption context for sending data.  Only used for encryption. */
    128 	struct sshcipher_ctx send_context;
    129 
    130 	/* Buffer for raw input data from the socket. */
    131 	struct sshbuf *input;
    132 
    133 	/* Buffer for raw output data going to the socket. */
    134 	struct sshbuf *output;
    135 
    136 	/* Buffer for the partial outgoing packet being constructed. */
    137 	struct sshbuf *outgoing_packet;
    138 
    139 	/* Buffer for the incoming packet currently being processed. */
    140 	struct sshbuf *incoming_packet;
    141 
    142 	/* Scratch buffer for packet compression/decompression. */
    143 	struct sshbuf *compression_buffer;
    144 
    145 	/* Incoming/outgoing compression dictionaries */
    146 	z_stream compression_in_stream;
    147 	z_stream compression_out_stream;
    148 	int compression_in_started;
    149 	int compression_out_started;
    150 	int compression_in_failures;
    151 	int compression_out_failures;
    152 
    153 	/*
    154 	 * Flag indicating whether packet compression/decompression is
    155 	 * enabled.
    156 	 */
    157 	int packet_compression;
    158 
    159 	/* default maximum packet size */
    160 	u_int max_packet_size;
    161 
    162 	/* Flag indicating whether this module has been initialized. */
    163 	int initialized;
    164 
    165 	/* Set to true if the connection is interactive. */
    166 	int interactive_mode;
    167 
    168 	/* Set to true if we are the server side. */
    169 	int server_side;
    170 
    171 	/* Set to true if we are authenticated. */
    172 	int after_authentication;
    173 
    174 	int keep_alive_timeouts;
    175 
    176 	/* The maximum time that we will wait to send or receive a packet */
    177 	int packet_timeout_ms;
    178 
    179 	/* Session key information for Encryption and MAC */
    180 	struct newkeys *newkeys[MODE_MAX];
    181 	struct packet_state p_read, p_send;
    182 
    183 	/* Volume-based rekeying */
    184 	u_int64_t max_blocks_in, max_blocks_out;
    185 	u_int32_t rekey_limit;
    186 
    187 	/* Time-based rekeying */
    188 	u_int32_t rekey_interval;	/* how often in seconds */
    189 	time_t rekey_time;	/* time of last rekeying */
    190 
    191 	/* Session key for protocol v1 */
    192 	u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
    193 	u_int ssh1_keylen;
    194 
    195 	/* roundup current message to extra_pad bytes */
    196 	u_char extra_pad;
    197 
    198 	/* XXX discard incoming data after MAC error */
    199 	u_int packet_discard;
    200 	struct sshmac *packet_discard_mac;
    201 
    202 	/* Used in packet_read_poll2() */
    203 	u_int packlen;
    204 
    205 	/* Used in packet_send2 */
    206 	int rekeying;
    207 
    208 	/* Used in packet_set_interactive */
    209 	int set_interactive_called;
    210 
    211 	/* Used in packet_set_maxsize */
    212 	int set_maxsize_called;
    213 
    214 	/* One-off warning about weak ciphers */
    215 	int cipher_warning_done;
    216 
    217 	/* SSH1 CRC compensation attack detector */
    218 	struct deattack_ctx deattack;
    219 
    220 	TAILQ_HEAD(, packet) outgoing;
    221 };
    222 
    223 struct ssh *
    224 ssh_alloc_session_state(void)
    225 {
    226 	struct ssh *ssh = NULL;
    227 	struct session_state *state = NULL;
    228 
    229 	if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
    230 	    (state = calloc(1, sizeof(*state))) == NULL ||
    231 	    (state->input = sshbuf_new()) == NULL ||
    232 	    (state->output = sshbuf_new()) == NULL ||
    233 	    (state->outgoing_packet = sshbuf_new()) == NULL ||
    234 	    (state->incoming_packet = sshbuf_new()) == NULL)
    235 		goto fail;
    236 	TAILQ_INIT(&state->outgoing);
    237 	TAILQ_INIT(&ssh->private_keys);
    238 	TAILQ_INIT(&ssh->public_keys);
    239 	state->connection_in = -1;
    240 	state->connection_out = -1;
    241 	state->max_packet_size = 32768;
    242 	state->packet_timeout_ms = -1;
    243 	state->p_send.packets = state->p_read.packets = 0;
    244 	state->initialized = 1;
    245 	/*
    246 	 * ssh_packet_send2() needs to queue packets until
    247 	 * we've done the initial key exchange.
    248 	 */
    249 	state->rekeying = 1;
    250 	ssh->state = state;
    251 	return ssh;
    252  fail:
    253 	if (state) {
    254 		sshbuf_free(state->input);
    255 		sshbuf_free(state->output);
    256 		sshbuf_free(state->incoming_packet);
    257 		sshbuf_free(state->outgoing_packet);
    258 		free(state);
    259 	}
    260 	free(ssh);
    261 	return NULL;
    262 }
    263 
    264 /*
    265  * Sets the descriptors used for communication.  Disables encryption until
    266  * packet_set_encryption_key is called.
    267  */
    268 struct ssh *
    269 ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
    270 {
    271 	struct session_state *state;
    272 	const struct sshcipher *none = cipher_by_name("none");
    273 	int r;
    274 
    275 	if (none == NULL) {
    276 		error("%s: cannot load cipher 'none'", __func__);
    277 		return NULL;
    278 	}
    279 	if (ssh == NULL)
    280 		ssh = ssh_alloc_session_state();
    281 	if (ssh == NULL) {
    282 		error("%s: cound not allocate state", __func__);
    283 		return NULL;
    284 	}
    285 	state = ssh->state;
    286 	state->connection_in = fd_in;
    287 	state->connection_out = fd_out;
    288 	if ((r = cipher_init(&state->send_context, none,
    289 	    (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
    290 	    (r = cipher_init(&state->receive_context, none,
    291 	    (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
    292 		error("%s: cipher_init failed: %s", __func__, ssh_err(r));
    293 		free(ssh);
    294 		return NULL;
    295 	}
    296 	state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
    297 	deattack_init(&state->deattack);
    298 	/*
    299 	 * Cache the IP address of the remote connection for use in error
    300 	 * messages that might be generated after the connection has closed.
    301 	 */
    302 	(void)ssh_remote_ipaddr(ssh);
    303 	return ssh;
    304 }
    305 
    306 void
    307 ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
    308 {
    309 	struct session_state *state = ssh->state;
    310 
    311 	if (timeout <= 0 || count <= 0) {
    312 		state->packet_timeout_ms = -1;
    313 		return;
    314 	}
    315 	if ((INT_MAX / 1000) / count < timeout)
    316 		state->packet_timeout_ms = INT_MAX;
    317 	else
    318 		state->packet_timeout_ms = timeout * count * 1000;
    319 }
    320 
    321 int
    322 ssh_packet_stop_discard(struct ssh *ssh)
    323 {
    324 	struct session_state *state = ssh->state;
    325 	int r;
    326 
    327 	if (state->packet_discard_mac) {
    328 		char buf[1024];
    329 
    330 		memset(buf, 'a', sizeof(buf));
    331 		while (sshbuf_len(state->incoming_packet) <
    332 		    PACKET_MAX_SIZE)
    333 			if ((r = sshbuf_put(state->incoming_packet, buf,
    334 			    sizeof(buf))) != 0)
    335 				return r;
    336 		(void) mac_compute(state->packet_discard_mac,
    337 		    state->p_read.seqnr,
    338 		    sshbuf_ptr(state->incoming_packet), PACKET_MAX_SIZE,
    339 		    NULL, 0);
    340 	}
    341 	logit("Finished discarding for %.200s", ssh_remote_ipaddr(ssh));
    342 	return SSH_ERR_MAC_INVALID;
    343 }
    344 
    345 static int
    346 ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
    347     struct sshmac *mac, u_int packet_length, u_int discard)
    348 {
    349 	struct session_state *state = ssh->state;
    350 	int r;
    351 
    352 	if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
    353 		if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
    354 			return r;
    355 		return SSH_ERR_MAC_INVALID;
    356 	}
    357 	if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
    358 		state->packet_discard_mac = mac;
    359 	if (sshbuf_len(state->input) >= discard &&
    360 	   (r = ssh_packet_stop_discard(ssh)) != 0)
    361 		return r;
    362 	state->packet_discard = discard - sshbuf_len(state->input);
    363 	return 0;
    364 }
    365 
    366 /* Returns 1 if remote host is connected via socket, 0 if not. */
    367 
    368 int
    369 ssh_packet_connection_is_on_socket(struct ssh *ssh)
    370 {
    371 	struct session_state *state = ssh->state;
    372 	struct sockaddr_storage from, to;
    373 	socklen_t fromlen, tolen;
    374 
    375 	/* filedescriptors in and out are the same, so it's a socket */
    376 	if (state->connection_in == state->connection_out)
    377 		return 1;
    378 	fromlen = sizeof(from);
    379 	memset(&from, 0, sizeof(from));
    380 	if (getpeername(state->connection_in, (struct sockaddr *)&from,
    381 	    &fromlen) < 0)
    382 		return 0;
    383 	tolen = sizeof(to);
    384 	memset(&to, 0, sizeof(to));
    385 	if (getpeername(state->connection_out, (struct sockaddr *)&to,
    386 	    &tolen) < 0)
    387 		return 0;
    388 	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
    389 		return 0;
    390 	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
    391 		return 0;
    392 	return 1;
    393 }
    394 
    395 void
    396 ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
    397 {
    398 	if (ibytes)
    399 		*ibytes = ssh->state->p_read.bytes;
    400 	if (obytes)
    401 		*obytes = ssh->state->p_send.bytes;
    402 }
    403 
    404 int
    405 ssh_packet_connection_af(struct ssh *ssh)
    406 {
    407 	struct sockaddr_storage to;
    408 	socklen_t tolen = sizeof(to);
    409 
    410 	memset(&to, 0, sizeof(to));
    411 	if (getsockname(ssh->state->connection_out, (struct sockaddr *)&to,
    412 	    &tolen) < 0)
    413 		return 0;
    414 #ifdef IPV4_IN_IPV6
    415 	if (to.ss_family == AF_INET6 &&
    416 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&to)->sin6_addr))
    417 		return AF_INET;
    418 #endif
    419 	return to.ss_family;
    420 }
    421 
    422 /* Sets the connection into non-blocking mode. */
    423 
    424 void
    425 ssh_packet_set_nonblocking(struct ssh *ssh)
    426 {
    427 	/* Set the socket into non-blocking mode. */
    428 	set_nonblock(ssh->state->connection_in);
    429 
    430 	if (ssh->state->connection_out != ssh->state->connection_in)
    431 		set_nonblock(ssh->state->connection_out);
    432 }
    433 
    434 /* Returns the socket used for reading. */
    435 
    436 int
    437 ssh_packet_get_connection_in(struct ssh *ssh)
    438 {
    439 	return ssh->state->connection_in;
    440 }
    441 
    442 /* Returns the descriptor used for writing. */
    443 
    444 int
    445 ssh_packet_get_connection_out(struct ssh *ssh)
    446 {
    447 	return ssh->state->connection_out;
    448 }
    449 
    450 /*
    451  * Returns the IP-address of the remote host as a string.  The returned
    452  * string must not be freed.
    453  */
    454 
    455 const char *
    456 ssh_remote_ipaddr(struct ssh *ssh)
    457 {
    458 	/* Check whether we have cached the ipaddr. */
    459 	if (ssh->remote_ipaddr == NULL)
    460 		ssh->remote_ipaddr = ssh_packet_connection_is_on_socket(ssh) ?
    461 		    get_peer_ipaddr(ssh->state->connection_in) :
    462 		    strdup("UNKNOWN");
    463 	if (ssh->remote_ipaddr == NULL)
    464 		return "UNKNOWN";
    465 	return ssh->remote_ipaddr;
    466 }
    467 
    468 /* Closes the connection and clears and frees internal data structures. */
    469 
    470 void
    471 ssh_packet_close(struct ssh *ssh)
    472 {
    473 	struct session_state *state = ssh->state;
    474 	int r;
    475 	u_int mode;
    476 
    477 	if (!state->initialized)
    478 		return;
    479 	state->initialized = 0;
    480 	if (state->connection_in == state->connection_out) {
    481 		shutdown(state->connection_out, SHUT_RDWR);
    482 		close(state->connection_out);
    483 	} else {
    484 		close(state->connection_in);
    485 		close(state->connection_out);
    486 	}
    487 	sshbuf_free(state->input);
    488 	sshbuf_free(state->output);
    489 	sshbuf_free(state->outgoing_packet);
    490 	sshbuf_free(state->incoming_packet);
    491 	for (mode = 0; mode < MODE_MAX; mode++)
    492 		kex_free_newkeys(state->newkeys[mode]);
    493 	if (state->compression_buffer) {
    494 		sshbuf_free(state->compression_buffer);
    495 		if (state->compression_out_started) {
    496 			z_streamp stream = &state->compression_out_stream;
    497 			debug("compress outgoing: "
    498 			    "raw data %llu, compressed %llu, factor %.2f",
    499 				(unsigned long long)stream->total_in,
    500 				(unsigned long long)stream->total_out,
    501 				stream->total_in == 0 ? 0.0 :
    502 				(double) stream->total_out / stream->total_in);
    503 			if (state->compression_out_failures == 0)
    504 				deflateEnd(stream);
    505 		}
    506 		if (state->compression_in_started) {
    507 			z_streamp stream = &state->compression_out_stream;
    508 			debug("compress incoming: "
    509 			    "raw data %llu, compressed %llu, factor %.2f",
    510 			    (unsigned long long)stream->total_out,
    511 			    (unsigned long long)stream->total_in,
    512 			    stream->total_out == 0 ? 0.0 :
    513 			    (double) stream->total_in / stream->total_out);
    514 			if (state->compression_in_failures == 0)
    515 				inflateEnd(stream);
    516 		}
    517 	}
    518 	if ((r = cipher_cleanup(&state->send_context)) != 0)
    519 		error("%s: cipher_cleanup failed: %s", __func__, ssh_err(r));
    520 	if ((r = cipher_cleanup(&state->receive_context)) != 0)
    521 		error("%s: cipher_cleanup failed: %s", __func__, ssh_err(r));
    522 	if (ssh->remote_ipaddr) {
    523 		free(ssh->remote_ipaddr);
    524 		ssh->remote_ipaddr = NULL;
    525 	}
    526 	free(ssh->state);
    527 	ssh->state = NULL;
    528 }
    529 
    530 /* Sets remote side protocol flags. */
    531 
    532 void
    533 ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
    534 {
    535 	ssh->state->remote_protocol_flags = protocol_flags;
    536 }
    537 
    538 /* Returns the remote protocol flags set earlier by the above function. */
    539 
    540 u_int
    541 ssh_packet_get_protocol_flags(struct ssh *ssh)
    542 {
    543 	return ssh->state->remote_protocol_flags;
    544 }
    545 
    546 /*
    547  * Starts packet compression from the next packet on in both directions.
    548  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
    549  */
    550 
    551 static int
    552 ssh_packet_init_compression(struct ssh *ssh)
    553 {
    554 	if (!ssh->state->compression_buffer &&
    555 	   ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
    556 		return SSH_ERR_ALLOC_FAIL;
    557 	return 0;
    558 }
    559 
    560 static int
    561 start_compression_out(struct ssh *ssh, int level)
    562 {
    563 	if (level < 1 || level > 9)
    564 		return SSH_ERR_INVALID_ARGUMENT;
    565 	debug("Enabling compression at level %d.", level);
    566 	if (ssh->state->compression_out_started == 1)
    567 		deflateEnd(&ssh->state->compression_out_stream);
    568 	switch (deflateInit(&ssh->state->compression_out_stream, level)) {
    569 	case Z_OK:
    570 		ssh->state->compression_out_started = 1;
    571 		break;
    572 	case Z_MEM_ERROR:
    573 		return SSH_ERR_ALLOC_FAIL;
    574 	default:
    575 		return SSH_ERR_INTERNAL_ERROR;
    576 	}
    577 	return 0;
    578 }
    579 
    580 static int
    581 start_compression_in(struct ssh *ssh)
    582 {
    583 	if (ssh->state->compression_in_started == 1)
    584 		inflateEnd(&ssh->state->compression_in_stream);
    585 	switch (inflateInit(&ssh->state->compression_in_stream)) {
    586 	case Z_OK:
    587 		ssh->state->compression_in_started = 1;
    588 		break;
    589 	case Z_MEM_ERROR:
    590 		return SSH_ERR_ALLOC_FAIL;
    591 	default:
    592 		return SSH_ERR_INTERNAL_ERROR;
    593 	}
    594 	return 0;
    595 }
    596 
    597 int
    598 ssh_packet_start_compression(struct ssh *ssh, int level)
    599 {
    600 	int r;
    601 
    602 	if (ssh->state->packet_compression && !compat20)
    603 		return SSH_ERR_INTERNAL_ERROR;
    604 	ssh->state->packet_compression = 1;
    605 	if ((r = ssh_packet_init_compression(ssh)) != 0 ||
    606 	    (r = start_compression_in(ssh)) != 0 ||
    607 	    (r = start_compression_out(ssh, level)) != 0)
    608 		return r;
    609 	return 0;
    610 }
    611 
    612 /* XXX remove need for separate compression buffer */
    613 static int
    614 compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
    615 {
    616 	u_char buf[4096];
    617 	int r, status;
    618 
    619 	if (ssh->state->compression_out_started != 1)
    620 		return SSH_ERR_INTERNAL_ERROR;
    621 
    622 	/* This case is not handled below. */
    623 	if (sshbuf_len(in) == 0)
    624 		return 0;
    625 
    626 	/* Input is the contents of the input buffer. */
    627 	if ((ssh->state->compression_out_stream.next_in =
    628 	    sshbuf_mutable_ptr(in)) == NULL)
    629 		return SSH_ERR_INTERNAL_ERROR;
    630 	ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
    631 
    632 	/* Loop compressing until deflate() returns with avail_out != 0. */
    633 	do {
    634 		/* Set up fixed-size output buffer. */
    635 		ssh->state->compression_out_stream.next_out = buf;
    636 		ssh->state->compression_out_stream.avail_out = sizeof(buf);
    637 
    638 		/* Compress as much data into the buffer as possible. */
    639 		status = deflate(&ssh->state->compression_out_stream,
    640 		    Z_PARTIAL_FLUSH);
    641 		switch (status) {
    642 		case Z_MEM_ERROR:
    643 			return SSH_ERR_ALLOC_FAIL;
    644 		case Z_OK:
    645 			/* Append compressed data to output_buffer. */
    646 			if ((r = sshbuf_put(out, buf, sizeof(buf) -
    647 			    ssh->state->compression_out_stream.avail_out)) != 0)
    648 				return r;
    649 			break;
    650 		case Z_STREAM_ERROR:
    651 		default:
    652 			ssh->state->compression_out_failures++;
    653 			return SSH_ERR_INVALID_FORMAT;
    654 		}
    655 	} while (ssh->state->compression_out_stream.avail_out == 0);
    656 	return 0;
    657 }
    658 
    659 static int
    660 uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
    661 {
    662 	u_char buf[4096];
    663 	int r, status;
    664 
    665 	if (ssh->state->compression_in_started != 1)
    666 		return SSH_ERR_INTERNAL_ERROR;
    667 
    668 	if ((ssh->state->compression_in_stream.next_in =
    669 	    sshbuf_mutable_ptr(in)) == NULL)
    670 		return SSH_ERR_INTERNAL_ERROR;
    671 	ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
    672 
    673 	for (;;) {
    674 		/* Set up fixed-size output buffer. */
    675 		ssh->state->compression_in_stream.next_out = buf;
    676 		ssh->state->compression_in_stream.avail_out = sizeof(buf);
    677 
    678 		status = inflate(&ssh->state->compression_in_stream,
    679 		    Z_PARTIAL_FLUSH);
    680 		switch (status) {
    681 		case Z_OK:
    682 			if ((r = sshbuf_put(out, buf, sizeof(buf) -
    683 			    ssh->state->compression_in_stream.avail_out)) != 0)
    684 				return r;
    685 			break;
    686 		case Z_BUF_ERROR:
    687 			/*
    688 			 * Comments in zlib.h say that we should keep calling
    689 			 * inflate() until we get an error.  This appears to
    690 			 * be the error that we get.
    691 			 */
    692 			return 0;
    693 		case Z_DATA_ERROR:
    694 			return SSH_ERR_INVALID_FORMAT;
    695 		case Z_MEM_ERROR:
    696 			return SSH_ERR_ALLOC_FAIL;
    697 		case Z_STREAM_ERROR:
    698 		default:
    699 			ssh->state->compression_in_failures++;
    700 			return SSH_ERR_INTERNAL_ERROR;
    701 		}
    702 	}
    703 	/* NOTREACHED */
    704 }
    705 
    706 /* Serialise compression state into a blob for privsep */
    707 static int
    708 ssh_packet_get_compress_state(struct sshbuf *m, struct ssh *ssh)
    709 {
    710 	struct session_state *state = ssh->state;
    711 	struct sshbuf *b;
    712 	int r;
    713 
    714 	if ((b = sshbuf_new()) == NULL)
    715 		return SSH_ERR_ALLOC_FAIL;
    716 	if (state->compression_in_started) {
    717 		if ((r = sshbuf_put_string(b, &state->compression_in_stream,
    718 		    sizeof(state->compression_in_stream))) != 0)
    719 			goto out;
    720 	} else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
    721 		goto out;
    722 	if (state->compression_out_started) {
    723 		if ((r = sshbuf_put_string(b, &state->compression_out_stream,
    724 		    sizeof(state->compression_out_stream))) != 0)
    725 			goto out;
    726 	} else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
    727 		goto out;
    728 	r = sshbuf_put_stringb(m, b);
    729  out:
    730 	sshbuf_free(b);
    731 	return r;
    732 }
    733 
    734 /* Deserialise compression state from a blob for privsep */
    735 static int
    736 ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
    737 {
    738 	struct session_state *state = ssh->state;
    739 	struct sshbuf *b = NULL;
    740 	int r;
    741 	const u_char *inblob, *outblob;
    742 	size_t inl, outl;
    743 
    744 	if ((r = sshbuf_froms(m, &b)) != 0)
    745 		goto out;
    746 	if ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 ||
    747 	    (r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0)
    748 		goto out;
    749 	if (inl == 0)
    750 		state->compression_in_started = 0;
    751 	else if (inl != sizeof(state->compression_in_stream)) {
    752 		r = SSH_ERR_INTERNAL_ERROR;
    753 		goto out;
    754 	} else {
    755 		state->compression_in_started = 1;
    756 		memcpy(&state->compression_in_stream, inblob, inl);
    757 	}
    758 	if (outl == 0)
    759 		state->compression_out_started = 0;
    760 	else if (outl != sizeof(state->compression_out_stream)) {
    761 		r = SSH_ERR_INTERNAL_ERROR;
    762 		goto out;
    763 	} else {
    764 		state->compression_out_started = 1;
    765 		memcpy(&state->compression_out_stream, outblob, outl);
    766 	}
    767 	r = 0;
    768  out:
    769 	sshbuf_free(b);
    770 	return r;
    771 }
    772 
    773 void
    774 ssh_packet_set_compress_hooks(struct ssh *ssh, void *ctx,
    775     void *(*allocfunc)(void *, u_int, u_int),
    776     void (*freefunc)(void *, void *))
    777 {
    778 	ssh->state->compression_out_stream.zalloc = (alloc_func)allocfunc;
    779 	ssh->state->compression_out_stream.zfree = (free_func)freefunc;
    780 	ssh->state->compression_out_stream.opaque = ctx;
    781 	ssh->state->compression_in_stream.zalloc = (alloc_func)allocfunc;
    782 	ssh->state->compression_in_stream.zfree = (free_func)freefunc;
    783 	ssh->state->compression_in_stream.opaque = ctx;
    784 }
    785 
    786 /*
    787  * Causes any further packets to be encrypted using the given key.  The same
    788  * key is used for both sending and reception.  However, both directions are
    789  * encrypted independently of each other.
    790  */
    791 
    792 void
    793 ssh_packet_set_encryption_key(struct ssh *ssh, const u_char *key, u_int keylen, int number)
    794 {
    795 #ifndef WITH_SSH1
    796 	fatal("no SSH protocol 1 support");
    797 #else /* WITH_SSH1 */
    798 	struct session_state *state = ssh->state;
    799 	const struct sshcipher *cipher = cipher_by_number(number);
    800 	int r;
    801 	const char *wmsg;
    802 
    803 	if (cipher == NULL)
    804 		fatal("%s: unknown cipher number %d", __func__, number);
    805 	if (keylen < 20)
    806 		fatal("%s: keylen too small: %d", __func__, keylen);
    807 	if (keylen > SSH_SESSION_KEY_LENGTH)
    808 		fatal("%s: keylen too big: %d", __func__, keylen);
    809 	memcpy(state->ssh1_key, key, keylen);
    810 	state->ssh1_keylen = keylen;
    811 	if ((r = cipher_init(&state->send_context, cipher, key, keylen,
    812 	    NULL, 0, CIPHER_ENCRYPT)) != 0 ||
    813 	    (r = cipher_init(&state->receive_context, cipher, key, keylen,
    814 	    NULL, 0, CIPHER_DECRYPT) != 0))
    815 		fatal("%s: cipher_init failed: %s", __func__, ssh_err(r));
    816 	if (!state->cipher_warning_done &&
    817 	    ((wmsg = cipher_warning_message(&state->send_context)) != NULL ||
    818 	    (wmsg = cipher_warning_message(&state->send_context)) != NULL)) {
    819 		error("Warning: %s", wmsg);
    820 		state->cipher_warning_done = 1;
    821 	}
    822 #endif /* WITH_SSH1 */
    823 }
    824 
    825 /*
    826  * Finalizes and sends the packet.  If the encryption key has been set,
    827  * encrypts the packet before sending.
    828  */
    829 
    830 int
    831 ssh_packet_send1(struct ssh *ssh)
    832 {
    833 	struct session_state *state = ssh->state;
    834 	u_char buf[8], *cp;
    835 	int r, padding, len;
    836 	u_int checksum;
    837 
    838 	/*
    839 	 * If using packet compression, compress the payload of the outgoing
    840 	 * packet.
    841 	 */
    842 	if (state->packet_compression) {
    843 		sshbuf_reset(state->compression_buffer);
    844 		/* Skip padding. */
    845 		if ((r = sshbuf_consume(state->outgoing_packet, 8)) != 0)
    846 			goto out;
    847 		/* padding */
    848 		if ((r = sshbuf_put(state->compression_buffer,
    849 		    "\0\0\0\0\0\0\0\0", 8)) != 0)
    850 			goto out;
    851 		if ((r = compress_buffer(ssh, state->outgoing_packet,
    852 		    state->compression_buffer)) != 0)
    853 			goto out;
    854 		sshbuf_reset(state->outgoing_packet);
    855                 if ((r = sshbuf_putb(state->outgoing_packet,
    856                     state->compression_buffer)) != 0)
    857 			goto out;
    858 	}
    859 	/* Compute packet length without padding (add checksum, remove padding). */
    860 	len = sshbuf_len(state->outgoing_packet) + 4 - 8;
    861 
    862 	/* Insert padding. Initialized to zero in packet_start1() */
    863 	padding = 8 - len % 8;
    864 	if (!state->send_context.plaintext) {
    865 		cp = sshbuf_mutable_ptr(state->outgoing_packet);
    866 		if (cp == NULL) {
    867 			r = SSH_ERR_INTERNAL_ERROR;
    868 			goto out;
    869 		}
    870 		arc4random_buf(cp + 8 - padding, padding);
    871 	}
    872 	if ((r = sshbuf_consume(state->outgoing_packet, 8 - padding)) != 0)
    873 		goto out;
    874 
    875 	/* Add check bytes. */
    876 	checksum = ssh_crc32(sshbuf_ptr(state->outgoing_packet),
    877 	    sshbuf_len(state->outgoing_packet));
    878 	POKE_U32(buf, checksum);
    879 	if ((r = sshbuf_put(state->outgoing_packet, buf, 4)) != 0)
    880 		goto out;
    881 
    882 #ifdef PACKET_DEBUG
    883 	fprintf(stderr, "packet_send plain: ");
    884 	sshbuf_dump(state->outgoing_packet, stderr);
    885 #endif
    886 
    887 	/* Append to output. */
    888 	POKE_U32(buf, len);
    889 	if ((r = sshbuf_put(state->output, buf, 4)) != 0)
    890 		goto out;
    891 	if ((r = sshbuf_reserve(state->output,
    892 	    sshbuf_len(state->outgoing_packet), &cp)) != 0)
    893 		goto out;
    894 	if ((r = cipher_crypt(&state->send_context, 0, cp,
    895 	    sshbuf_ptr(state->outgoing_packet),
    896 	    sshbuf_len(state->outgoing_packet), 0, 0)) != 0)
    897 		goto out;
    898 
    899 #ifdef PACKET_DEBUG
    900 	fprintf(stderr, "encrypted: ");
    901 	sshbuf_dump(state->output, stderr);
    902 #endif
    903 	state->p_send.packets++;
    904 	state->p_send.bytes += len +
    905 	    sshbuf_len(state->outgoing_packet);
    906 	sshbuf_reset(state->outgoing_packet);
    907 
    908 	/*
    909 	 * Note that the packet is now only buffered in output.  It won't be
    910 	 * actually sent until ssh_packet_write_wait or ssh_packet_write_poll
    911 	 * is called.
    912 	 */
    913 	r = 0;
    914  out:
    915 	return r;
    916 }
    917 
    918 int
    919 ssh_set_newkeys(struct ssh *ssh, int mode)
    920 {
    921 	struct session_state *state = ssh->state;
    922 	struct sshenc *enc;
    923 	struct sshmac *mac;
    924 	struct sshcomp *comp;
    925 	struct sshcipher_ctx *cc;
    926 	u_int64_t *max_blocks;
    927 	const char *wmsg;
    928 	int r, crypt_type;
    929 
    930 	debug2("set_newkeys: mode %d", mode);
    931 
    932 	if (mode == MODE_OUT) {
    933 		cc = &state->send_context;
    934 		crypt_type = CIPHER_ENCRYPT;
    935 		state->p_send.packets = state->p_send.blocks = 0;
    936 		max_blocks = &state->max_blocks_out;
    937 	} else {
    938 		cc = &state->receive_context;
    939 		crypt_type = CIPHER_DECRYPT;
    940 		state->p_read.packets = state->p_read.blocks = 0;
    941 		max_blocks = &state->max_blocks_in;
    942 	}
    943 	if (state->newkeys[mode] != NULL) {
    944 		debug("set_newkeys: rekeying");
    945 		if ((r = cipher_cleanup(cc)) != 0)
    946 			return r;
    947 		enc  = &state->newkeys[mode]->enc;
    948 		mac  = &state->newkeys[mode]->mac;
    949 		comp = &state->newkeys[mode]->comp;
    950 		mac_clear(mac);
    951 		explicit_bzero(enc->iv,  enc->iv_len);
    952 		explicit_bzero(enc->key, enc->key_len);
    953 		explicit_bzero(mac->key, mac->key_len);
    954 		free(enc->name);
    955 		free(enc->iv);
    956 		free(enc->key);
    957 		free(mac->name);
    958 		free(mac->key);
    959 		free(comp->name);
    960 		free(state->newkeys[mode]);
    961 	}
    962 	/* move newkeys from kex to state */
    963 	if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
    964 		return SSH_ERR_INTERNAL_ERROR;
    965 	ssh->kex->newkeys[mode] = NULL;
    966 	enc  = &state->newkeys[mode]->enc;
    967 	mac  = &state->newkeys[mode]->mac;
    968 	comp = &state->newkeys[mode]->comp;
    969 	if (cipher_authlen(enc->cipher) == 0) {
    970 		if ((r = mac_init(mac)) != 0)
    971 			return r;
    972 	}
    973 	mac->enabled = 1;
    974 	DBG(debug("cipher_init_context: %d", mode));
    975 	if ((r = cipher_init(cc, enc->cipher, enc->key, enc->key_len,
    976 	    enc->iv, enc->iv_len, crypt_type)) != 0)
    977 		return r;
    978 	if (!state->cipher_warning_done &&
    979 	    (wmsg = cipher_warning_message(cc)) != NULL) {
    980 		error("Warning: %s", wmsg);
    981 		state->cipher_warning_done = 1;
    982 	}
    983 	/* Deleting the keys does not gain extra security */
    984 	/* explicit_bzero(enc->iv,  enc->block_size);
    985 	   explicit_bzero(enc->key, enc->key_len);
    986 	   explicit_bzero(mac->key, mac->key_len); */
    987 	if ((comp->type == COMP_ZLIB ||
    988 	    (comp->type == COMP_DELAYED &&
    989 	     state->after_authentication)) && comp->enabled == 0) {
    990 		if ((r = ssh_packet_init_compression(ssh)) < 0)
    991 			return r;
    992 		if (mode == MODE_OUT) {
    993 			if ((r = start_compression_out(ssh, 6)) != 0)
    994 				return r;
    995 		} else {
    996 			if ((r = start_compression_in(ssh)) != 0)
    997 				return r;
    998 		}
    999 		comp->enabled = 1;
   1000 	}
   1001 	/*
   1002 	 * The 2^(blocksize*2) limit is too expensive for 3DES,
   1003 	 * blowfish, etc, so enforce a 1GB limit for small blocksizes.
   1004 	 */
   1005 	if (enc->block_size >= 16)
   1006 		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
   1007 	else
   1008 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
   1009 	if (state->rekey_limit)
   1010 		*max_blocks = MIN(*max_blocks,
   1011 		    state->rekey_limit / enc->block_size);
   1012 	return 0;
   1013 }
   1014 
   1015 /*
   1016  * Delayed compression for SSH2 is enabled after authentication:
   1017  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
   1018  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
   1019  */
   1020 static int
   1021 ssh_packet_enable_delayed_compress(struct ssh *ssh)
   1022 {
   1023 	struct session_state *state = ssh->state;
   1024 	struct sshcomp *comp = NULL;
   1025 	int r, mode;
   1026 
   1027 	/*
   1028 	 * Remember that we are past the authentication step, so rekeying
   1029 	 * with COMP_DELAYED will turn on compression immediately.
   1030 	 */
   1031 	state->after_authentication = 1;
   1032 	for (mode = 0; mode < MODE_MAX; mode++) {
   1033 		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
   1034 		if (state->newkeys[mode] == NULL)
   1035 			continue;
   1036 		comp = &state->newkeys[mode]->comp;
   1037 		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
   1038 			if ((r = ssh_packet_init_compression(ssh)) != 0)
   1039 				return r;
   1040 			if (mode == MODE_OUT) {
   1041 				if ((r = start_compression_out(ssh, 6)) != 0)
   1042 					return r;
   1043 			} else {
   1044 				if ((r = start_compression_in(ssh)) != 0)
   1045 					return r;
   1046 			}
   1047 			comp->enabled = 1;
   1048 		}
   1049 	}
   1050 	return 0;
   1051 }
   1052 
   1053 /*
   1054  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
   1055  */
   1056 int
   1057 ssh_packet_send2_wrapped(struct ssh *ssh)
   1058 {
   1059 	struct session_state *state = ssh->state;
   1060 	u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
   1061 	u_char padlen, pad = 0;
   1062 	u_int authlen = 0, aadlen = 0;
   1063 	u_int len;
   1064 	struct sshenc *enc   = NULL;
   1065 	struct sshmac *mac   = NULL;
   1066 	struct sshcomp *comp = NULL;
   1067 	int r, block_size;
   1068 
   1069 	if (state->newkeys[MODE_OUT] != NULL) {
   1070 		enc  = &state->newkeys[MODE_OUT]->enc;
   1071 		mac  = &state->newkeys[MODE_OUT]->mac;
   1072 		comp = &state->newkeys[MODE_OUT]->comp;
   1073 		/* disable mac for authenticated encryption */
   1074 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
   1075 			mac = NULL;
   1076 	}
   1077 	block_size = enc ? enc->block_size : 8;
   1078 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
   1079 
   1080 	type = (sshbuf_ptr(state->outgoing_packet))[5];
   1081 
   1082 #ifdef PACKET_DEBUG
   1083 	fprintf(stderr, "plain:     ");
   1084 	sshbuf_dump(state->outgoing_packet, stderr);
   1085 #endif
   1086 
   1087 	if (comp && comp->enabled) {
   1088 		len = sshbuf_len(state->outgoing_packet);
   1089 		/* skip header, compress only payload */
   1090 		if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
   1091 			goto out;
   1092 		sshbuf_reset(state->compression_buffer);
   1093 		if ((r = compress_buffer(ssh, state->outgoing_packet,
   1094 		    state->compression_buffer)) != 0)
   1095 			goto out;
   1096 		sshbuf_reset(state->outgoing_packet);
   1097 		if ((r = sshbuf_put(state->outgoing_packet,
   1098 		    "\0\0\0\0\0", 5)) != 0 ||
   1099 		    (r = sshbuf_putb(state->outgoing_packet,
   1100 		    state->compression_buffer)) != 0)
   1101 			goto out;
   1102 		DBG(debug("compression: raw %d compressed %zd", len,
   1103 		    sshbuf_len(state->outgoing_packet)));
   1104 	}
   1105 
   1106 	/* sizeof (packet_len + pad_len + payload) */
   1107 	len = sshbuf_len(state->outgoing_packet);
   1108 
   1109 	/*
   1110 	 * calc size of padding, alloc space, get random data,
   1111 	 * minimum padding is 4 bytes
   1112 	 */
   1113 	len -= aadlen; /* packet length is not encrypted for EtM modes */
   1114 	padlen = block_size - (len % block_size);
   1115 	if (padlen < 4)
   1116 		padlen += block_size;
   1117 	if (state->extra_pad) {
   1118 		/* will wrap if extra_pad+padlen > 255 */
   1119 		state->extra_pad =
   1120 		    roundup(state->extra_pad, block_size);
   1121 		pad = state->extra_pad -
   1122 		    ((len + padlen) % state->extra_pad);
   1123 		DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
   1124 		    __func__, pad, len, padlen, state->extra_pad));
   1125 		padlen += pad;
   1126 		state->extra_pad = 0;
   1127 	}
   1128 	if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
   1129 		goto out;
   1130 	if (enc && !state->send_context.plaintext) {
   1131 		/* random padding */
   1132 		arc4random_buf(cp, padlen);
   1133 	} else {
   1134 		/* clear padding */
   1135 		explicit_bzero(cp, padlen);
   1136 	}
   1137 	/* sizeof (packet_len + pad_len + payload + padding) */
   1138 	len = sshbuf_len(state->outgoing_packet);
   1139 	cp = sshbuf_mutable_ptr(state->outgoing_packet);
   1140 	if (cp == NULL) {
   1141 		r = SSH_ERR_INTERNAL_ERROR;
   1142 		goto out;
   1143 	}
   1144 	/* packet_length includes payload, padding and padding length field */
   1145 	POKE_U32(cp, len - 4);
   1146 	cp[4] = padlen;
   1147 	DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
   1148 	    len, padlen, aadlen));
   1149 
   1150 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
   1151 	if (mac && mac->enabled && !mac->etm) {
   1152 		if ((r = mac_compute(mac, state->p_send.seqnr,
   1153 		    sshbuf_ptr(state->outgoing_packet), len,
   1154 		    macbuf, sizeof(macbuf))) != 0)
   1155 			goto out;
   1156 		DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
   1157 	}
   1158 	/* encrypt packet and append to output buffer. */
   1159 	if ((r = sshbuf_reserve(state->output,
   1160 	    sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
   1161 		goto out;
   1162 	if ((r = cipher_crypt(&state->send_context, state->p_send.seqnr, cp,
   1163 	    sshbuf_ptr(state->outgoing_packet),
   1164 	    len - aadlen, aadlen, authlen)) != 0)
   1165 		goto out;
   1166 	/* append unencrypted MAC */
   1167 	if (mac && mac->enabled) {
   1168 		if (mac->etm) {
   1169 			/* EtM: compute mac over aadlen + cipher text */
   1170 			if ((r = mac_compute(mac, state->p_send.seqnr,
   1171 			    cp, len, macbuf, sizeof(macbuf))) != 0)
   1172 				goto out;
   1173 			DBG(debug("done calc MAC(EtM) out #%d",
   1174 			    state->p_send.seqnr));
   1175 		}
   1176 		if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
   1177 			goto out;
   1178 	}
   1179 #ifdef PACKET_DEBUG
   1180 	fprintf(stderr, "encrypted: ");
   1181 	sshbuf_dump(state->output, stderr);
   1182 #endif
   1183 	/* increment sequence number for outgoing packets */
   1184 	if (++state->p_send.seqnr == 0)
   1185 		logit("outgoing seqnr wraps around");
   1186 	if (++state->p_send.packets == 0)
   1187 		if (!(ssh->compat & SSH_BUG_NOREKEY))
   1188 			return SSH_ERR_NEED_REKEY;
   1189 	state->p_send.blocks += len / block_size;
   1190 	state->p_send.bytes += len;
   1191 	sshbuf_reset(state->outgoing_packet);
   1192 
   1193 	if (type == SSH2_MSG_NEWKEYS)
   1194 		r = ssh_set_newkeys(ssh, MODE_OUT);
   1195 	else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
   1196 		r = ssh_packet_enable_delayed_compress(ssh);
   1197 	else
   1198 		r = 0;
   1199  out:
   1200 	return r;
   1201 }
   1202 
   1203 int
   1204 ssh_packet_send2(struct ssh *ssh)
   1205 {
   1206 	struct session_state *state = ssh->state;
   1207 	struct packet *p;
   1208 	u_char type;
   1209 	int r;
   1210 
   1211 	type = sshbuf_ptr(state->outgoing_packet)[5];
   1212 
   1213 	/* during rekeying we can only send key exchange messages */
   1214 	if (state->rekeying) {
   1215 		if ((type < SSH2_MSG_TRANSPORT_MIN) ||
   1216 		    (type > SSH2_MSG_TRANSPORT_MAX) ||
   1217 		    (type == SSH2_MSG_SERVICE_REQUEST) ||
   1218 		    (type == SSH2_MSG_SERVICE_ACCEPT)) {
   1219 			debug("enqueue packet: %u", type);
   1220 			p = calloc(1, sizeof(*p));
   1221 			if (p == NULL)
   1222 				return SSH_ERR_ALLOC_FAIL;
   1223 			p->type = type;
   1224 			p->payload = state->outgoing_packet;
   1225 			TAILQ_INSERT_TAIL(&state->outgoing, p, next);
   1226 			state->outgoing_packet = sshbuf_new();
   1227 			if (state->outgoing_packet == NULL)
   1228 				return SSH_ERR_ALLOC_FAIL;
   1229 			return 0;
   1230 		}
   1231 	}
   1232 
   1233 	/* rekeying starts with sending KEXINIT */
   1234 	if (type == SSH2_MSG_KEXINIT)
   1235 		state->rekeying = 1;
   1236 
   1237 	if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
   1238 		return r;
   1239 
   1240 	/* after a NEWKEYS message we can send the complete queue */
   1241 	if (type == SSH2_MSG_NEWKEYS) {
   1242 		state->rekeying = 0;
   1243 		state->rekey_time = monotime();
   1244 		while ((p = TAILQ_FIRST(&state->outgoing))) {
   1245 			type = p->type;
   1246 			debug("dequeue packet: %u", type);
   1247 			sshbuf_free(state->outgoing_packet);
   1248 			state->outgoing_packet = p->payload;
   1249 			TAILQ_REMOVE(&state->outgoing, p, next);
   1250 			free(p);
   1251 			if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
   1252 				return r;
   1253 		}
   1254 	}
   1255 	return 0;
   1256 }
   1257 
   1258 /*
   1259  * Waits until a packet has been received, and returns its type.  Note that
   1260  * no other data is processed until this returns, so this function should not
   1261  * be used during the interactive session.
   1262  */
   1263 
   1264 int
   1265 ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
   1266 {
   1267 	struct session_state *state = ssh->state;
   1268 	int len, r, ms_remain, cont;
   1269 	fd_set *setp;
   1270 	char buf[8192];
   1271 	struct timeval timeout, start, *timeoutp = NULL;
   1272 
   1273 	DBG(debug("packet_read()"));
   1274 
   1275 	setp = calloc(howmany(state->connection_in + 1,
   1276 	    NFDBITS), sizeof(fd_mask));
   1277 	if (setp == NULL)
   1278 		return SSH_ERR_ALLOC_FAIL;
   1279 
   1280 	/*
   1281 	 * Since we are blocking, ensure that all written packets have
   1282 	 * been sent.
   1283 	 */
   1284 	if ((r = ssh_packet_write_wait(ssh)) != 0)
   1285 		goto out;
   1286 
   1287 	/* Stay in the loop until we have received a complete packet. */
   1288 	for (;;) {
   1289 		/* Try to read a packet from the buffer. */
   1290 		r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
   1291 		if (r != 0)
   1292 			break;
   1293 		if (!compat20 && (
   1294 		    *typep == SSH_SMSG_SUCCESS
   1295 		    || *typep == SSH_SMSG_FAILURE
   1296 		    || *typep == SSH_CMSG_EOF
   1297 		    || *typep == SSH_CMSG_EXIT_CONFIRMATION))
   1298 			if ((r = sshpkt_get_end(ssh)) != 0)
   1299 				break;
   1300 		/* If we got a packet, return it. */
   1301 		if (*typep != SSH_MSG_NONE)
   1302 			break;
   1303 		/*
   1304 		 * Otherwise, wait for some data to arrive, add it to the
   1305 		 * buffer, and try again.
   1306 		 */
   1307 		memset(setp, 0, howmany(state->connection_in + 1,
   1308 		    NFDBITS) * sizeof(fd_mask));
   1309 		FD_SET(state->connection_in, setp);
   1310 
   1311 		if (state->packet_timeout_ms > 0) {
   1312 			ms_remain = state->packet_timeout_ms;
   1313 			timeoutp = &timeout;
   1314 		}
   1315 		/* Wait for some data to arrive. */
   1316 		for (;;) {
   1317 			if (state->packet_timeout_ms != -1) {
   1318 				ms_to_timeval(&timeout, ms_remain);
   1319 				gettimeofday(&start, NULL);
   1320 			}
   1321 			if ((r = select(state->connection_in + 1, setp,
   1322 			    NULL, NULL, timeoutp)) >= 0)
   1323 				break;
   1324 			if (errno != EAGAIN && errno != EINTR &&
   1325 			    errno != EWOULDBLOCK)
   1326 				break;
   1327 			if (state->packet_timeout_ms == -1)
   1328 				continue;
   1329 			ms_subtract_diff(&start, &ms_remain);
   1330 			if (ms_remain <= 0) {
   1331 				r = 0;
   1332 				break;
   1333 			}
   1334 		}
   1335 		if (r == 0)
   1336 			return SSH_ERR_CONN_TIMEOUT;
   1337 		/* Read data from the socket. */
   1338 		do {
   1339 			cont = 0;
   1340 			len = roaming_read(state->connection_in, buf,
   1341 			    sizeof(buf), &cont);
   1342 		} while (len == 0 && cont);
   1343 		if (len == 0) {
   1344 			r = SSH_ERR_CONN_CLOSED;
   1345 			goto out;
   1346 		}
   1347 		if (len < 0) {
   1348 			r = SSH_ERR_SYSTEM_ERROR;
   1349 			goto out;
   1350 		}
   1351 
   1352 		/* Append it to the buffer. */
   1353 		if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
   1354 			goto out;
   1355 	}
   1356  out:
   1357 	free(setp);
   1358 	return r;
   1359 }
   1360 
   1361 int
   1362 ssh_packet_read(struct ssh *ssh)
   1363 {
   1364 	u_char type;
   1365 	int r;
   1366 
   1367 	if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
   1368 		fatal("%s: %s", __func__, ssh_err(r));
   1369 	return type;
   1370 }
   1371 
   1372 /*
   1373  * Waits until a packet has been received, verifies that its type matches
   1374  * that given, and gives a fatal error and exits if there is a mismatch.
   1375  */
   1376 
   1377 int
   1378 ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
   1379 {
   1380 	int r;
   1381 	u_char type;
   1382 
   1383 	if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
   1384 		return r;
   1385 	if (type != expected_type) {
   1386 		if ((r = sshpkt_disconnect(ssh,
   1387 		    "Protocol error: expected packet type %d, got %d",
   1388 		    expected_type, type)) != 0)
   1389 			return r;
   1390 		return SSH_ERR_PROTOCOL_ERROR;
   1391 	}
   1392 	return 0;
   1393 }
   1394 
   1395 /* Checks if a full packet is available in the data received so far via
   1396  * packet_process_incoming.  If so, reads the packet; otherwise returns
   1397  * SSH_MSG_NONE.  This does not wait for data from the connection.
   1398  *
   1399  * SSH_MSG_DISCONNECT is handled specially here.  Also,
   1400  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
   1401  * to higher levels.
   1402  */
   1403 
   1404 int
   1405 ssh_packet_read_poll1(struct ssh *ssh, u_char *typep)
   1406 {
   1407 	struct session_state *state = ssh->state;
   1408 	u_int len, padded_len;
   1409 	const char *emsg;
   1410 	const u_char *cp;
   1411 	u_char *p;
   1412 	u_int checksum, stored_checksum;
   1413 	int r;
   1414 
   1415 	*typep = SSH_MSG_NONE;
   1416 
   1417 	/* Check if input size is less than minimum packet size. */
   1418 	if (sshbuf_len(state->input) < 4 + 8)
   1419 		return 0;
   1420 	/* Get length of incoming packet. */
   1421 	len = PEEK_U32(sshbuf_ptr(state->input));
   1422 	if (len < 1 + 2 + 2 || len > 256 * 1024) {
   1423 		if ((r = sshpkt_disconnect(ssh, "Bad packet length %u",
   1424 		    len)) != 0)
   1425 			return r;
   1426 		return SSH_ERR_CONN_CORRUPT;
   1427 	}
   1428 	padded_len = (len + 8) & ~7;
   1429 
   1430 	/* Check if the packet has been entirely received. */
   1431 	if (sshbuf_len(state->input) < 4 + padded_len)
   1432 		return 0;
   1433 
   1434 	/* The entire packet is in buffer. */
   1435 
   1436 	/* Consume packet length. */
   1437 	if ((r = sshbuf_consume(state->input, 4)) != 0)
   1438 		goto out;
   1439 
   1440 	/*
   1441 	 * Cryptographic attack detector for ssh
   1442 	 * (C)1998 CORE-SDI, Buenos Aires Argentina
   1443 	 * Ariel Futoransky(futo (at) core-sdi.com)
   1444 	 */
   1445 	if (!state->receive_context.plaintext) {
   1446 		emsg = NULL;
   1447 		switch (detect_attack(&state->deattack,
   1448 		    sshbuf_ptr(state->input), padded_len)) {
   1449 		case DEATTACK_OK:
   1450 			break;
   1451 		case DEATTACK_DETECTED:
   1452 			emsg = "crc32 compensation attack detected";
   1453 			break;
   1454 		case DEATTACK_DOS_DETECTED:
   1455 			emsg = "deattack denial of service detected";
   1456 			break;
   1457 		default:
   1458 			emsg = "deattack error";
   1459 			break;
   1460 		}
   1461 		if (emsg != NULL) {
   1462 			error("%s", emsg);
   1463 			if ((r = sshpkt_disconnect(ssh, "%s", emsg)) != 0 ||
   1464 			    (r = ssh_packet_write_wait(ssh)) != 0)
   1465 					return r;
   1466 			return SSH_ERR_CONN_CORRUPT;
   1467 		}
   1468 	}
   1469 
   1470 	/* Decrypt data to incoming_packet. */
   1471 	sshbuf_reset(state->incoming_packet);
   1472 	if ((r = sshbuf_reserve(state->incoming_packet, padded_len, &p)) != 0)
   1473 		goto out;
   1474 	if ((r = cipher_crypt(&state->receive_context, 0, p,
   1475 	    sshbuf_ptr(state->input), padded_len, 0, 0)) != 0)
   1476 		goto out;
   1477 
   1478 	if ((r = sshbuf_consume(state->input, padded_len)) != 0)
   1479 		goto out;
   1480 
   1481 #ifdef PACKET_DEBUG
   1482 	fprintf(stderr, "read_poll plain: ");
   1483 	sshbuf_dump(state->incoming_packet, stderr);
   1484 #endif
   1485 
   1486 	/* Compute packet checksum. */
   1487 	checksum = ssh_crc32(sshbuf_ptr(state->incoming_packet),
   1488 	    sshbuf_len(state->incoming_packet) - 4);
   1489 
   1490 	/* Skip padding. */
   1491 	if ((r = sshbuf_consume(state->incoming_packet, 8 - len % 8)) != 0)
   1492 		goto out;
   1493 
   1494 	/* Test check bytes. */
   1495 	if (len != sshbuf_len(state->incoming_packet)) {
   1496 		error("%s: len %d != sshbuf_len %zd", __func__,
   1497 		    len, sshbuf_len(state->incoming_packet));
   1498 		if ((r = sshpkt_disconnect(ssh, "invalid packet length")) != 0 ||
   1499 		    (r = ssh_packet_write_wait(ssh)) != 0)
   1500 			return r;
   1501 		return SSH_ERR_CONN_CORRUPT;
   1502 	}
   1503 
   1504 	cp = sshbuf_ptr(state->incoming_packet) + len - 4;
   1505 	stored_checksum = PEEK_U32(cp);
   1506 	if (checksum != stored_checksum) {
   1507 		error("Corrupted check bytes on input");
   1508 		if ((r = sshpkt_disconnect(ssh, "connection corrupted")) != 0 ||
   1509 		    (r = ssh_packet_write_wait(ssh)) != 0)
   1510 			return r;
   1511 		return SSH_ERR_CONN_CORRUPT;
   1512 	}
   1513 	if ((r = sshbuf_consume_end(state->incoming_packet, 4)) < 0)
   1514 		goto out;
   1515 
   1516 	if (state->packet_compression) {
   1517 		sshbuf_reset(state->compression_buffer);
   1518 		if ((r = uncompress_buffer(ssh, state->incoming_packet,
   1519 		    state->compression_buffer)) != 0)
   1520 			goto out;
   1521 		sshbuf_reset(state->incoming_packet);
   1522 		if ((r = sshbuf_putb(state->incoming_packet,
   1523 		    state->compression_buffer)) != 0)
   1524 			goto out;
   1525 	}
   1526 	state->p_read.packets++;
   1527 	state->p_read.bytes += padded_len + 4;
   1528 	if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
   1529 		goto out;
   1530 	if (*typep < SSH_MSG_MIN || *typep > SSH_MSG_MAX) {
   1531 		error("Invalid ssh1 packet type: %d", *typep);
   1532 		if ((r = sshpkt_disconnect(ssh, "invalid packet type")) != 0 ||
   1533 		    (r = ssh_packet_write_wait(ssh)) != 0)
   1534 			return r;
   1535 		return SSH_ERR_PROTOCOL_ERROR;
   1536 	}
   1537 	r = 0;
   1538  out:
   1539 	return r;
   1540 }
   1541 
   1542 int
   1543 ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
   1544 {
   1545 	struct session_state *state = ssh->state;
   1546 	u_int padlen, need;
   1547 	u_char *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
   1548 	u_int maclen, aadlen = 0, authlen = 0, block_size;
   1549 	struct sshenc *enc   = NULL;
   1550 	struct sshmac *mac   = NULL;
   1551 	struct sshcomp *comp = NULL;
   1552 	int r;
   1553 
   1554 	*typep = SSH_MSG_NONE;
   1555 
   1556 	if (state->packet_discard)
   1557 		return 0;
   1558 
   1559 	if (state->newkeys[MODE_IN] != NULL) {
   1560 		enc  = &state->newkeys[MODE_IN]->enc;
   1561 		mac  = &state->newkeys[MODE_IN]->mac;
   1562 		comp = &state->newkeys[MODE_IN]->comp;
   1563 		/* disable mac for authenticated encryption */
   1564 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
   1565 			mac = NULL;
   1566 	}
   1567 	maclen = mac && mac->enabled ? mac->mac_len : 0;
   1568 	block_size = enc ? enc->block_size : 8;
   1569 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
   1570 
   1571 	if (aadlen && state->packlen == 0) {
   1572 		if (cipher_get_length(&state->receive_context,
   1573 		    &state->packlen, state->p_read.seqnr,
   1574 		    sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
   1575 			return 0;
   1576 		if (state->packlen < 1 + 4 ||
   1577 		    state->packlen > PACKET_MAX_SIZE) {
   1578 #ifdef PACKET_DEBUG
   1579 			sshbuf_dump(state->input, stderr);
   1580 #endif
   1581 			logit("Bad packet length %u.", state->packlen);
   1582 			if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
   1583 				return r;
   1584 			return SSH_ERR_CONN_CORRUPT;
   1585 		}
   1586 		sshbuf_reset(state->incoming_packet);
   1587 	} else if (state->packlen == 0) {
   1588 		/*
   1589 		 * check if input size is less than the cipher block size,
   1590 		 * decrypt first block and extract length of incoming packet
   1591 		 */
   1592 		if (sshbuf_len(state->input) < block_size)
   1593 			return 0;
   1594 		sshbuf_reset(state->incoming_packet);
   1595 		if ((r = sshbuf_reserve(state->incoming_packet, block_size,
   1596 		    &cp)) != 0)
   1597 			goto out;
   1598 		if ((r = cipher_crypt(&state->receive_context,
   1599 		    state->p_send.seqnr, cp, sshbuf_ptr(state->input),
   1600 		    block_size, 0, 0)) != 0)
   1601 			goto out;
   1602 		state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
   1603 		if (state->packlen < 1 + 4 ||
   1604 		    state->packlen > PACKET_MAX_SIZE) {
   1605 #ifdef PACKET_DEBUG
   1606 			fprintf(stderr, "input: \n");
   1607 			sshbuf_dump(state->input, stderr);
   1608 			fprintf(stderr, "incoming_packet: \n");
   1609 			sshbuf_dump(state->incoming_packet, stderr);
   1610 #endif
   1611 			logit("Bad packet length %u.", state->packlen);
   1612 			return ssh_packet_start_discard(ssh, enc, mac,
   1613 			    state->packlen, PACKET_MAX_SIZE);
   1614 		}
   1615 		if ((r = sshbuf_consume(state->input, block_size)) != 0)
   1616 			goto out;
   1617 	}
   1618 	DBG(debug("input: packet len %u", state->packlen+4));
   1619 
   1620 	if (aadlen) {
   1621 		/* only the payload is encrypted */
   1622 		need = state->packlen;
   1623 	} else {
   1624 		/*
   1625 		 * the payload size and the payload are encrypted, but we
   1626 		 * have a partial packet of block_size bytes
   1627 		 */
   1628 		need = 4 + state->packlen - block_size;
   1629 	}
   1630 	DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
   1631 	    " aadlen %d", block_size, need, maclen, authlen, aadlen));
   1632 	if (need % block_size != 0) {
   1633 		logit("padding error: need %d block %d mod %d",
   1634 		    need, block_size, need % block_size);
   1635 		return ssh_packet_start_discard(ssh, enc, mac,
   1636 		    state->packlen, PACKET_MAX_SIZE - block_size);
   1637 	}
   1638 	/*
   1639 	 * check if the entire packet has been received and
   1640 	 * decrypt into incoming_packet:
   1641 	 * 'aadlen' bytes are unencrypted, but authenticated.
   1642 	 * 'need' bytes are encrypted, followed by either
   1643 	 * 'authlen' bytes of authentication tag or
   1644 	 * 'maclen' bytes of message authentication code.
   1645 	 */
   1646 	if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
   1647 		return 0;
   1648 #ifdef PACKET_DEBUG
   1649 	fprintf(stderr, "read_poll enc/full: ");
   1650 	sshbuf_dump(state->input, stderr);
   1651 #endif
   1652 	/* EtM: compute mac over encrypted input */
   1653 	if (mac && mac->enabled && mac->etm) {
   1654 		if ((r = mac_compute(mac, state->p_read.seqnr,
   1655 		    sshbuf_ptr(state->input), aadlen + need,
   1656 		    macbuf, sizeof(macbuf))) != 0)
   1657 			goto out;
   1658 	}
   1659 	if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
   1660 	    &cp)) != 0)
   1661 		goto out;
   1662 	if ((r = cipher_crypt(&state->receive_context, state->p_read.seqnr, cp,
   1663 	    sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
   1664 		goto out;
   1665 	if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
   1666 		goto out;
   1667 	/*
   1668 	 * compute MAC over seqnr and packet,
   1669 	 * increment sequence number for incoming packet
   1670 	 */
   1671 	if (mac && mac->enabled) {
   1672 		if (!mac->etm)
   1673 			if ((r = mac_compute(mac, state->p_read.seqnr,
   1674 			    sshbuf_ptr(state->incoming_packet),
   1675 			    sshbuf_len(state->incoming_packet),
   1676 			    macbuf, sizeof(macbuf))) != 0)
   1677 				goto out;
   1678 		if (timingsafe_bcmp(macbuf, sshbuf_ptr(state->input),
   1679 		    mac->mac_len) != 0) {
   1680 			logit("Corrupted MAC on input.");
   1681 			if (need > PACKET_MAX_SIZE)
   1682 				return SSH_ERR_INTERNAL_ERROR;
   1683 			return ssh_packet_start_discard(ssh, enc, mac,
   1684 			    state->packlen, PACKET_MAX_SIZE - need);
   1685 		}
   1686 
   1687 		DBG(debug("MAC #%d ok", state->p_read.seqnr));
   1688 		if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
   1689 			goto out;
   1690 	}
   1691 	if (seqnr_p != NULL)
   1692 		*seqnr_p = state->p_read.seqnr;
   1693 	if (++state->p_read.seqnr == 0)
   1694 		logit("incoming seqnr wraps around");
   1695 	if (++state->p_read.packets == 0)
   1696 		if (!(ssh->compat & SSH_BUG_NOREKEY))
   1697 			return SSH_ERR_NEED_REKEY;
   1698 	state->p_read.blocks += (state->packlen + 4) / block_size;
   1699 	state->p_read.bytes += state->packlen + 4;
   1700 
   1701 	/* get padlen */
   1702 	padlen = sshbuf_ptr(state->incoming_packet)[4];
   1703 	DBG(debug("input: padlen %d", padlen));
   1704 	if (padlen < 4)	{
   1705 		if ((r = sshpkt_disconnect(ssh,
   1706 		    "Corrupted padlen %d on input.", padlen)) != 0 ||
   1707 		    (r = ssh_packet_write_wait(ssh)) != 0)
   1708 			return r;
   1709 		return SSH_ERR_CONN_CORRUPT;
   1710 	}
   1711 
   1712 	/* skip packet size + padlen, discard padding */
   1713 	if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
   1714 	    ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
   1715 		goto out;
   1716 
   1717 	DBG(debug("input: len before de-compress %zd",
   1718 	    sshbuf_len(state->incoming_packet)));
   1719 	if (comp && comp->enabled) {
   1720 		sshbuf_reset(state->compression_buffer);
   1721 		if ((r = uncompress_buffer(ssh, state->incoming_packet,
   1722 		    state->compression_buffer)) != 0)
   1723 			goto out;
   1724 		sshbuf_reset(state->incoming_packet);
   1725 		if ((r = sshbuf_putb(state->incoming_packet,
   1726 		    state->compression_buffer)) != 0)
   1727 			goto out;
   1728 		DBG(debug("input: len after de-compress %zd",
   1729 		    sshbuf_len(state->incoming_packet)));
   1730 	}
   1731 	/*
   1732 	 * get packet type, implies consume.
   1733 	 * return length of payload (without type field)
   1734 	 */
   1735 	if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
   1736 		goto out;
   1737 	if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
   1738 		if ((r = sshpkt_disconnect(ssh,
   1739 		    "Invalid ssh2 packet type: %d", *typep)) != 0 ||
   1740 		    (r = ssh_packet_write_wait(ssh)) != 0)
   1741 			return r;
   1742 		return SSH_ERR_PROTOCOL_ERROR;
   1743 	}
   1744 	if (*typep == SSH2_MSG_NEWKEYS)
   1745 		r = ssh_set_newkeys(ssh, MODE_IN);
   1746 	else if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
   1747 		r = ssh_packet_enable_delayed_compress(ssh);
   1748 	else
   1749 		r = 0;
   1750 #ifdef PACKET_DEBUG
   1751 	fprintf(stderr, "read/plain[%d]:\r\n", *typep);
   1752 	sshbuf_dump(state->incoming_packet, stderr);
   1753 #endif
   1754 	/* reset for next packet */
   1755 	state->packlen = 0;
   1756  out:
   1757 	return r;
   1758 }
   1759 
   1760 int
   1761 ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
   1762 {
   1763 	struct session_state *state = ssh->state;
   1764 	u_int reason, seqnr;
   1765 	int r;
   1766 	u_char *msg;
   1767 
   1768 	for (;;) {
   1769 		msg = NULL;
   1770 		if (compat20) {
   1771 			r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
   1772 			if (r != 0)
   1773 				return r;
   1774 			if (*typep) {
   1775 				state->keep_alive_timeouts = 0;
   1776 				DBG(debug("received packet type %d", *typep));
   1777 			}
   1778 			switch (*typep) {
   1779 			case SSH2_MSG_IGNORE:
   1780 				debug3("Received SSH2_MSG_IGNORE");
   1781 				break;
   1782 			case SSH2_MSG_DEBUG:
   1783 				if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
   1784 				    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
   1785 				    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
   1786 					if (msg)
   1787 						free(msg);
   1788 					return r;
   1789 				}
   1790 				debug("Remote: %.900s", msg);
   1791 				free(msg);
   1792 				break;
   1793 			case SSH2_MSG_DISCONNECT:
   1794 				if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
   1795 				    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
   1796 					return r;
   1797 				/* Ignore normal client exit notifications */
   1798 				do_log2(ssh->state->server_side &&
   1799 				    reason == SSH2_DISCONNECT_BY_APPLICATION ?
   1800 				    SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
   1801 				    "Received disconnect from %s: %u: %.400s",
   1802 				    ssh_remote_ipaddr(ssh), reason, msg);
   1803 				free(msg);
   1804 				return SSH_ERR_DISCONNECTED;
   1805 			case SSH2_MSG_UNIMPLEMENTED:
   1806 				if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
   1807 					return r;
   1808 				debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
   1809 				    seqnr);
   1810 				break;
   1811 			default:
   1812 				return 0;
   1813 			}
   1814 		} else {
   1815 			r = ssh_packet_read_poll1(ssh, typep);
   1816 			switch (*typep) {
   1817 			case SSH_MSG_NONE:
   1818 				return SSH_MSG_NONE;
   1819 			case SSH_MSG_IGNORE:
   1820 				break;
   1821 			case SSH_MSG_DEBUG:
   1822 				if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
   1823 					return r;
   1824 				debug("Remote: %.900s", msg);
   1825 				free(msg);
   1826 				break;
   1827 			case SSH_MSG_DISCONNECT:
   1828 				if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
   1829 					return r;
   1830 				error("Received disconnect from %s: %.400s",
   1831 				    ssh_remote_ipaddr(ssh), msg);
   1832 				free(msg);
   1833 				return SSH_ERR_DISCONNECTED;
   1834 			default:
   1835 				DBG(debug("received packet type %d", *typep));
   1836 				return 0;
   1837 			}
   1838 		}
   1839 	}
   1840 }
   1841 
   1842 /*
   1843  * Buffers the given amount of input characters.  This is intended to be used
   1844  * together with packet_read_poll.
   1845  */
   1846 
   1847 int
   1848 ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
   1849 {
   1850 	struct session_state *state = ssh->state;
   1851 	int r;
   1852 
   1853 	if (state->packet_discard) {
   1854 		state->keep_alive_timeouts = 0; /* ?? */
   1855 		if (len >= state->packet_discard) {
   1856 			if ((r = ssh_packet_stop_discard(ssh)) != 0)
   1857 				return r;
   1858 		}
   1859 		state->packet_discard -= len;
   1860 		return 0;
   1861 	}
   1862 	if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
   1863 		return r;
   1864 
   1865 	return 0;
   1866 }
   1867 
   1868 int
   1869 ssh_packet_remaining(struct ssh *ssh)
   1870 {
   1871 	return sshbuf_len(ssh->state->incoming_packet);
   1872 }
   1873 
   1874 /*
   1875  * Sends a diagnostic message from the server to the client.  This message
   1876  * can be sent at any time (but not while constructing another message). The
   1877  * message is printed immediately, but only if the client is being executed
   1878  * in verbose mode.  These messages are primarily intended to ease debugging
   1879  * authentication problems.   The length of the formatted message must not
   1880  * exceed 1024 bytes.  This will automatically call ssh_packet_write_wait.
   1881  */
   1882 void
   1883 ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
   1884 {
   1885 	char buf[1024];
   1886 	va_list args;
   1887 	int r;
   1888 
   1889 	if (compat20 && (ssh->compat & SSH_BUG_DEBUG))
   1890 		return;
   1891 
   1892 	va_start(args, fmt);
   1893 	vsnprintf(buf, sizeof(buf), fmt, args);
   1894 	va_end(args);
   1895 
   1896 	if (compat20) {
   1897 		if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
   1898 		    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
   1899 		    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
   1900 		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
   1901 		    (r = sshpkt_send(ssh)) != 0)
   1902 			fatal("%s: %s", __func__, ssh_err(r));
   1903 	} else {
   1904 		if ((r = sshpkt_start(ssh, SSH_MSG_DEBUG)) != 0 ||
   1905 		    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
   1906 		    (r = sshpkt_send(ssh)) != 0)
   1907 			fatal("%s: %s", __func__, ssh_err(r));
   1908 	}
   1909 	if ((r = ssh_packet_write_wait(ssh)) != 0)
   1910 		fatal("%s: %s", __func__, ssh_err(r));
   1911 }
   1912 
   1913 /*
   1914  * Pretty-print connection-terminating errors and exit.
   1915  */
   1916 void
   1917 sshpkt_fatal(struct ssh *ssh, const char *tag, int r)
   1918 {
   1919 	switch (r) {
   1920 	case SSH_ERR_CONN_CLOSED:
   1921 		logit("Connection closed by %.200s", ssh_remote_ipaddr(ssh));
   1922 		cleanup_exit(255);
   1923 	case SSH_ERR_CONN_TIMEOUT:
   1924 		logit("Connection to %.200s timed out", ssh_remote_ipaddr(ssh));
   1925 		cleanup_exit(255);
   1926 	case SSH_ERR_DISCONNECTED:
   1927 		logit("Disconnected from %.200s",
   1928 		    ssh_remote_ipaddr(ssh));
   1929 		cleanup_exit(255);
   1930 	case SSH_ERR_SYSTEM_ERROR:
   1931 		if (errno == ECONNRESET) {
   1932 			logit("Connection reset by %.200s",
   1933 			    ssh_remote_ipaddr(ssh));
   1934 			cleanup_exit(255);
   1935 		}
   1936 		/* FALLTHROUGH */
   1937 	case SSH_ERR_NO_CIPHER_ALG_MATCH:
   1938 	case SSH_ERR_NO_MAC_ALG_MATCH:
   1939 	case SSH_ERR_NO_COMPRESS_ALG_MATCH:
   1940 	case SSH_ERR_NO_KEX_ALG_MATCH:
   1941 	case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
   1942 		if (ssh && ssh->kex && ssh->kex->failed_choice) {
   1943 			fatal("Unable to negotiate with %.200s: %s. "
   1944 			    "Their offer: %s", ssh_remote_ipaddr(ssh),
   1945 			    ssh_err(r), ssh->kex->failed_choice);
   1946 		}
   1947 		/* FALLTHROUGH */
   1948 	default:
   1949 		fatal("%s%sConnection to %.200s: %s",
   1950 		    tag != NULL ? tag : "", tag != NULL ? ": " : "",
   1951 		    ssh_remote_ipaddr(ssh), ssh_err(r));
   1952 	}
   1953 }
   1954 
   1955 /*
   1956  * Logs the error plus constructs and sends a disconnect packet, closes the
   1957  * connection, and exits.  This function never returns. The error message
   1958  * should not contain a newline.  The length of the formatted message must
   1959  * not exceed 1024 bytes.
   1960  */
   1961 void
   1962 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
   1963 {
   1964 	char buf[1024];
   1965 	va_list args;
   1966 	static int disconnecting = 0;
   1967 	int r;
   1968 
   1969 	if (disconnecting)	/* Guard against recursive invocations. */
   1970 		fatal("packet_disconnect called recursively.");
   1971 	disconnecting = 1;
   1972 
   1973 	/*
   1974 	 * Format the message.  Note that the caller must make sure the
   1975 	 * message is of limited size.
   1976 	 */
   1977 	va_start(args, fmt);
   1978 	vsnprintf(buf, sizeof(buf), fmt, args);
   1979 	va_end(args);
   1980 
   1981 	/* Display the error locally */
   1982 	logit("Disconnecting: %.100s", buf);
   1983 
   1984 	/*
   1985 	 * Send the disconnect message to the other side, and wait
   1986 	 * for it to get sent.
   1987 	 */
   1988 	if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
   1989 		sshpkt_fatal(ssh, __func__, r);
   1990 
   1991 	if ((r = ssh_packet_write_wait(ssh)) != 0)
   1992 		sshpkt_fatal(ssh, __func__, r);
   1993 
   1994 	/* Close the connection. */
   1995 	ssh_packet_close(ssh);
   1996 	cleanup_exit(255);
   1997 }
   1998 
   1999 /*
   2000  * Checks if there is any buffered output, and tries to write some of
   2001  * the output.
   2002  */
   2003 int
   2004 ssh_packet_write_poll(struct ssh *ssh)
   2005 {
   2006 	struct session_state *state = ssh->state;
   2007 	int len = sshbuf_len(state->output);
   2008 	int cont, r;
   2009 
   2010 	if (len > 0) {
   2011 		cont = 0;
   2012 		len = roaming_write(state->connection_out,
   2013 		    sshbuf_ptr(state->output), len, &cont);
   2014 		if (len == -1) {
   2015 			if (errno == EINTR || errno == EAGAIN ||
   2016 			    errno == EWOULDBLOCK)
   2017 				return 0;
   2018 			return SSH_ERR_SYSTEM_ERROR;
   2019 		}
   2020 		if (len == 0 && !cont)
   2021 			return SSH_ERR_CONN_CLOSED;
   2022 		if ((r = sshbuf_consume(state->output, len)) != 0)
   2023 			return r;
   2024 	}
   2025 	return 0;
   2026 }
   2027 
   2028 /*
   2029  * Calls packet_write_poll repeatedly until all pending output data has been
   2030  * written.
   2031  */
   2032 int
   2033 ssh_packet_write_wait(struct ssh *ssh)
   2034 {
   2035 	fd_set *setp;
   2036 	int ret, r, ms_remain = 0;
   2037 	struct timeval start, timeout, *timeoutp = NULL;
   2038 	struct session_state *state = ssh->state;
   2039 
   2040 	setp = calloc(howmany(state->connection_out + 1,
   2041 	    NFDBITS), sizeof(fd_mask));
   2042 	if (setp == NULL)
   2043 		return SSH_ERR_ALLOC_FAIL;
   2044 	ssh_packet_write_poll(ssh);
   2045 	while (ssh_packet_have_data_to_write(ssh)) {
   2046 		memset(setp, 0, howmany(state->connection_out + 1,
   2047 		    NFDBITS) * sizeof(fd_mask));
   2048 		FD_SET(state->connection_out, setp);
   2049 
   2050 		if (state->packet_timeout_ms > 0) {
   2051 			ms_remain = state->packet_timeout_ms;
   2052 			timeoutp = &timeout;
   2053 		}
   2054 		for (;;) {
   2055 			if (state->packet_timeout_ms != -1) {
   2056 				ms_to_timeval(&timeout, ms_remain);
   2057 				gettimeofday(&start, NULL);
   2058 			}
   2059 			if ((ret = select(state->connection_out + 1,
   2060 			    NULL, setp, NULL, timeoutp)) >= 0)
   2061 				break;
   2062 			if (errno != EAGAIN && errno != EINTR &&
   2063 			    errno != EWOULDBLOCK)
   2064 				break;
   2065 			if (state->packet_timeout_ms == -1)
   2066 				continue;
   2067 			ms_subtract_diff(&start, &ms_remain);
   2068 			if (ms_remain <= 0) {
   2069 				ret = 0;
   2070 				break;
   2071 			}
   2072 		}
   2073 		if (ret == 0) {
   2074 			free(setp);
   2075 			return SSH_ERR_CONN_TIMEOUT;
   2076 		}
   2077 		if ((r = ssh_packet_write_poll(ssh)) != 0) {
   2078 			free(setp);
   2079 			return r;
   2080 		}
   2081 	}
   2082 	free(setp);
   2083 	return 0;
   2084 }
   2085 
   2086 /* Returns true if there is buffered data to write to the connection. */
   2087 
   2088 int
   2089 ssh_packet_have_data_to_write(struct ssh *ssh)
   2090 {
   2091 	return sshbuf_len(ssh->state->output) != 0;
   2092 }
   2093 
   2094 /* Returns true if there is not too much data to write to the connection. */
   2095 
   2096 int
   2097 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
   2098 {
   2099 	if (ssh->state->interactive_mode)
   2100 		return sshbuf_len(ssh->state->output) < 16384;
   2101 	else
   2102 		return sshbuf_len(ssh->state->output) < 128 * 1024;
   2103 }
   2104 
   2105 void
   2106 ssh_packet_set_tos(struct ssh *ssh, int tos)
   2107 {
   2108 #ifndef IP_TOS_IS_BROKEN
   2109 	if (!ssh_packet_connection_is_on_socket(ssh))
   2110 		return;
   2111 	switch (ssh_packet_connection_af(ssh)) {
   2112 # ifdef IP_TOS
   2113 	case AF_INET:
   2114 		debug3("%s: set IP_TOS 0x%02x", __func__, tos);
   2115 		if (setsockopt(ssh->state->connection_in,
   2116 		    IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
   2117 			error("setsockopt IP_TOS %d: %.100s:",
   2118 			    tos, strerror(errno));
   2119 		break;
   2120 # endif /* IP_TOS */
   2121 # ifdef IPV6_TCLASS
   2122 	case AF_INET6:
   2123 		debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
   2124 		if (setsockopt(ssh->state->connection_in,
   2125 		    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
   2126 			error("setsockopt IPV6_TCLASS %d: %.100s:",
   2127 			    tos, strerror(errno));
   2128 		break;
   2129 # endif /* IPV6_TCLASS */
   2130 	}
   2131 #endif /* IP_TOS_IS_BROKEN */
   2132 }
   2133 
   2134 /* Informs that the current session is interactive.  Sets IP flags for that. */
   2135 
   2136 void
   2137 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
   2138 {
   2139 	struct session_state *state = ssh->state;
   2140 
   2141 	if (state->set_interactive_called)
   2142 		return;
   2143 	state->set_interactive_called = 1;
   2144 
   2145 	/* Record that we are in interactive mode. */
   2146 	state->interactive_mode = interactive;
   2147 
   2148 	/* Only set socket options if using a socket.  */
   2149 	if (!ssh_packet_connection_is_on_socket(ssh))
   2150 		return;
   2151 	set_nodelay(state->connection_in);
   2152 	ssh_packet_set_tos(ssh, interactive ? qos_interactive :
   2153 	    qos_bulk);
   2154 }
   2155 
   2156 /* Returns true if the current connection is interactive. */
   2157 
   2158 int
   2159 ssh_packet_is_interactive(struct ssh *ssh)
   2160 {
   2161 	return ssh->state->interactive_mode;
   2162 }
   2163 
   2164 int
   2165 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
   2166 {
   2167 	struct session_state *state = ssh->state;
   2168 
   2169 	if (state->set_maxsize_called) {
   2170 		logit("packet_set_maxsize: called twice: old %d new %d",
   2171 		    state->max_packet_size, s);
   2172 		return -1;
   2173 	}
   2174 	if (s < 4 * 1024 || s > 1024 * 1024) {
   2175 		logit("packet_set_maxsize: bad size %d", s);
   2176 		return -1;
   2177 	}
   2178 	state->set_maxsize_called = 1;
   2179 	debug("packet_set_maxsize: setting to %d", s);
   2180 	state->max_packet_size = s;
   2181 	return s;
   2182 }
   2183 
   2184 int
   2185 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
   2186 {
   2187 	return ++ssh->state->keep_alive_timeouts;
   2188 }
   2189 
   2190 void
   2191 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
   2192 {
   2193 	ssh->state->keep_alive_timeouts = ka;
   2194 }
   2195 
   2196 u_int
   2197 ssh_packet_get_maxsize(struct ssh *ssh)
   2198 {
   2199 	return ssh->state->max_packet_size;
   2200 }
   2201 
   2202 /*
   2203  * 9.2.  Ignored Data Message
   2204  *
   2205  *   byte      SSH_MSG_IGNORE
   2206  *   string    data
   2207  *
   2208  * All implementations MUST understand (and ignore) this message at any
   2209  * time (after receiving the protocol version). No implementation is
   2210  * required to send them. This message can be used as an additional
   2211  * protection measure against advanced traffic analysis techniques.
   2212  */
   2213 void
   2214 ssh_packet_send_ignore(struct ssh *ssh, int nbytes)
   2215 {
   2216 	u_int32_t rnd = 0;
   2217 	int r, i;
   2218 
   2219 	if ((r = sshpkt_start(ssh, compat20 ?
   2220 	    SSH2_MSG_IGNORE : SSH_MSG_IGNORE)) != 0 ||
   2221 	    (r = sshpkt_put_u32(ssh, nbytes)) != 0)
   2222 		fatal("%s: %s", __func__, ssh_err(r));
   2223 	for (i = 0; i < nbytes; i++) {
   2224 		if (i % 4 == 0)
   2225 			rnd = arc4random();
   2226 		if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
   2227 			fatal("%s: %s", __func__, ssh_err(r));
   2228 		rnd >>= 8;
   2229 	}
   2230 }
   2231 
   2232 #define MAX_PACKETS	(1U<<31)
   2233 int
   2234 ssh_packet_need_rekeying(struct ssh *ssh)
   2235 {
   2236 	struct session_state *state = ssh->state;
   2237 
   2238 	if (ssh->compat & SSH_BUG_NOREKEY)
   2239 		return 0;
   2240 	return
   2241 	    (state->p_send.packets > MAX_PACKETS) ||
   2242 	    (state->p_read.packets > MAX_PACKETS) ||
   2243 	    (state->max_blocks_out &&
   2244 	        (state->p_send.blocks > state->max_blocks_out)) ||
   2245 	    (state->max_blocks_in &&
   2246 	        (state->p_read.blocks > state->max_blocks_in)) ||
   2247 	    (state->rekey_interval != 0 && state->rekey_time +
   2248 		 state->rekey_interval <= monotime());
   2249 }
   2250 
   2251 void
   2252 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int32_t bytes, time_t seconds)
   2253 {
   2254 	debug3("rekey after %lld bytes, %d seconds", (long long)bytes,
   2255 	    (int)seconds);
   2256 	ssh->state->rekey_limit = bytes;
   2257 	ssh->state->rekey_interval = seconds;
   2258 }
   2259 
   2260 time_t
   2261 ssh_packet_get_rekey_timeout(struct ssh *ssh)
   2262 {
   2263 	time_t seconds;
   2264 
   2265 	seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
   2266 	    monotime();
   2267 	return (seconds <= 0 ? 1 : seconds);
   2268 }
   2269 
   2270 void
   2271 ssh_packet_set_server(struct ssh *ssh)
   2272 {
   2273 	ssh->state->server_side = 1;
   2274 }
   2275 
   2276 void
   2277 ssh_packet_set_authenticated(struct ssh *ssh)
   2278 {
   2279 	ssh->state->after_authentication = 1;
   2280 }
   2281 
   2282 void *
   2283 ssh_packet_get_input(struct ssh *ssh)
   2284 {
   2285 	return (void *)ssh->state->input;
   2286 }
   2287 
   2288 void *
   2289 ssh_packet_get_output(struct ssh *ssh)
   2290 {
   2291 	return (void *)ssh->state->output;
   2292 }
   2293 
   2294 /* XXX TODO update roaming to new API (does not work anyway) */
   2295 /*
   2296  * Save the state for the real connection, and use a separate state when
   2297  * resuming a suspended connection.
   2298  */
   2299 void
   2300 ssh_packet_backup_state(struct ssh *ssh,
   2301     struct ssh *backup_state)
   2302 {
   2303 	struct ssh *tmp;
   2304 
   2305 	close(ssh->state->connection_in);
   2306 	ssh->state->connection_in = -1;
   2307 	close(ssh->state->connection_out);
   2308 	ssh->state->connection_out = -1;
   2309 	if (backup_state)
   2310 		tmp = backup_state;
   2311 	else
   2312 		tmp = ssh_alloc_session_state();
   2313 	backup_state = ssh;
   2314 	ssh = tmp;
   2315 }
   2316 
   2317 /* XXX FIXME FIXME FIXME */
   2318 /*
   2319  * Swap in the old state when resuming a connecion.
   2320  */
   2321 void
   2322 ssh_packet_restore_state(struct ssh *ssh,
   2323     struct ssh *backup_state)
   2324 {
   2325 	struct ssh *tmp;
   2326 	u_int len;
   2327 	int r;
   2328 
   2329 	tmp = backup_state;
   2330 	backup_state = ssh;
   2331 	ssh = tmp;
   2332 	ssh->state->connection_in = backup_state->state->connection_in;
   2333 	backup_state->state->connection_in = -1;
   2334 	ssh->state->connection_out = backup_state->state->connection_out;
   2335 	backup_state->state->connection_out = -1;
   2336 	len = sshbuf_len(backup_state->state->input);
   2337 	if (len > 0) {
   2338 		if ((r = sshbuf_putb(ssh->state->input,
   2339 		    backup_state->state->input)) != 0)
   2340 			fatal("%s: %s", __func__, ssh_err(r));
   2341 		sshbuf_reset(backup_state->state->input);
   2342 		add_recv_bytes(len);
   2343 	}
   2344 }
   2345 
   2346 /* Reset after_authentication and reset compression in post-auth privsep */
   2347 static int
   2348 ssh_packet_set_postauth(struct ssh *ssh)
   2349 {
   2350 	struct sshcomp *comp;
   2351 	int r, mode;
   2352 
   2353 	debug("%s: called", __func__);
   2354 	/* This was set in net child, but is not visible in user child */
   2355 	ssh->state->after_authentication = 1;
   2356 	ssh->state->rekeying = 0;
   2357 	for (mode = 0; mode < MODE_MAX; mode++) {
   2358 		if (ssh->state->newkeys[mode] == NULL)
   2359 			continue;
   2360 		comp = &ssh->state->newkeys[mode]->comp;
   2361 		if (comp && comp->enabled &&
   2362 		    (r = ssh_packet_init_compression(ssh)) != 0)
   2363 			return r;
   2364 	}
   2365 	return 0;
   2366 }
   2367 
   2368 /* Packet state (de-)serialization for privsep */
   2369 
   2370 /* turn kex into a blob for packet state serialization */
   2371 static int
   2372 kex_to_blob(struct sshbuf *m, struct kex *kex)
   2373 {
   2374 	int r;
   2375 
   2376 	if ((r = sshbuf_put_string(m, kex->session_id,
   2377 	    kex->session_id_len)) != 0 ||
   2378 	    (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
   2379 	    (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
   2380 	    (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
   2381 	    (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
   2382 	    (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
   2383 	    (r = sshbuf_put_u32(m, kex->flags)) != 0 ||
   2384 	    (r = sshbuf_put_cstring(m, kex->client_version_string)) != 0 ||
   2385 	    (r = sshbuf_put_cstring(m, kex->server_version_string)) != 0)
   2386 		return r;
   2387 	return 0;
   2388 }
   2389 
   2390 /* turn key exchange results into a blob for packet state serialization */
   2391 static int
   2392 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
   2393 {
   2394 	struct sshbuf *b;
   2395 	struct sshcipher_ctx *cc;
   2396 	struct sshcomp *comp;
   2397 	struct sshenc *enc;
   2398 	struct sshmac *mac;
   2399 	struct newkeys *newkey;
   2400 	int r;
   2401 
   2402 	if ((newkey = ssh->state->newkeys[mode]) == NULL)
   2403 		return SSH_ERR_INTERNAL_ERROR;
   2404 	enc = &newkey->enc;
   2405 	mac = &newkey->mac;
   2406 	comp = &newkey->comp;
   2407 	cc = (mode == MODE_OUT) ? &ssh->state->send_context :
   2408 	    &ssh->state->receive_context;
   2409 	if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
   2410 		return r;
   2411 	if ((b = sshbuf_new()) == NULL)
   2412 		return SSH_ERR_ALLOC_FAIL;
   2413 	/* The cipher struct is constant and shared, you export pointer */
   2414 	if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
   2415 	    (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
   2416 	    (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
   2417 	    (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
   2418 	    (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
   2419 	    (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
   2420 		goto out;
   2421 	if (cipher_authlen(enc->cipher) == 0) {
   2422 		if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
   2423 		    (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
   2424 		    (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
   2425 			goto out;
   2426 	}
   2427 	if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
   2428 	    (r = sshbuf_put_u32(b, comp->enabled)) != 0 ||
   2429 	    (r = sshbuf_put_cstring(b, comp->name)) != 0)
   2430 		goto out;
   2431 	r = sshbuf_put_stringb(m, b);
   2432  out:
   2433 	if (b != NULL)
   2434 		sshbuf_free(b);
   2435 	return r;
   2436 }
   2437 
   2438 /* serialize packet state into a blob */
   2439 int
   2440 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
   2441 {
   2442 	struct session_state *state = ssh->state;
   2443 	u_char *p;
   2444 	size_t slen, rlen;
   2445 	int r, ssh1cipher;
   2446 
   2447 	if (!compat20) {
   2448 		ssh1cipher = cipher_get_number(state->receive_context.cipher);
   2449 		slen = cipher_get_keyiv_len(&state->send_context);
   2450 		rlen = cipher_get_keyiv_len(&state->receive_context);
   2451 		if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
   2452 		    (r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
   2453 		    (r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
   2454 		    (r = sshbuf_put_u32(m, slen)) != 0 ||
   2455 		    (r = sshbuf_reserve(m, slen, &p)) != 0 ||
   2456 		    (r = cipher_get_keyiv(&state->send_context, p, slen)) != 0 ||
   2457 		    (r = sshbuf_put_u32(m, rlen)) != 0 ||
   2458 		    (r = sshbuf_reserve(m, rlen, &p)) != 0 ||
   2459 		    (r = cipher_get_keyiv(&state->receive_context, p, rlen)) != 0)
   2460 			return r;
   2461 	} else {
   2462 		if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
   2463 		    (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
   2464 		    (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
   2465 		    (r = sshbuf_put_u32(m, state->rekey_limit)) != 0 ||
   2466 		    (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
   2467 		    (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
   2468 		    (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
   2469 		    (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
   2470 		    (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
   2471 		    (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
   2472 		    (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
   2473 		    (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
   2474 		    (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
   2475 			return r;
   2476 	}
   2477 
   2478 	slen = cipher_get_keycontext(&state->send_context, NULL);
   2479 	rlen = cipher_get_keycontext(&state->receive_context, NULL);
   2480 	if ((r = sshbuf_put_u32(m, slen)) != 0 ||
   2481 	    (r = sshbuf_reserve(m, slen, &p)) != 0)
   2482 		return r;
   2483 	if (cipher_get_keycontext(&state->send_context, p) != (int)slen)
   2484 		return SSH_ERR_INTERNAL_ERROR;
   2485 	if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
   2486 	    (r = sshbuf_reserve(m, rlen, &p)) != 0)
   2487 		return r;
   2488 	if (cipher_get_keycontext(&state->receive_context, p) != (int)rlen)
   2489 		return SSH_ERR_INTERNAL_ERROR;
   2490 
   2491 	if ((r = ssh_packet_get_compress_state(m, ssh)) != 0 ||
   2492 	    (r = sshbuf_put_stringb(m, state->input)) != 0 ||
   2493 	    (r = sshbuf_put_stringb(m, state->output)) != 0)
   2494 		return r;
   2495 
   2496 	if (compat20) {
   2497 		if ((r = sshbuf_put_u64(m, get_sent_bytes())) != 0 ||
   2498 		    (r = sshbuf_put_u64(m, get_recv_bytes())) != 0)
   2499 			return r;
   2500 	}
   2501 	return 0;
   2502 }
   2503 
   2504 /* restore key exchange results from blob for packet state de-serialization */
   2505 static int
   2506 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
   2507 {
   2508 	struct sshbuf *b = NULL;
   2509 	struct sshcomp *comp;
   2510 	struct sshenc *enc;
   2511 	struct sshmac *mac;
   2512 	struct newkeys *newkey = NULL;
   2513 	size_t keylen, ivlen, maclen;
   2514 	int r;
   2515 
   2516 	if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
   2517 		r = SSH_ERR_ALLOC_FAIL;
   2518 		goto out;
   2519 	}
   2520 	if ((r = sshbuf_froms(m, &b)) != 0)
   2521 		goto out;
   2522 #ifdef DEBUG_PK
   2523 	sshbuf_dump(b, stderr);
   2524 #endif
   2525 	enc = &newkey->enc;
   2526 	mac = &newkey->mac;
   2527 	comp = &newkey->comp;
   2528 
   2529 	if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
   2530 	    (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
   2531 	    (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
   2532 	    (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
   2533 	    (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
   2534 	    (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
   2535 		goto out;
   2536 	if (cipher_authlen(enc->cipher) == 0) {
   2537 		if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
   2538 			goto out;
   2539 		if ((r = mac_setup(mac, mac->name)) != 0)
   2540 			goto out;
   2541 		if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
   2542 		    (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
   2543 			goto out;
   2544 		if (maclen > mac->key_len) {
   2545 			r = SSH_ERR_INVALID_FORMAT;
   2546 			goto out;
   2547 		}
   2548 		mac->key_len = maclen;
   2549 	}
   2550 	if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
   2551 	    (r = sshbuf_get_u32(b, (u_int *)&comp->enabled)) != 0 ||
   2552 	    (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
   2553 		goto out;
   2554 	if (enc->name == NULL ||
   2555 	    cipher_by_name(enc->name) != enc->cipher) {
   2556 		r = SSH_ERR_INVALID_FORMAT;
   2557 		goto out;
   2558 	}
   2559 	if (sshbuf_len(b) != 0) {
   2560 		r = SSH_ERR_INVALID_FORMAT;
   2561 		goto out;
   2562 	}
   2563 	enc->key_len = keylen;
   2564 	enc->iv_len = ivlen;
   2565 	ssh->kex->newkeys[mode] = newkey;
   2566 	newkey = NULL;
   2567 	r = 0;
   2568  out:
   2569 	if (newkey != NULL)
   2570 		free(newkey);
   2571 	if (b != NULL)
   2572 		sshbuf_free(b);
   2573 	return r;
   2574 }
   2575 
   2576 /* restore kex from blob for packet state de-serialization */
   2577 static int
   2578 kex_from_blob(struct sshbuf *m, struct kex **kexp)
   2579 {
   2580 	struct kex *kex;
   2581 	int r;
   2582 
   2583 	if ((kex = calloc(1, sizeof(struct kex))) == NULL ||
   2584 	    (kex->my = sshbuf_new()) == NULL ||
   2585 	    (kex->peer = sshbuf_new()) == NULL) {
   2586 		r = SSH_ERR_ALLOC_FAIL;
   2587 		goto out;
   2588 	}
   2589 	if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
   2590 	    (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
   2591 	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
   2592 	    (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
   2593 	    (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
   2594 	    (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
   2595 	    (r = sshbuf_get_u32(m, &kex->flags)) != 0 ||
   2596 	    (r = sshbuf_get_cstring(m, &kex->client_version_string, NULL)) != 0 ||
   2597 	    (r = sshbuf_get_cstring(m, &kex->server_version_string, NULL)) != 0)
   2598 		goto out;
   2599 	kex->server = 1;
   2600 	kex->done = 1;
   2601 	r = 0;
   2602  out:
   2603 	if (r != 0 || kexp == NULL) {
   2604 		if (kex != NULL) {
   2605 			if (kex->my != NULL)
   2606 				sshbuf_free(kex->my);
   2607 			if (kex->peer != NULL)
   2608 				sshbuf_free(kex->peer);
   2609 			free(kex);
   2610 		}
   2611 		if (kexp != NULL)
   2612 			*kexp = NULL;
   2613 	} else {
   2614 		*kexp = kex;
   2615 	}
   2616 	return r;
   2617 }
   2618 
   2619 /*
   2620  * Restore packet state from content of blob 'm' (de-serialization).
   2621  * Note that 'm' will be partially consumed on parsing or any other errors.
   2622  */
   2623 int
   2624 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
   2625 {
   2626 	struct session_state *state = ssh->state;
   2627 	const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output;
   2628 	size_t ssh1keylen, rlen, slen, ilen, olen;
   2629 	int r;
   2630 	u_int ssh1cipher = 0;
   2631 	u_int64_t sent_bytes = 0, recv_bytes = 0;
   2632 
   2633 	if (!compat20) {
   2634 		if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 ||
   2635 		    (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 ||
   2636 		    (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 ||
   2637 		    (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 ||
   2638 		    (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0)
   2639 			return r;
   2640 		if (ssh1cipher > INT_MAX)
   2641 			return SSH_ERR_KEY_UNKNOWN_CIPHER;
   2642 		ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen,
   2643 		    (int)ssh1cipher);
   2644 		if (cipher_get_keyiv_len(&state->send_context) != (int)slen ||
   2645 		    cipher_get_keyiv_len(&state->receive_context) != (int)rlen)
   2646 			return SSH_ERR_INVALID_FORMAT;
   2647 		if ((r = cipher_set_keyiv(&state->send_context, ivout)) != 0 ||
   2648 		    (r = cipher_set_keyiv(&state->receive_context, ivin)) != 0)
   2649 			return r;
   2650 	} else {
   2651 		if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
   2652 		    (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
   2653 		    (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
   2654 		    (r = sshbuf_get_u32(m, &state->rekey_limit)) != 0 ||
   2655 		    (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
   2656 		    (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
   2657 		    (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
   2658 		    (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
   2659 		    (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
   2660 		    (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
   2661 		    (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
   2662 		    (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
   2663 		    (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
   2664 			return r;
   2665 		/*
   2666 		 * We set the time here so that in post-auth privsep slave we
   2667 		 * count from the completion of the authentication.
   2668 		 */
   2669 		state->rekey_time = monotime();
   2670 		/* XXX ssh_set_newkeys overrides p_read.packets? XXX */
   2671 		if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
   2672 		    (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
   2673 			return r;
   2674 	}
   2675 	if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 ||
   2676 	    (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0)
   2677 		return r;
   2678 	if (cipher_get_keycontext(&state->send_context, NULL) != (int)slen ||
   2679 	    cipher_get_keycontext(&state->receive_context, NULL) != (int)rlen)
   2680 		return SSH_ERR_INVALID_FORMAT;
   2681 	cipher_set_keycontext(&state->send_context, keyout);
   2682 	cipher_set_keycontext(&state->receive_context, keyin);
   2683 
   2684 	if ((r = ssh_packet_set_compress_state(ssh, m)) != 0 ||
   2685 	    (r = ssh_packet_set_postauth(ssh)) != 0)
   2686 		return r;
   2687 
   2688 	sshbuf_reset(state->input);
   2689 	sshbuf_reset(state->output);
   2690 	if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
   2691 	    (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
   2692 	    (r = sshbuf_put(state->input, input, ilen)) != 0 ||
   2693 	    (r = sshbuf_put(state->output, output, olen)) != 0)
   2694 		return r;
   2695 
   2696 	if (compat20) {
   2697 		if ((r = sshbuf_get_u64(m, &sent_bytes)) != 0 ||
   2698 		    (r = sshbuf_get_u64(m, &recv_bytes)) != 0)
   2699 			return r;
   2700 		roam_set_bytes(sent_bytes, recv_bytes);
   2701 	}
   2702 	if (sshbuf_len(m))
   2703 		return SSH_ERR_INVALID_FORMAT;
   2704 	debug3("%s: done", __func__);
   2705 	return 0;
   2706 }
   2707 
   2708 /* NEW API */
   2709 
   2710 /* put data to the outgoing packet */
   2711 
   2712 int
   2713 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
   2714 {
   2715 	return sshbuf_put(ssh->state->outgoing_packet, v, len);
   2716 }
   2717 
   2718 int
   2719 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
   2720 {
   2721 	return sshbuf_putb(ssh->state->outgoing_packet, b);
   2722 }
   2723 
   2724 int
   2725 sshpkt_put_u8(struct ssh *ssh, u_char val)
   2726 {
   2727 	return sshbuf_put_u8(ssh->state->outgoing_packet, val);
   2728 }
   2729 
   2730 int
   2731 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
   2732 {
   2733 	return sshbuf_put_u32(ssh->state->outgoing_packet, val);
   2734 }
   2735 
   2736 int
   2737 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
   2738 {
   2739 	return sshbuf_put_u64(ssh->state->outgoing_packet, val);
   2740 }
   2741 
   2742 int
   2743 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
   2744 {
   2745 	return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
   2746 }
   2747 
   2748 int
   2749 sshpkt_put_cstring(struct ssh *ssh, const void *v)
   2750 {
   2751 	return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
   2752 }
   2753 
   2754 int
   2755 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
   2756 {
   2757 	return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
   2758 }
   2759 
   2760 #ifdef WITH_OPENSSL
   2761 #ifdef OPENSSL_HAS_ECC
   2762 int
   2763 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
   2764 {
   2765 	return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
   2766 }
   2767 #endif /* OPENSSL_HAS_ECC */
   2768 
   2769 #ifdef WITH_SSH1
   2770 int
   2771 sshpkt_put_bignum1(struct ssh *ssh, const BIGNUM *v)
   2772 {
   2773 	return sshbuf_put_bignum1(ssh->state->outgoing_packet, v);
   2774 }
   2775 #endif /* WITH_SSH1 */
   2776 
   2777 int
   2778 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
   2779 {
   2780 	return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
   2781 }
   2782 #endif /* WITH_OPENSSL */
   2783 
   2784 /* fetch data from the incoming packet */
   2785 
   2786 int
   2787 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
   2788 {
   2789 	return sshbuf_get(ssh->state->incoming_packet, valp, len);
   2790 }
   2791 
   2792 int
   2793 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
   2794 {
   2795 	return sshbuf_get_u8(ssh->state->incoming_packet, valp);
   2796 }
   2797 
   2798 int
   2799 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
   2800 {
   2801 	return sshbuf_get_u32(ssh->state->incoming_packet, valp);
   2802 }
   2803 
   2804 int
   2805 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
   2806 {
   2807 	return sshbuf_get_u64(ssh->state->incoming_packet, valp);
   2808 }
   2809 
   2810 int
   2811 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
   2812 {
   2813 	return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
   2814 }
   2815 
   2816 int
   2817 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
   2818 {
   2819 	return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
   2820 }
   2821 
   2822 int
   2823 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
   2824 {
   2825 	return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
   2826 }
   2827 
   2828 #ifdef WITH_OPENSSL
   2829 #ifdef OPENSSL_HAS_ECC
   2830 int
   2831 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
   2832 {
   2833 	return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
   2834 }
   2835 #endif /* OPENSSL_HAS_ECC */
   2836 
   2837 #ifdef WITH_SSH1
   2838 int
   2839 sshpkt_get_bignum1(struct ssh *ssh, BIGNUM *v)
   2840 {
   2841 	return sshbuf_get_bignum1(ssh->state->incoming_packet, v);
   2842 }
   2843 #endif /* WITH_SSH1 */
   2844 
   2845 int
   2846 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM *v)
   2847 {
   2848 	return sshbuf_get_bignum2(ssh->state->incoming_packet, v);
   2849 }
   2850 #endif /* WITH_OPENSSL */
   2851 
   2852 int
   2853 sshpkt_get_end(struct ssh *ssh)
   2854 {
   2855 	if (sshbuf_len(ssh->state->incoming_packet) > 0)
   2856 		return SSH_ERR_UNEXPECTED_TRAILING_DATA;
   2857 	return 0;
   2858 }
   2859 
   2860 const u_char *
   2861 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
   2862 {
   2863 	if (lenp != NULL)
   2864 		*lenp = sshbuf_len(ssh->state->incoming_packet);
   2865 	return sshbuf_ptr(ssh->state->incoming_packet);
   2866 }
   2867 
   2868 /* start a new packet */
   2869 
   2870 int
   2871 sshpkt_start(struct ssh *ssh, u_char type)
   2872 {
   2873 	u_char buf[9];
   2874 	int len;
   2875 
   2876 	DBG(debug("packet_start[%d]", type));
   2877 	len = compat20 ? 6 : 9;
   2878 	memset(buf, 0, len - 1);
   2879 	buf[len - 1] = type;
   2880 	sshbuf_reset(ssh->state->outgoing_packet);
   2881 	return sshbuf_put(ssh->state->outgoing_packet, buf, len);
   2882 }
   2883 
   2884 /* send it */
   2885 
   2886 int
   2887 sshpkt_send(struct ssh *ssh)
   2888 {
   2889 	if (compat20)
   2890 		return ssh_packet_send2(ssh);
   2891 	else
   2892 		return ssh_packet_send1(ssh);
   2893 }
   2894 
   2895 int
   2896 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
   2897 {
   2898 	char buf[1024];
   2899 	va_list args;
   2900 	int r;
   2901 
   2902 	va_start(args, fmt);
   2903 	vsnprintf(buf, sizeof(buf), fmt, args);
   2904 	va_end(args);
   2905 
   2906 	if (compat20) {
   2907 		if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
   2908 		    (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
   2909 		    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
   2910 		    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
   2911 		    (r = sshpkt_send(ssh)) != 0)
   2912 			return r;
   2913 	} else {
   2914 		if ((r = sshpkt_start(ssh, SSH_MSG_DISCONNECT)) != 0 ||
   2915 		    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
   2916 		    (r = sshpkt_send(ssh)) != 0)
   2917 			return r;
   2918 	}
   2919 	return 0;
   2920 }
   2921 
   2922 /* roundup current message to pad bytes */
   2923 int
   2924 sshpkt_add_padding(struct ssh *ssh, u_char pad)
   2925 {
   2926 	ssh->state->extra_pad = pad;
   2927 	return 0;
   2928 }
   2929