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