xref: /dflybsd-src/crypto/openssh/packet.c (revision ba1276acd1c8c22d225b1bcf370a14c878644f44)
1*ba1276acSMatthew Dillon /* $OpenBSD: packet.c,v 1.315 2024/05/31 08:49:35 djm Exp $ */
218de8d7fSPeter Avalos /*
318de8d7fSPeter Avalos  * Author: Tatu Ylonen <ylo@cs.hut.fi>
418de8d7fSPeter Avalos  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
518de8d7fSPeter Avalos  *                    All rights reserved
618de8d7fSPeter Avalos  * This file contains code implementing the packet protocol and communication
718de8d7fSPeter Avalos  * with the other side.  This same code is used both on client and server side.
818de8d7fSPeter Avalos  *
918de8d7fSPeter Avalos  * As far as I am concerned, the code I have written for this software
1018de8d7fSPeter Avalos  * can be used freely for any purpose.  Any derived versions of this
1118de8d7fSPeter Avalos  * software must be clearly marked as such, and if the derived work is
1218de8d7fSPeter Avalos  * incompatible with the protocol description in the RFC file, it must be
1318de8d7fSPeter Avalos  * called by a name other than "ssh" or "Secure Shell".
1418de8d7fSPeter Avalos  *
1518de8d7fSPeter Avalos  *
1618de8d7fSPeter Avalos  * SSH2 packet format added by Markus Friedl.
1718de8d7fSPeter Avalos  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
1818de8d7fSPeter Avalos  *
1918de8d7fSPeter Avalos  * Redistribution and use in source and binary forms, with or without
2018de8d7fSPeter Avalos  * modification, are permitted provided that the following conditions
2118de8d7fSPeter Avalos  * are met:
2218de8d7fSPeter Avalos  * 1. Redistributions of source code must retain the above copyright
2318de8d7fSPeter Avalos  *    notice, this list of conditions and the following disclaimer.
2418de8d7fSPeter Avalos  * 2. Redistributions in binary form must reproduce the above copyright
2518de8d7fSPeter Avalos  *    notice, this list of conditions and the following disclaimer in the
2618de8d7fSPeter Avalos  *    documentation and/or other materials provided with the distribution.
2718de8d7fSPeter Avalos  *
2818de8d7fSPeter Avalos  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
2918de8d7fSPeter Avalos  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
3018de8d7fSPeter Avalos  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
3118de8d7fSPeter Avalos  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
3218de8d7fSPeter Avalos  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
3318de8d7fSPeter Avalos  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3418de8d7fSPeter Avalos  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3518de8d7fSPeter Avalos  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3618de8d7fSPeter Avalos  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
3718de8d7fSPeter Avalos  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3818de8d7fSPeter Avalos  */
3918de8d7fSPeter Avalos 
4018de8d7fSPeter Avalos #include "includes.h"
4118de8d7fSPeter Avalos 
4218de8d7fSPeter Avalos #include <sys/types.h>
4318de8d7fSPeter Avalos #include "openbsd-compat/sys-queue.h"
4418de8d7fSPeter Avalos #include <sys/socket.h>
4518de8d7fSPeter Avalos #ifdef HAVE_SYS_TIME_H
4618de8d7fSPeter Avalos # include <sys/time.h>
4718de8d7fSPeter Avalos #endif
4818de8d7fSPeter Avalos 
4918de8d7fSPeter Avalos #include <netinet/in.h>
5018de8d7fSPeter Avalos #include <netinet/ip.h>
5118de8d7fSPeter Avalos #include <arpa/inet.h>
5218de8d7fSPeter Avalos 
5318de8d7fSPeter Avalos #include <errno.h>
54e9778795SPeter Avalos #include <netdb.h>
5518de8d7fSPeter Avalos #include <stdarg.h>
5618de8d7fSPeter Avalos #include <stdio.h>
5718de8d7fSPeter Avalos #include <stdlib.h>
5818de8d7fSPeter Avalos #include <string.h>
5918de8d7fSPeter Avalos #include <unistd.h>
60e9778795SPeter Avalos #include <limits.h>
610cbfa66cSDaniel Fojt #ifdef HAVE_POLL_H
62664f4763Szrj #include <poll.h>
630cbfa66cSDaniel Fojt #endif
6418de8d7fSPeter Avalos #include <signal.h>
6536e94dc5SPeter Avalos #include <time.h>
6618de8d7fSPeter Avalos 
67664f4763Szrj /*
68664f4763Szrj  * Explicitly include OpenSSL before zlib as some versions of OpenSSL have
69664f4763Szrj  * "free_func" in their headers, which zlib typedefs.
70664f4763Szrj  */
71664f4763Szrj #ifdef WITH_OPENSSL
72664f4763Szrj # include <openssl/bn.h>
73664f4763Szrj # include <openssl/evp.h>
74664f4763Szrj # ifdef OPENSSL_HAS_ECC
75664f4763Szrj #  include <openssl/ec.h>
76664f4763Szrj # endif
77664f4763Szrj #endif
78e9778795SPeter Avalos 
790cbfa66cSDaniel Fojt #ifdef WITH_ZLIB
80664f4763Szrj #include <zlib.h>
810cbfa66cSDaniel Fojt #endif
82e9778795SPeter Avalos 
8318de8d7fSPeter Avalos #include "xmalloc.h"
8418de8d7fSPeter Avalos #include "compat.h"
8518de8d7fSPeter Avalos #include "ssh2.h"
8618de8d7fSPeter Avalos #include "cipher.h"
87e9778795SPeter Avalos #include "sshkey.h"
8818de8d7fSPeter Avalos #include "kex.h"
89e9778795SPeter Avalos #include "digest.h"
9018de8d7fSPeter Avalos #include "mac.h"
9118de8d7fSPeter Avalos #include "log.h"
9218de8d7fSPeter Avalos #include "canohost.h"
9318de8d7fSPeter Avalos #include "misc.h"
9436e94dc5SPeter Avalos #include "channels.h"
9518de8d7fSPeter Avalos #include "ssh.h"
96e9778795SPeter Avalos #include "packet.h"
9736e94dc5SPeter Avalos #include "ssherr.h"
98e9778795SPeter Avalos #include "sshbuf.h"
9918de8d7fSPeter Avalos 
10018de8d7fSPeter Avalos #ifdef PACKET_DEBUG
10118de8d7fSPeter Avalos #define DBG(x) x
10218de8d7fSPeter Avalos #else
10318de8d7fSPeter Avalos #define DBG(x)
10418de8d7fSPeter Avalos #endif
10518de8d7fSPeter Avalos 
106cb5eb4f1SPeter Avalos #define PACKET_MAX_SIZE (256 * 1024)
107cb5eb4f1SPeter Avalos 
10840c002afSPeter Avalos struct packet_state {
10940c002afSPeter Avalos 	u_int32_t seqnr;
11040c002afSPeter Avalos 	u_int32_t packets;
11140c002afSPeter Avalos 	u_int64_t blocks;
11240c002afSPeter Avalos 	u_int64_t bytes;
11340c002afSPeter Avalos };
11440c002afSPeter Avalos 
11540c002afSPeter Avalos struct packet {
11640c002afSPeter Avalos 	TAILQ_ENTRY(packet) next;
11740c002afSPeter Avalos 	u_char type;
118e9778795SPeter Avalos 	struct sshbuf *payload;
11940c002afSPeter Avalos };
12040c002afSPeter Avalos 
12140c002afSPeter Avalos struct session_state {
12218de8d7fSPeter Avalos 	/*
12340c002afSPeter Avalos 	 * This variable contains the file descriptors used for
12440c002afSPeter Avalos 	 * communicating with the other side.  connection_in is used for
12540c002afSPeter Avalos 	 * reading; connection_out for writing.  These can be the same
12640c002afSPeter Avalos 	 * descriptor, in which case it is assumed to be a socket.
12718de8d7fSPeter Avalos 	 */
12840c002afSPeter Avalos 	int connection_in;
12940c002afSPeter Avalos 	int connection_out;
13018de8d7fSPeter Avalos 
13118de8d7fSPeter Avalos 	/* Protocol flags for the remote side. */
13240c002afSPeter Avalos 	u_int remote_protocol_flags;
13318de8d7fSPeter Avalos 
13440c002afSPeter Avalos 	/* Encryption context for receiving data.  Only used for decryption. */
135ce74bacaSMatthew Dillon 	struct sshcipher_ctx *receive_context;
13618de8d7fSPeter Avalos 
13740c002afSPeter Avalos 	/* Encryption context for sending data.  Only used for encryption. */
138ce74bacaSMatthew Dillon 	struct sshcipher_ctx *send_context;
13918de8d7fSPeter Avalos 
14018de8d7fSPeter Avalos 	/* Buffer for raw input data from the socket. */
141e9778795SPeter Avalos 	struct sshbuf *input;
14218de8d7fSPeter Avalos 
14318de8d7fSPeter Avalos 	/* Buffer for raw output data going to the socket. */
144e9778795SPeter Avalos 	struct sshbuf *output;
14518de8d7fSPeter Avalos 
14618de8d7fSPeter Avalos 	/* Buffer for the partial outgoing packet being constructed. */
147e9778795SPeter Avalos 	struct sshbuf *outgoing_packet;
14818de8d7fSPeter Avalos 
14918de8d7fSPeter Avalos 	/* Buffer for the incoming packet currently being processed. */
150e9778795SPeter Avalos 	struct sshbuf *incoming_packet;
15118de8d7fSPeter Avalos 
15218de8d7fSPeter Avalos 	/* Scratch buffer for packet compression/decompression. */
153e9778795SPeter Avalos 	struct sshbuf *compression_buffer;
154e9778795SPeter Avalos 
1550cbfa66cSDaniel Fojt #ifdef WITH_ZLIB
156e9778795SPeter Avalos 	/* Incoming/outgoing compression dictionaries */
157e9778795SPeter Avalos 	z_stream compression_in_stream;
158e9778795SPeter Avalos 	z_stream compression_out_stream;
1590cbfa66cSDaniel Fojt #endif
160e9778795SPeter Avalos 	int compression_in_started;
161e9778795SPeter Avalos 	int compression_out_started;
162e9778795SPeter Avalos 	int compression_in_failures;
163e9778795SPeter Avalos 	int compression_out_failures;
16418de8d7fSPeter Avalos 
16518de8d7fSPeter Avalos 	/* default maximum packet size */
16640c002afSPeter Avalos 	u_int max_packet_size;
16718de8d7fSPeter Avalos 
16818de8d7fSPeter Avalos 	/* Flag indicating whether this module has been initialized. */
16940c002afSPeter Avalos 	int initialized;
17018de8d7fSPeter Avalos 
17118de8d7fSPeter Avalos 	/* Set to true if the connection is interactive. */
17240c002afSPeter Avalos 	int interactive_mode;
17318de8d7fSPeter Avalos 
17418de8d7fSPeter Avalos 	/* Set to true if we are the server side. */
17540c002afSPeter Avalos 	int server_side;
17618de8d7fSPeter Avalos 
17718de8d7fSPeter Avalos 	/* Set to true if we are authenticated. */
17840c002afSPeter Avalos 	int after_authentication;
17918de8d7fSPeter Avalos 
18040c002afSPeter Avalos 	int keep_alive_timeouts;
18118de8d7fSPeter Avalos 
18240c002afSPeter Avalos 	/* The maximum time that we will wait to send or receive a packet */
18340c002afSPeter Avalos 	int packet_timeout_ms;
18418de8d7fSPeter Avalos 
18518de8d7fSPeter Avalos 	/* Session key information for Encryption and MAC */
186e9778795SPeter Avalos 	struct newkeys *newkeys[MODE_MAX];
18740c002afSPeter Avalos 	struct packet_state p_read, p_send;
18818de8d7fSPeter Avalos 
18936e94dc5SPeter Avalos 	/* Volume-based rekeying */
190e9778795SPeter Avalos 	u_int64_t max_blocks_in, max_blocks_out, rekey_limit;
19118de8d7fSPeter Avalos 
19236e94dc5SPeter Avalos 	/* Time-based rekeying */
193e9778795SPeter Avalos 	u_int32_t rekey_interval;	/* how often in seconds */
19436e94dc5SPeter Avalos 	time_t rekey_time;	/* time of last rekeying */
19536e94dc5SPeter Avalos 
19618de8d7fSPeter Avalos 	/* roundup current message to extra_pad bytes */
19740c002afSPeter Avalos 	u_char extra_pad;
19818de8d7fSPeter Avalos 
199cb5eb4f1SPeter Avalos 	/* XXX discard incoming data after MAC error */
20040c002afSPeter Avalos 	u_int packet_discard;
201e9778795SPeter Avalos 	size_t packet_discard_mac_already;
202e9778795SPeter Avalos 	struct sshmac *packet_discard_mac;
203cb5eb4f1SPeter Avalos 
20440c002afSPeter Avalos 	/* Used in packet_read_poll2() */
20540c002afSPeter Avalos 	u_int packlen;
20640c002afSPeter Avalos 
20740c002afSPeter Avalos 	/* Used in packet_send2 */
20840c002afSPeter Avalos 	int rekeying;
20940c002afSPeter Avalos 
210ce74bacaSMatthew Dillon 	/* Used in ssh_packet_send_mux() */
211ce74bacaSMatthew Dillon 	int mux;
212ce74bacaSMatthew Dillon 
21340c002afSPeter Avalos 	/* Used in packet_set_interactive */
21440c002afSPeter Avalos 	int set_interactive_called;
21540c002afSPeter Avalos 
21640c002afSPeter Avalos 	/* Used in packet_set_maxsize */
21740c002afSPeter Avalos 	int set_maxsize_called;
21840c002afSPeter Avalos 
219e9778795SPeter Avalos 	/* One-off warning about weak ciphers */
220e9778795SPeter Avalos 	int cipher_warning_done;
221e9778795SPeter Avalos 
222ce74bacaSMatthew Dillon 	/* Hook for fuzzing inbound packets */
223ce74bacaSMatthew Dillon 	ssh_packet_hook_fn *hook_in;
224ce74bacaSMatthew Dillon 	void *hook_in_ctx;
225e9778795SPeter Avalos 
22618de8d7fSPeter Avalos 	TAILQ_HEAD(, packet) outgoing;
22740c002afSPeter Avalos };
22840c002afSPeter Avalos 
229e9778795SPeter Avalos struct ssh *
ssh_alloc_session_state(void)230e9778795SPeter Avalos ssh_alloc_session_state(void)
23140c002afSPeter Avalos {
232e9778795SPeter Avalos 	struct ssh *ssh = NULL;
233e9778795SPeter Avalos 	struct session_state *state = NULL;
23440c002afSPeter Avalos 
235e9778795SPeter Avalos 	if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
236e9778795SPeter Avalos 	    (state = calloc(1, sizeof(*state))) == NULL ||
237664f4763Szrj 	    (ssh->kex = kex_new()) == NULL ||
238e9778795SPeter Avalos 	    (state->input = sshbuf_new()) == NULL ||
239e9778795SPeter Avalos 	    (state->output = sshbuf_new()) == NULL ||
240e9778795SPeter Avalos 	    (state->outgoing_packet = sshbuf_new()) == NULL ||
241e9778795SPeter Avalos 	    (state->incoming_packet = sshbuf_new()) == NULL)
242e9778795SPeter Avalos 		goto fail;
243e9778795SPeter Avalos 	TAILQ_INIT(&state->outgoing);
244e9778795SPeter Avalos 	TAILQ_INIT(&ssh->private_keys);
245e9778795SPeter Avalos 	TAILQ_INIT(&ssh->public_keys);
246e9778795SPeter Avalos 	state->connection_in = -1;
247e9778795SPeter Avalos 	state->connection_out = -1;
248e9778795SPeter Avalos 	state->max_packet_size = 32768;
249e9778795SPeter Avalos 	state->packet_timeout_ms = -1;
250e9778795SPeter Avalos 	state->p_send.packets = state->p_read.packets = 0;
251e9778795SPeter Avalos 	state->initialized = 1;
252e9778795SPeter Avalos 	/*
253e9778795SPeter Avalos 	 * ssh_packet_send2() needs to queue packets until
254e9778795SPeter Avalos 	 * we've done the initial key exchange.
255e9778795SPeter Avalos 	 */
256e9778795SPeter Avalos 	state->rekeying = 1;
257e9778795SPeter Avalos 	ssh->state = state;
258e9778795SPeter Avalos 	return ssh;
259e9778795SPeter Avalos  fail:
260664f4763Szrj 	if (ssh) {
261664f4763Szrj 		kex_free(ssh->kex);
262664f4763Szrj 		free(ssh);
263664f4763Szrj 	}
264e9778795SPeter Avalos 	if (state) {
265e9778795SPeter Avalos 		sshbuf_free(state->input);
266e9778795SPeter Avalos 		sshbuf_free(state->output);
267e9778795SPeter Avalos 		sshbuf_free(state->incoming_packet);
268e9778795SPeter Avalos 		sshbuf_free(state->outgoing_packet);
269e9778795SPeter Avalos 		free(state);
270e9778795SPeter Avalos 	}
271e9778795SPeter Avalos 	return NULL;
272e9778795SPeter Avalos }
273e9778795SPeter Avalos 
274ce74bacaSMatthew Dillon void
ssh_packet_set_input_hook(struct ssh * ssh,ssh_packet_hook_fn * hook,void * ctx)275ce74bacaSMatthew Dillon ssh_packet_set_input_hook(struct ssh *ssh, ssh_packet_hook_fn *hook, void *ctx)
276ce74bacaSMatthew Dillon {
277ce74bacaSMatthew Dillon 	ssh->state->hook_in = hook;
278ce74bacaSMatthew Dillon 	ssh->state->hook_in_ctx = ctx;
279ce74bacaSMatthew Dillon }
280ce74bacaSMatthew Dillon 
281e9778795SPeter Avalos /* Returns nonzero if rekeying is in progress */
282e9778795SPeter Avalos int
ssh_packet_is_rekeying(struct ssh * ssh)283e9778795SPeter Avalos ssh_packet_is_rekeying(struct ssh *ssh)
284e9778795SPeter Avalos {
28550a69bb5SSascha Wildner 	return ssh->state->rekeying ||
28650a69bb5SSascha Wildner 	    (ssh->kex != NULL && ssh->kex->done == 0);
28740c002afSPeter Avalos }
28818de8d7fSPeter Avalos 
28918de8d7fSPeter Avalos /*
290ce74bacaSMatthew Dillon  * Sets the descriptors used for communication.
29118de8d7fSPeter Avalos  */
292e9778795SPeter Avalos struct ssh *
ssh_packet_set_connection(struct ssh * ssh,int fd_in,int fd_out)293e9778795SPeter Avalos ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
29418de8d7fSPeter Avalos {
295e9778795SPeter Avalos 	struct session_state *state;
296e9778795SPeter Avalos 	const struct sshcipher *none = cipher_by_name("none");
29736e94dc5SPeter Avalos 	int r;
29818de8d7fSPeter Avalos 
299e9778795SPeter Avalos 	if (none == NULL) {
30050a69bb5SSascha Wildner 		error_f("cannot load cipher 'none'");
301e9778795SPeter Avalos 		return NULL;
30218de8d7fSPeter Avalos 	}
303e9778795SPeter Avalos 	if (ssh == NULL)
304e9778795SPeter Avalos 		ssh = ssh_alloc_session_state();
305e9778795SPeter Avalos 	if (ssh == NULL) {
30650a69bb5SSascha Wildner 		error_f("could not allocate state");
307e9778795SPeter Avalos 		return NULL;
308e9778795SPeter Avalos 	}
309e9778795SPeter Avalos 	state = ssh->state;
310e9778795SPeter Avalos 	state->connection_in = fd_in;
311e9778795SPeter Avalos 	state->connection_out = fd_out;
312e9778795SPeter Avalos 	if ((r = cipher_init(&state->send_context, none,
313e9778795SPeter Avalos 	    (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
314e9778795SPeter Avalos 	    (r = cipher_init(&state->receive_context, none,
315e9778795SPeter Avalos 	    (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
31650a69bb5SSascha Wildner 		error_fr(r, "cipher_init failed");
317e9778795SPeter Avalos 		free(ssh); /* XXX need ssh_free_session_state? */
318e9778795SPeter Avalos 		return NULL;
319e9778795SPeter Avalos 	}
320e9778795SPeter Avalos 	state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
321e9778795SPeter Avalos 	/*
322e9778795SPeter Avalos 	 * Cache the IP address of the remote connection for use in error
323e9778795SPeter Avalos 	 * messages that might be generated after the connection has closed.
324e9778795SPeter Avalos 	 */
325e9778795SPeter Avalos 	(void)ssh_remote_ipaddr(ssh);
326e9778795SPeter Avalos 	return ssh;
32718de8d7fSPeter Avalos }
32818de8d7fSPeter Avalos 
32918de8d7fSPeter Avalos void
ssh_packet_set_timeout(struct ssh * ssh,int timeout,int count)330e9778795SPeter Avalos ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
33118de8d7fSPeter Avalos {
332e9778795SPeter Avalos 	struct session_state *state = ssh->state;
333e9778795SPeter Avalos 
33499e85e0dSPeter Avalos 	if (timeout <= 0 || count <= 0) {
335e9778795SPeter Avalos 		state->packet_timeout_ms = -1;
33618de8d7fSPeter Avalos 		return;
33718de8d7fSPeter Avalos 	}
33818de8d7fSPeter Avalos 	if ((INT_MAX / 1000) / count < timeout)
339e9778795SPeter Avalos 		state->packet_timeout_ms = INT_MAX;
34018de8d7fSPeter Avalos 	else
341e9778795SPeter Avalos 		state->packet_timeout_ms = timeout * count * 1000;
34218de8d7fSPeter Avalos }
34318de8d7fSPeter Avalos 
344ce74bacaSMatthew Dillon void
ssh_packet_set_mux(struct ssh * ssh)345ce74bacaSMatthew Dillon ssh_packet_set_mux(struct ssh *ssh)
346ce74bacaSMatthew Dillon {
347ce74bacaSMatthew Dillon 	ssh->state->mux = 1;
348ce74bacaSMatthew Dillon 	ssh->state->rekeying = 0;
34950a69bb5SSascha Wildner 	kex_free(ssh->kex);
35050a69bb5SSascha Wildner 	ssh->kex = NULL;
351ce74bacaSMatthew Dillon }
352ce74bacaSMatthew Dillon 
353ce74bacaSMatthew Dillon int
ssh_packet_get_mux(struct ssh * ssh)354ce74bacaSMatthew Dillon ssh_packet_get_mux(struct ssh *ssh)
355ce74bacaSMatthew Dillon {
356ce74bacaSMatthew Dillon 	return ssh->state->mux;
357ce74bacaSMatthew Dillon }
358ce74bacaSMatthew Dillon 
359ce74bacaSMatthew Dillon int
ssh_packet_set_log_preamble(struct ssh * ssh,const char * fmt,...)360ce74bacaSMatthew Dillon ssh_packet_set_log_preamble(struct ssh *ssh, const char *fmt, ...)
361ce74bacaSMatthew Dillon {
362ce74bacaSMatthew Dillon 	va_list args;
363ce74bacaSMatthew Dillon 	int r;
364ce74bacaSMatthew Dillon 
365ce74bacaSMatthew Dillon 	free(ssh->log_preamble);
366ce74bacaSMatthew Dillon 	if (fmt == NULL)
367ce74bacaSMatthew Dillon 		ssh->log_preamble = NULL;
368ce74bacaSMatthew Dillon 	else {
369ce74bacaSMatthew Dillon 		va_start(args, fmt);
370ce74bacaSMatthew Dillon 		r = vasprintf(&ssh->log_preamble, fmt, args);
371ce74bacaSMatthew Dillon 		va_end(args);
372ce74bacaSMatthew Dillon 		if (r < 0 || ssh->log_preamble == NULL)
373ce74bacaSMatthew Dillon 			return SSH_ERR_ALLOC_FAIL;
374ce74bacaSMatthew Dillon 	}
375ce74bacaSMatthew Dillon 	return 0;
376ce74bacaSMatthew Dillon }
377ce74bacaSMatthew Dillon 
378e9778795SPeter Avalos int
ssh_packet_stop_discard(struct ssh * ssh)379e9778795SPeter Avalos ssh_packet_stop_discard(struct ssh *ssh)
380cb5eb4f1SPeter Avalos {
381e9778795SPeter Avalos 	struct session_state *state = ssh->state;
382e9778795SPeter Avalos 	int r;
383e9778795SPeter Avalos 
384e9778795SPeter Avalos 	if (state->packet_discard_mac) {
385cb5eb4f1SPeter Avalos 		char buf[1024];
386e9778795SPeter Avalos 		size_t dlen = PACKET_MAX_SIZE;
387cb5eb4f1SPeter Avalos 
388e9778795SPeter Avalos 		if (dlen > state->packet_discard_mac_already)
389e9778795SPeter Avalos 			dlen -= state->packet_discard_mac_already;
390cb5eb4f1SPeter Avalos 		memset(buf, 'a', sizeof(buf));
391e9778795SPeter Avalos 		while (sshbuf_len(state->incoming_packet) < dlen)
392e9778795SPeter Avalos 			if ((r = sshbuf_put(state->incoming_packet, buf,
393e9778795SPeter Avalos 			    sizeof(buf))) != 0)
394e9778795SPeter Avalos 				return r;
395e9778795SPeter Avalos 		(void) mac_compute(state->packet_discard_mac,
396e9778795SPeter Avalos 		    state->p_read.seqnr,
397e9778795SPeter Avalos 		    sshbuf_ptr(state->incoming_packet), dlen,
398e9778795SPeter Avalos 		    NULL, 0);
399cb5eb4f1SPeter Avalos 	}
400e9778795SPeter Avalos 	logit("Finished discarding for %.200s port %d",
401e9778795SPeter Avalos 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
402e9778795SPeter Avalos 	return SSH_ERR_MAC_INVALID;
403cb5eb4f1SPeter Avalos }
404cb5eb4f1SPeter Avalos 
405e9778795SPeter Avalos static int
ssh_packet_start_discard(struct ssh * ssh,struct sshenc * enc,struct sshmac * mac,size_t mac_already,u_int discard)406e9778795SPeter Avalos ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
407e9778795SPeter Avalos     struct sshmac *mac, size_t mac_already, u_int discard)
408cb5eb4f1SPeter Avalos {
409e9778795SPeter Avalos 	struct session_state *state = ssh->state;
410e9778795SPeter Avalos 	int r;
411e9778795SPeter Avalos 
412e9778795SPeter Avalos 	if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
413e9778795SPeter Avalos 		if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
414e9778795SPeter Avalos 			return r;
415e9778795SPeter Avalos 		return SSH_ERR_MAC_INVALID;
416e9778795SPeter Avalos 	}
417e9778795SPeter Avalos 	/*
418e9778795SPeter Avalos 	 * Record number of bytes over which the mac has already
419e9778795SPeter Avalos 	 * been computed in order to minimize timing attacks.
420e9778795SPeter Avalos 	 */
421e9778795SPeter Avalos 	if (mac && mac->enabled) {
422e9778795SPeter Avalos 		state->packet_discard_mac = mac;
423e9778795SPeter Avalos 		state->packet_discard_mac_already = mac_already;
424e9778795SPeter Avalos 	}
425e9778795SPeter Avalos 	if (sshbuf_len(state->input) >= discard)
426e9778795SPeter Avalos 		return ssh_packet_stop_discard(ssh);
427e9778795SPeter Avalos 	state->packet_discard = discard - sshbuf_len(state->input);
428e9778795SPeter Avalos 	return 0;
429cb5eb4f1SPeter Avalos }
430cb5eb4f1SPeter Avalos 
43118de8d7fSPeter Avalos /* Returns 1 if remote host is connected via socket, 0 if not. */
43218de8d7fSPeter Avalos 
43318de8d7fSPeter Avalos int
ssh_packet_connection_is_on_socket(struct ssh * ssh)434e9778795SPeter Avalos ssh_packet_connection_is_on_socket(struct ssh *ssh)
43518de8d7fSPeter Avalos {
436664f4763Szrj 	struct session_state *state;
43718de8d7fSPeter Avalos 	struct sockaddr_storage from, to;
43818de8d7fSPeter Avalos 	socklen_t fromlen, tolen;
43918de8d7fSPeter Avalos 
440664f4763Szrj 	if (ssh == NULL || ssh->state == NULL)
441e9778795SPeter Avalos 		return 0;
442e9778795SPeter Avalos 
443664f4763Szrj 	state = ssh->state;
444664f4763Szrj 	if (state->connection_in == -1 || state->connection_out == -1)
445664f4763Szrj 		return 0;
44618de8d7fSPeter Avalos 	/* filedescriptors in and out are the same, so it's a socket */
447e9778795SPeter Avalos 	if (state->connection_in == state->connection_out)
44818de8d7fSPeter Avalos 		return 1;
44918de8d7fSPeter Avalos 	fromlen = sizeof(from);
45018de8d7fSPeter Avalos 	memset(&from, 0, sizeof(from));
451e9778795SPeter Avalos 	if (getpeername(state->connection_in, (struct sockaddr *)&from,
4520cbfa66cSDaniel Fojt 	    &fromlen) == -1)
45318de8d7fSPeter Avalos 		return 0;
45418de8d7fSPeter Avalos 	tolen = sizeof(to);
45518de8d7fSPeter Avalos 	memset(&to, 0, sizeof(to));
456e9778795SPeter Avalos 	if (getpeername(state->connection_out, (struct sockaddr *)&to,
4570cbfa66cSDaniel Fojt 	    &tolen) == -1)
45818de8d7fSPeter Avalos 		return 0;
45918de8d7fSPeter Avalos 	if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
46018de8d7fSPeter Avalos 		return 0;
46118de8d7fSPeter Avalos 	if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
46218de8d7fSPeter Avalos 		return 0;
46318de8d7fSPeter Avalos 	return 1;
46418de8d7fSPeter Avalos }
46518de8d7fSPeter Avalos 
46618de8d7fSPeter Avalos void
ssh_packet_get_bytes(struct ssh * ssh,u_int64_t * ibytes,u_int64_t * obytes)467e9778795SPeter Avalos ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
46818de8d7fSPeter Avalos {
469e9778795SPeter Avalos 	if (ibytes)
470e9778795SPeter Avalos 		*ibytes = ssh->state->p_read.bytes;
471e9778795SPeter Avalos 	if (obytes)
472e9778795SPeter Avalos 		*obytes = ssh->state->p_send.bytes;
47318de8d7fSPeter Avalos }
47418de8d7fSPeter Avalos 
47518de8d7fSPeter Avalos int
ssh_packet_connection_af(struct ssh * ssh)476e9778795SPeter Avalos ssh_packet_connection_af(struct ssh *ssh)
47718de8d7fSPeter Avalos {
47850a69bb5SSascha Wildner 	return get_sock_af(ssh->state->connection_out);
47918de8d7fSPeter Avalos }
48018de8d7fSPeter Avalos 
48118de8d7fSPeter Avalos /* Sets the connection into non-blocking mode. */
48218de8d7fSPeter Avalos 
48318de8d7fSPeter Avalos void
ssh_packet_set_nonblocking(struct ssh * ssh)484e9778795SPeter Avalos ssh_packet_set_nonblocking(struct ssh *ssh)
48518de8d7fSPeter Avalos {
48618de8d7fSPeter Avalos 	/* Set the socket into non-blocking mode. */
487e9778795SPeter Avalos 	set_nonblock(ssh->state->connection_in);
48818de8d7fSPeter Avalos 
489e9778795SPeter Avalos 	if (ssh->state->connection_out != ssh->state->connection_in)
490e9778795SPeter Avalos 		set_nonblock(ssh->state->connection_out);
49118de8d7fSPeter Avalos }
49218de8d7fSPeter Avalos 
49318de8d7fSPeter Avalos /* Returns the socket used for reading. */
49418de8d7fSPeter Avalos 
49518de8d7fSPeter Avalos int
ssh_packet_get_connection_in(struct ssh * ssh)496e9778795SPeter Avalos ssh_packet_get_connection_in(struct ssh *ssh)
49718de8d7fSPeter Avalos {
498e9778795SPeter Avalos 	return ssh->state->connection_in;
49918de8d7fSPeter Avalos }
50018de8d7fSPeter Avalos 
50118de8d7fSPeter Avalos /* Returns the descriptor used for writing. */
50218de8d7fSPeter Avalos 
50318de8d7fSPeter Avalos int
ssh_packet_get_connection_out(struct ssh * ssh)504e9778795SPeter Avalos ssh_packet_get_connection_out(struct ssh *ssh)
50518de8d7fSPeter Avalos {
506e9778795SPeter Avalos 	return ssh->state->connection_out;
507e9778795SPeter Avalos }
508e9778795SPeter Avalos 
509e9778795SPeter Avalos /*
510e9778795SPeter Avalos  * Returns the IP-address of the remote host as a string.  The returned
511e9778795SPeter Avalos  * string must not be freed.
512e9778795SPeter Avalos  */
513e9778795SPeter Avalos 
514e9778795SPeter Avalos const char *
ssh_remote_ipaddr(struct ssh * ssh)515e9778795SPeter Avalos ssh_remote_ipaddr(struct ssh *ssh)
516e9778795SPeter Avalos {
517664f4763Szrj 	int sock;
518e9778795SPeter Avalos 
519e9778795SPeter Avalos 	/* Check whether we have cached the ipaddr. */
520e9778795SPeter Avalos 	if (ssh->remote_ipaddr == NULL) {
521e9778795SPeter Avalos 		if (ssh_packet_connection_is_on_socket(ssh)) {
522664f4763Szrj 			sock = ssh->state->connection_in;
523e9778795SPeter Avalos 			ssh->remote_ipaddr = get_peer_ipaddr(sock);
524e9778795SPeter Avalos 			ssh->remote_port = get_peer_port(sock);
525e9778795SPeter Avalos 			ssh->local_ipaddr = get_local_ipaddr(sock);
526e9778795SPeter Avalos 			ssh->local_port = get_local_port(sock);
527e9778795SPeter Avalos 		} else {
5280cbfa66cSDaniel Fojt 			ssh->remote_ipaddr = xstrdup("UNKNOWN");
529e9778795SPeter Avalos 			ssh->remote_port = 65535;
5300cbfa66cSDaniel Fojt 			ssh->local_ipaddr = xstrdup("UNKNOWN");
531e9778795SPeter Avalos 			ssh->local_port = 65535;
532e9778795SPeter Avalos 		}
533e9778795SPeter Avalos 	}
534e9778795SPeter Avalos 	return ssh->remote_ipaddr;
535e9778795SPeter Avalos }
536e9778795SPeter Avalos 
537*ba1276acSMatthew Dillon /*
538*ba1276acSMatthew Dillon  * Returns the remote DNS hostname as a string. The returned string must not
539*ba1276acSMatthew Dillon  * be freed. NB. this will usually trigger a DNS query. Return value is on
540*ba1276acSMatthew Dillon  * heap and no caching is performed.
541*ba1276acSMatthew Dillon  * This function does additional checks on the hostname to mitigate some
542*ba1276acSMatthew Dillon  * attacks based on conflation of hostnames and addresses and will
543*ba1276acSMatthew Dillon  * fall back to returning an address on error.
544*ba1276acSMatthew Dillon  */
545*ba1276acSMatthew Dillon 
546*ba1276acSMatthew Dillon char *
ssh_remote_hostname(struct ssh * ssh)547*ba1276acSMatthew Dillon ssh_remote_hostname(struct ssh *ssh)
548*ba1276acSMatthew Dillon {
549*ba1276acSMatthew Dillon 	struct sockaddr_storage from;
550*ba1276acSMatthew Dillon 	socklen_t fromlen;
551*ba1276acSMatthew Dillon 	struct addrinfo hints, *ai, *aitop;
552*ba1276acSMatthew Dillon 	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
553*ba1276acSMatthew Dillon 	const char *ntop = ssh_remote_ipaddr(ssh);
554*ba1276acSMatthew Dillon 
555*ba1276acSMatthew Dillon 	/* Get IP address of client. */
556*ba1276acSMatthew Dillon 	fromlen = sizeof(from);
557*ba1276acSMatthew Dillon 	memset(&from, 0, sizeof(from));
558*ba1276acSMatthew Dillon 	if (getpeername(ssh_packet_get_connection_in(ssh),
559*ba1276acSMatthew Dillon 	    (struct sockaddr *)&from, &fromlen) == -1) {
560*ba1276acSMatthew Dillon 		debug_f("getpeername failed: %.100s", strerror(errno));
561*ba1276acSMatthew Dillon 		return xstrdup(ntop);
562*ba1276acSMatthew Dillon 	}
563*ba1276acSMatthew Dillon 
564*ba1276acSMatthew Dillon 	ipv64_normalise_mapped(&from, &fromlen);
565*ba1276acSMatthew Dillon 	if (from.ss_family == AF_INET6)
566*ba1276acSMatthew Dillon 		fromlen = sizeof(struct sockaddr_in6);
567*ba1276acSMatthew Dillon 
568*ba1276acSMatthew Dillon 	debug3("trying to reverse map address %.100s.", ntop);
569*ba1276acSMatthew Dillon 	/* Map the IP address to a host name. */
570*ba1276acSMatthew Dillon 	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
571*ba1276acSMatthew Dillon 	    NULL, 0, NI_NAMEREQD) != 0) {
572*ba1276acSMatthew Dillon 		/* Host name not found.  Use ip address. */
573*ba1276acSMatthew Dillon 		return xstrdup(ntop);
574*ba1276acSMatthew Dillon 	}
575*ba1276acSMatthew Dillon 
576*ba1276acSMatthew Dillon 	/*
577*ba1276acSMatthew Dillon 	 * if reverse lookup result looks like a numeric hostname,
578*ba1276acSMatthew Dillon 	 * someone is trying to trick us by PTR record like following:
579*ba1276acSMatthew Dillon 	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
580*ba1276acSMatthew Dillon 	 */
581*ba1276acSMatthew Dillon 	memset(&hints, 0, sizeof(hints));
582*ba1276acSMatthew Dillon 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
583*ba1276acSMatthew Dillon 	hints.ai_flags = AI_NUMERICHOST;
584*ba1276acSMatthew Dillon 	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
585*ba1276acSMatthew Dillon 		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
586*ba1276acSMatthew Dillon 		    name, ntop);
587*ba1276acSMatthew Dillon 		freeaddrinfo(ai);
588*ba1276acSMatthew Dillon 		return xstrdup(ntop);
589*ba1276acSMatthew Dillon 	}
590*ba1276acSMatthew Dillon 
591*ba1276acSMatthew Dillon 	/* Names are stored in lowercase. */
592*ba1276acSMatthew Dillon 	lowercase(name);
593*ba1276acSMatthew Dillon 
594*ba1276acSMatthew Dillon 	/*
595*ba1276acSMatthew Dillon 	 * Map it back to an IP address and check that the given
596*ba1276acSMatthew Dillon 	 * address actually is an address of this host.  This is
597*ba1276acSMatthew Dillon 	 * necessary because anyone with access to a name server can
598*ba1276acSMatthew Dillon 	 * define arbitrary names for an IP address. Mapping from
599*ba1276acSMatthew Dillon 	 * name to IP address can be trusted better (but can still be
600*ba1276acSMatthew Dillon 	 * fooled if the intruder has access to the name server of
601*ba1276acSMatthew Dillon 	 * the domain).
602*ba1276acSMatthew Dillon 	 */
603*ba1276acSMatthew Dillon 	memset(&hints, 0, sizeof(hints));
604*ba1276acSMatthew Dillon 	hints.ai_family = from.ss_family;
605*ba1276acSMatthew Dillon 	hints.ai_socktype = SOCK_STREAM;
606*ba1276acSMatthew Dillon 	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
607*ba1276acSMatthew Dillon 		logit("reverse mapping checking getaddrinfo for %.700s "
608*ba1276acSMatthew Dillon 		    "[%s] failed.", name, ntop);
609*ba1276acSMatthew Dillon 		return xstrdup(ntop);
610*ba1276acSMatthew Dillon 	}
611*ba1276acSMatthew Dillon 	/* Look for the address from the list of addresses. */
612*ba1276acSMatthew Dillon 	for (ai = aitop; ai; ai = ai->ai_next) {
613*ba1276acSMatthew Dillon 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
614*ba1276acSMatthew Dillon 		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
615*ba1276acSMatthew Dillon 		    (strcmp(ntop, ntop2) == 0))
616*ba1276acSMatthew Dillon 				break;
617*ba1276acSMatthew Dillon 	}
618*ba1276acSMatthew Dillon 	freeaddrinfo(aitop);
619*ba1276acSMatthew Dillon 	/* If we reached the end of the list, the address was not there. */
620*ba1276acSMatthew Dillon 	if (ai == NULL) {
621*ba1276acSMatthew Dillon 		/* Address not found for the host name. */
622*ba1276acSMatthew Dillon 		logit("Address %.100s maps to %.600s, but this does not "
623*ba1276acSMatthew Dillon 		    "map back to the address.", ntop, name);
624*ba1276acSMatthew Dillon 		return xstrdup(ntop);
625*ba1276acSMatthew Dillon 	}
626*ba1276acSMatthew Dillon 	return xstrdup(name);
627*ba1276acSMatthew Dillon }
628*ba1276acSMatthew Dillon 
629e9778795SPeter Avalos /* Returns the port number of the remote host. */
630e9778795SPeter Avalos 
631e9778795SPeter Avalos int
ssh_remote_port(struct ssh * ssh)632e9778795SPeter Avalos ssh_remote_port(struct ssh *ssh)
633e9778795SPeter Avalos {
634e9778795SPeter Avalos 	(void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
635e9778795SPeter Avalos 	return ssh->remote_port;
636e9778795SPeter Avalos }
637e9778795SPeter Avalos 
638e9778795SPeter Avalos /*
639e9778795SPeter Avalos  * Returns the IP-address of the local host as a string.  The returned
640e9778795SPeter Avalos  * string must not be freed.
641e9778795SPeter Avalos  */
642e9778795SPeter Avalos 
643e9778795SPeter Avalos const char *
ssh_local_ipaddr(struct ssh * ssh)644e9778795SPeter Avalos ssh_local_ipaddr(struct ssh *ssh)
645e9778795SPeter Avalos {
646e9778795SPeter Avalos 	(void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
647e9778795SPeter Avalos 	return ssh->local_ipaddr;
648e9778795SPeter Avalos }
649e9778795SPeter Avalos 
650e9778795SPeter Avalos /* Returns the port number of the local host. */
651e9778795SPeter Avalos 
652e9778795SPeter Avalos int
ssh_local_port(struct ssh * ssh)653e9778795SPeter Avalos ssh_local_port(struct ssh *ssh)
654e9778795SPeter Avalos {
655e9778795SPeter Avalos 	(void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
656e9778795SPeter Avalos 	return ssh->local_port;
65718de8d7fSPeter Avalos }
65818de8d7fSPeter Avalos 
659664f4763Szrj /* Returns the routing domain of the input socket, or NULL if unavailable */
660664f4763Szrj const char *
ssh_packet_rdomain_in(struct ssh * ssh)661664f4763Szrj ssh_packet_rdomain_in(struct ssh *ssh)
662664f4763Szrj {
663664f4763Szrj 	if (ssh->rdomain_in != NULL)
664664f4763Szrj 		return ssh->rdomain_in;
665664f4763Szrj 	if (!ssh_packet_connection_is_on_socket(ssh))
666664f4763Szrj 		return NULL;
667664f4763Szrj 	ssh->rdomain_in = get_rdomain(ssh->state->connection_in);
668664f4763Szrj 	return ssh->rdomain_in;
669664f4763Szrj }
670664f4763Szrj 
67118de8d7fSPeter Avalos /* Closes the connection and clears and frees internal data structures. */
67218de8d7fSPeter Avalos 
673ce74bacaSMatthew Dillon static void
ssh_packet_close_internal(struct ssh * ssh,int do_close)674ce74bacaSMatthew Dillon ssh_packet_close_internal(struct ssh *ssh, int do_close)
67518de8d7fSPeter Avalos {
676e9778795SPeter Avalos 	struct session_state *state = ssh->state;
677e9778795SPeter Avalos 	u_int mode;
678e9778795SPeter Avalos 
679e9778795SPeter Avalos 	if (!state->initialized)
68018de8d7fSPeter Avalos 		return;
681e9778795SPeter Avalos 	state->initialized = 0;
682ce74bacaSMatthew Dillon 	if (do_close) {
683e9778795SPeter Avalos 		if (state->connection_in == state->connection_out) {
684e9778795SPeter Avalos 			close(state->connection_out);
68518de8d7fSPeter Avalos 		} else {
686e9778795SPeter Avalos 			close(state->connection_in);
687e9778795SPeter Avalos 			close(state->connection_out);
68818de8d7fSPeter Avalos 		}
689ce74bacaSMatthew Dillon 	}
690e9778795SPeter Avalos 	sshbuf_free(state->input);
691e9778795SPeter Avalos 	sshbuf_free(state->output);
692e9778795SPeter Avalos 	sshbuf_free(state->outgoing_packet);
693e9778795SPeter Avalos 	sshbuf_free(state->incoming_packet);
694ce74bacaSMatthew Dillon 	for (mode = 0; mode < MODE_MAX; mode++) {
695ce74bacaSMatthew Dillon 		kex_free_newkeys(state->newkeys[mode]);	/* current keys */
696ce74bacaSMatthew Dillon 		state->newkeys[mode] = NULL;
697ce74bacaSMatthew Dillon 		ssh_clear_newkeys(ssh, mode);		/* next keys */
698ce74bacaSMatthew Dillon 	}
6990cbfa66cSDaniel Fojt #ifdef WITH_ZLIB
700664f4763Szrj 	/* compression state is in shared mem, so we can only release it once */
701ce74bacaSMatthew Dillon 	if (do_close && state->compression_buffer) {
702e9778795SPeter Avalos 		sshbuf_free(state->compression_buffer);
703e9778795SPeter Avalos 		if (state->compression_out_started) {
704e9778795SPeter Avalos 			z_streamp stream = &state->compression_out_stream;
705e9778795SPeter Avalos 			debug("compress outgoing: "
706e9778795SPeter Avalos 			    "raw data %llu, compressed %llu, factor %.2f",
707e9778795SPeter Avalos 				(unsigned long long)stream->total_in,
708e9778795SPeter Avalos 				(unsigned long long)stream->total_out,
709e9778795SPeter Avalos 				stream->total_in == 0 ? 0.0 :
710e9778795SPeter Avalos 				(double) stream->total_out / stream->total_in);
711e9778795SPeter Avalos 			if (state->compression_out_failures == 0)
712e9778795SPeter Avalos 				deflateEnd(stream);
71318de8d7fSPeter Avalos 		}
714e9778795SPeter Avalos 		if (state->compression_in_started) {
715ce74bacaSMatthew Dillon 			z_streamp stream = &state->compression_in_stream;
716e9778795SPeter Avalos 			debug("compress incoming: "
717e9778795SPeter Avalos 			    "raw data %llu, compressed %llu, factor %.2f",
718e9778795SPeter Avalos 			    (unsigned long long)stream->total_out,
719e9778795SPeter Avalos 			    (unsigned long long)stream->total_in,
720e9778795SPeter Avalos 			    stream->total_out == 0 ? 0.0 :
721e9778795SPeter Avalos 			    (double) stream->total_in / stream->total_out);
722e9778795SPeter Avalos 			if (state->compression_in_failures == 0)
723e9778795SPeter Avalos 				inflateEnd(stream);
724e9778795SPeter Avalos 		}
725e9778795SPeter Avalos 	}
7260cbfa66cSDaniel Fojt #endif	/* WITH_ZLIB */
727ce74bacaSMatthew Dillon 	cipher_free(state->send_context);
728ce74bacaSMatthew Dillon 	cipher_free(state->receive_context);
729ce74bacaSMatthew Dillon 	state->send_context = state->receive_context = NULL;
730ce74bacaSMatthew Dillon 	if (do_close) {
731664f4763Szrj 		free(ssh->local_ipaddr);
732664f4763Szrj 		ssh->local_ipaddr = NULL;
733e9778795SPeter Avalos 		free(ssh->remote_ipaddr);
734e9778795SPeter Avalos 		ssh->remote_ipaddr = NULL;
735e9778795SPeter Avalos 		free(ssh->state);
736e9778795SPeter Avalos 		ssh->state = NULL;
73750a69bb5SSascha Wildner 		kex_free(ssh->kex);
73850a69bb5SSascha Wildner 		ssh->kex = NULL;
73918de8d7fSPeter Avalos 	}
740ce74bacaSMatthew Dillon }
741ce74bacaSMatthew Dillon 
742ce74bacaSMatthew Dillon void
ssh_packet_close(struct ssh * ssh)743ce74bacaSMatthew Dillon ssh_packet_close(struct ssh *ssh)
744ce74bacaSMatthew Dillon {
745ce74bacaSMatthew Dillon 	ssh_packet_close_internal(ssh, 1);
746ce74bacaSMatthew Dillon }
747ce74bacaSMatthew Dillon 
748ce74bacaSMatthew Dillon void
ssh_packet_clear_keys(struct ssh * ssh)749ce74bacaSMatthew Dillon ssh_packet_clear_keys(struct ssh *ssh)
750ce74bacaSMatthew Dillon {
751ce74bacaSMatthew Dillon 	ssh_packet_close_internal(ssh, 0);
752ce74bacaSMatthew Dillon }
75318de8d7fSPeter Avalos 
75418de8d7fSPeter Avalos /* Sets remote side protocol flags. */
75518de8d7fSPeter Avalos 
75618de8d7fSPeter Avalos void
ssh_packet_set_protocol_flags(struct ssh * ssh,u_int protocol_flags)757e9778795SPeter Avalos ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
75818de8d7fSPeter Avalos {
759e9778795SPeter Avalos 	ssh->state->remote_protocol_flags = protocol_flags;
76018de8d7fSPeter Avalos }
76118de8d7fSPeter Avalos 
76218de8d7fSPeter Avalos /* Returns the remote protocol flags set earlier by the above function. */
76318de8d7fSPeter Avalos 
76418de8d7fSPeter Avalos u_int
ssh_packet_get_protocol_flags(struct ssh * ssh)765e9778795SPeter Avalos ssh_packet_get_protocol_flags(struct ssh *ssh)
76618de8d7fSPeter Avalos {
767e9778795SPeter Avalos 	return ssh->state->remote_protocol_flags;
76818de8d7fSPeter Avalos }
76918de8d7fSPeter Avalos 
77018de8d7fSPeter Avalos /*
77118de8d7fSPeter Avalos  * Starts packet compression from the next packet on in both directions.
77218de8d7fSPeter Avalos  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
77318de8d7fSPeter Avalos  */
77418de8d7fSPeter Avalos 
775e9778795SPeter Avalos static int
ssh_packet_init_compression(struct ssh * ssh)776e9778795SPeter Avalos ssh_packet_init_compression(struct ssh *ssh)
77718de8d7fSPeter Avalos {
778e9778795SPeter Avalos 	if (!ssh->state->compression_buffer &&
779e9778795SPeter Avalos 	    ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
780e9778795SPeter Avalos 		return SSH_ERR_ALLOC_FAIL;
781e9778795SPeter Avalos 	return 0;
782e9778795SPeter Avalos }
783e9778795SPeter Avalos 
7840cbfa66cSDaniel Fojt #ifdef WITH_ZLIB
785e9778795SPeter Avalos static int
start_compression_out(struct ssh * ssh,int level)786e9778795SPeter Avalos start_compression_out(struct ssh *ssh, int level)
787e9778795SPeter Avalos {
788e9778795SPeter Avalos 	if (level < 1 || level > 9)
789e9778795SPeter Avalos 		return SSH_ERR_INVALID_ARGUMENT;
790e9778795SPeter Avalos 	debug("Enabling compression at level %d.", level);
791e9778795SPeter Avalos 	if (ssh->state->compression_out_started == 1)
792e9778795SPeter Avalos 		deflateEnd(&ssh->state->compression_out_stream);
793e9778795SPeter Avalos 	switch (deflateInit(&ssh->state->compression_out_stream, level)) {
794e9778795SPeter Avalos 	case Z_OK:
795e9778795SPeter Avalos 		ssh->state->compression_out_started = 1;
796e9778795SPeter Avalos 		break;
797e9778795SPeter Avalos 	case Z_MEM_ERROR:
798e9778795SPeter Avalos 		return SSH_ERR_ALLOC_FAIL;
799e9778795SPeter Avalos 	default:
800e9778795SPeter Avalos 		return SSH_ERR_INTERNAL_ERROR;
801e9778795SPeter Avalos 	}
802e9778795SPeter Avalos 	return 0;
803e9778795SPeter Avalos }
804e9778795SPeter Avalos 
805e9778795SPeter Avalos static int
start_compression_in(struct ssh * ssh)806e9778795SPeter Avalos start_compression_in(struct ssh *ssh)
807e9778795SPeter Avalos {
808e9778795SPeter Avalos 	if (ssh->state->compression_in_started == 1)
809e9778795SPeter Avalos 		inflateEnd(&ssh->state->compression_in_stream);
810e9778795SPeter Avalos 	switch (inflateInit(&ssh->state->compression_in_stream)) {
811e9778795SPeter Avalos 	case Z_OK:
812e9778795SPeter Avalos 		ssh->state->compression_in_started = 1;
813e9778795SPeter Avalos 		break;
814e9778795SPeter Avalos 	case Z_MEM_ERROR:
815e9778795SPeter Avalos 		return SSH_ERR_ALLOC_FAIL;
816e9778795SPeter Avalos 	default:
817e9778795SPeter Avalos 		return SSH_ERR_INTERNAL_ERROR;
818e9778795SPeter Avalos 	}
819e9778795SPeter Avalos 	return 0;
820e9778795SPeter Avalos }
821e9778795SPeter Avalos 
822e9778795SPeter Avalos /* XXX remove need for separate compression buffer */
823e9778795SPeter Avalos static int
compress_buffer(struct ssh * ssh,struct sshbuf * in,struct sshbuf * out)824e9778795SPeter Avalos compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
825e9778795SPeter Avalos {
826e9778795SPeter Avalos 	u_char buf[4096];
827e9778795SPeter Avalos 	int r, status;
828e9778795SPeter Avalos 
829e9778795SPeter Avalos 	if (ssh->state->compression_out_started != 1)
830e9778795SPeter Avalos 		return SSH_ERR_INTERNAL_ERROR;
831e9778795SPeter Avalos 
832e9778795SPeter Avalos 	/* This case is not handled below. */
833e9778795SPeter Avalos 	if (sshbuf_len(in) == 0)
834e9778795SPeter Avalos 		return 0;
835e9778795SPeter Avalos 
836e9778795SPeter Avalos 	/* Input is the contents of the input buffer. */
837e9778795SPeter Avalos 	if ((ssh->state->compression_out_stream.next_in =
838e9778795SPeter Avalos 	    sshbuf_mutable_ptr(in)) == NULL)
839e9778795SPeter Avalos 		return SSH_ERR_INTERNAL_ERROR;
840e9778795SPeter Avalos 	ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
841e9778795SPeter Avalos 
842e9778795SPeter Avalos 	/* Loop compressing until deflate() returns with avail_out != 0. */
843e9778795SPeter Avalos 	do {
844e9778795SPeter Avalos 		/* Set up fixed-size output buffer. */
845e9778795SPeter Avalos 		ssh->state->compression_out_stream.next_out = buf;
846e9778795SPeter Avalos 		ssh->state->compression_out_stream.avail_out = sizeof(buf);
847e9778795SPeter Avalos 
848e9778795SPeter Avalos 		/* Compress as much data into the buffer as possible. */
849e9778795SPeter Avalos 		status = deflate(&ssh->state->compression_out_stream,
850e9778795SPeter Avalos 		    Z_PARTIAL_FLUSH);
851e9778795SPeter Avalos 		switch (status) {
852e9778795SPeter Avalos 		case Z_MEM_ERROR:
853e9778795SPeter Avalos 			return SSH_ERR_ALLOC_FAIL;
854e9778795SPeter Avalos 		case Z_OK:
855e9778795SPeter Avalos 			/* Append compressed data to output_buffer. */
856e9778795SPeter Avalos 			if ((r = sshbuf_put(out, buf, sizeof(buf) -
857e9778795SPeter Avalos 			    ssh->state->compression_out_stream.avail_out)) != 0)
858e9778795SPeter Avalos 				return r;
859e9778795SPeter Avalos 			break;
860e9778795SPeter Avalos 		case Z_STREAM_ERROR:
861e9778795SPeter Avalos 		default:
862e9778795SPeter Avalos 			ssh->state->compression_out_failures++;
863e9778795SPeter Avalos 			return SSH_ERR_INVALID_FORMAT;
864e9778795SPeter Avalos 		}
865e9778795SPeter Avalos 	} while (ssh->state->compression_out_stream.avail_out == 0);
866e9778795SPeter Avalos 	return 0;
867e9778795SPeter Avalos }
868e9778795SPeter Avalos 
869e9778795SPeter Avalos static int
uncompress_buffer(struct ssh * ssh,struct sshbuf * in,struct sshbuf * out)870e9778795SPeter Avalos uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
871e9778795SPeter Avalos {
872e9778795SPeter Avalos 	u_char buf[4096];
873e9778795SPeter Avalos 	int r, status;
874e9778795SPeter Avalos 
875e9778795SPeter Avalos 	if (ssh->state->compression_in_started != 1)
876e9778795SPeter Avalos 		return SSH_ERR_INTERNAL_ERROR;
877e9778795SPeter Avalos 
878e9778795SPeter Avalos 	if ((ssh->state->compression_in_stream.next_in =
879e9778795SPeter Avalos 	    sshbuf_mutable_ptr(in)) == NULL)
880e9778795SPeter Avalos 		return SSH_ERR_INTERNAL_ERROR;
881e9778795SPeter Avalos 	ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
882e9778795SPeter Avalos 
883e9778795SPeter Avalos 	for (;;) {
884e9778795SPeter Avalos 		/* Set up fixed-size output buffer. */
885e9778795SPeter Avalos 		ssh->state->compression_in_stream.next_out = buf;
886e9778795SPeter Avalos 		ssh->state->compression_in_stream.avail_out = sizeof(buf);
887e9778795SPeter Avalos 
888e9778795SPeter Avalos 		status = inflate(&ssh->state->compression_in_stream,
889ee116499SAntonio Huete Jimenez 		    Z_SYNC_FLUSH);
890e9778795SPeter Avalos 		switch (status) {
891e9778795SPeter Avalos 		case Z_OK:
892e9778795SPeter Avalos 			if ((r = sshbuf_put(out, buf, sizeof(buf) -
893e9778795SPeter Avalos 			    ssh->state->compression_in_stream.avail_out)) != 0)
894e9778795SPeter Avalos 				return r;
895e9778795SPeter Avalos 			break;
896e9778795SPeter Avalos 		case Z_BUF_ERROR:
897e9778795SPeter Avalos 			/*
898e9778795SPeter Avalos 			 * Comments in zlib.h say that we should keep calling
899e9778795SPeter Avalos 			 * inflate() until we get an error.  This appears to
900e9778795SPeter Avalos 			 * be the error that we get.
901e9778795SPeter Avalos 			 */
902e9778795SPeter Avalos 			return 0;
903e9778795SPeter Avalos 		case Z_DATA_ERROR:
904e9778795SPeter Avalos 			return SSH_ERR_INVALID_FORMAT;
905e9778795SPeter Avalos 		case Z_MEM_ERROR:
906e9778795SPeter Avalos 			return SSH_ERR_ALLOC_FAIL;
907e9778795SPeter Avalos 		case Z_STREAM_ERROR:
908e9778795SPeter Avalos 		default:
909e9778795SPeter Avalos 			ssh->state->compression_in_failures++;
910e9778795SPeter Avalos 			return SSH_ERR_INTERNAL_ERROR;
911e9778795SPeter Avalos 		}
912e9778795SPeter Avalos 	}
913e9778795SPeter Avalos 	/* NOTREACHED */
914e9778795SPeter Avalos }
915e9778795SPeter Avalos 
9160cbfa66cSDaniel Fojt #else	/* WITH_ZLIB */
9170cbfa66cSDaniel Fojt 
9180cbfa66cSDaniel Fojt static int
start_compression_out(struct ssh * ssh,int level)9190cbfa66cSDaniel Fojt start_compression_out(struct ssh *ssh, int level)
9200cbfa66cSDaniel Fojt {
9210cbfa66cSDaniel Fojt 	return SSH_ERR_INTERNAL_ERROR;
9220cbfa66cSDaniel Fojt }
9230cbfa66cSDaniel Fojt 
9240cbfa66cSDaniel Fojt static int
start_compression_in(struct ssh * ssh)9250cbfa66cSDaniel Fojt start_compression_in(struct ssh *ssh)
9260cbfa66cSDaniel Fojt {
9270cbfa66cSDaniel Fojt 	return SSH_ERR_INTERNAL_ERROR;
9280cbfa66cSDaniel Fojt }
9290cbfa66cSDaniel Fojt 
9300cbfa66cSDaniel Fojt static int
compress_buffer(struct ssh * ssh,struct sshbuf * in,struct sshbuf * out)9310cbfa66cSDaniel Fojt compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
9320cbfa66cSDaniel Fojt {
9330cbfa66cSDaniel Fojt 	return SSH_ERR_INTERNAL_ERROR;
9340cbfa66cSDaniel Fojt }
9350cbfa66cSDaniel Fojt 
9360cbfa66cSDaniel Fojt static int
uncompress_buffer(struct ssh * ssh,struct sshbuf * in,struct sshbuf * out)9370cbfa66cSDaniel Fojt uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
9380cbfa66cSDaniel Fojt {
9390cbfa66cSDaniel Fojt 	return SSH_ERR_INTERNAL_ERROR;
9400cbfa66cSDaniel Fojt }
9410cbfa66cSDaniel Fojt #endif	/* WITH_ZLIB */
9420cbfa66cSDaniel Fojt 
94318de8d7fSPeter Avalos void
ssh_clear_newkeys(struct ssh * ssh,int mode)944ce74bacaSMatthew Dillon ssh_clear_newkeys(struct ssh *ssh, int mode)
94518de8d7fSPeter Avalos {
946ce74bacaSMatthew Dillon 	if (ssh->kex && ssh->kex->newkeys[mode]) {
947ce74bacaSMatthew Dillon 		kex_free_newkeys(ssh->kex->newkeys[mode]);
948ce74bacaSMatthew Dillon 		ssh->kex->newkeys[mode] = NULL;
94918de8d7fSPeter Avalos 	}
95018de8d7fSPeter Avalos }
95118de8d7fSPeter Avalos 
952e9778795SPeter Avalos int
ssh_set_newkeys(struct ssh * ssh,int mode)953e9778795SPeter Avalos ssh_set_newkeys(struct ssh *ssh, int mode)
95418de8d7fSPeter Avalos {
955e9778795SPeter Avalos 	struct session_state *state = ssh->state;
956e9778795SPeter Avalos 	struct sshenc *enc;
957e9778795SPeter Avalos 	struct sshmac *mac;
958e9778795SPeter Avalos 	struct sshcomp *comp;
959ce74bacaSMatthew Dillon 	struct sshcipher_ctx **ccp;
960ce74bacaSMatthew Dillon 	struct packet_state *ps;
96118de8d7fSPeter Avalos 	u_int64_t *max_blocks;
962e9778795SPeter Avalos 	const char *wmsg;
96336e94dc5SPeter Avalos 	int r, crypt_type;
964664f4763Szrj 	const char *dir = mode == MODE_OUT ? "out" : "in";
96518de8d7fSPeter Avalos 
966ee116499SAntonio Huete Jimenez 	debug2_f("mode %d", mode);
96718de8d7fSPeter Avalos 
96818de8d7fSPeter Avalos 	if (mode == MODE_OUT) {
969ce74bacaSMatthew Dillon 		ccp = &state->send_context;
97018de8d7fSPeter Avalos 		crypt_type = CIPHER_ENCRYPT;
971ce74bacaSMatthew Dillon 		ps = &state->p_send;
972e9778795SPeter Avalos 		max_blocks = &state->max_blocks_out;
97318de8d7fSPeter Avalos 	} else {
974ce74bacaSMatthew Dillon 		ccp = &state->receive_context;
97518de8d7fSPeter Avalos 		crypt_type = CIPHER_DECRYPT;
976ce74bacaSMatthew Dillon 		ps = &state->p_read;
977e9778795SPeter Avalos 		max_blocks = &state->max_blocks_in;
97818de8d7fSPeter Avalos 	}
979e9778795SPeter Avalos 	if (state->newkeys[mode] != NULL) {
98050a69bb5SSascha Wildner 		debug_f("rekeying %s, input %llu bytes %llu blocks, "
98150a69bb5SSascha Wildner 		    "output %llu bytes %llu blocks", dir,
982e9778795SPeter Avalos 		    (unsigned long long)state->p_read.bytes,
983e9778795SPeter Avalos 		    (unsigned long long)state->p_read.blocks,
984e9778795SPeter Avalos 		    (unsigned long long)state->p_send.bytes,
985e9778795SPeter Avalos 		    (unsigned long long)state->p_send.blocks);
986ce74bacaSMatthew Dillon 		kex_free_newkeys(state->newkeys[mode]);
987ce74bacaSMatthew Dillon 		state->newkeys[mode] = NULL;
98818de8d7fSPeter Avalos 	}
989ce74bacaSMatthew Dillon 	/* note that both bytes and the seqnr are not reset */
990ce74bacaSMatthew Dillon 	ps->packets = ps->blocks = 0;
991e9778795SPeter Avalos 	/* move newkeys from kex to state */
992e9778795SPeter Avalos 	if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
993e9778795SPeter Avalos 		return SSH_ERR_INTERNAL_ERROR;
994e9778795SPeter Avalos 	ssh->kex->newkeys[mode] = NULL;
995e9778795SPeter Avalos 	enc  = &state->newkeys[mode]->enc;
996e9778795SPeter Avalos 	mac  = &state->newkeys[mode]->mac;
997e9778795SPeter Avalos 	comp = &state->newkeys[mode]->comp;
998e9778795SPeter Avalos 	if (cipher_authlen(enc->cipher) == 0) {
999e9778795SPeter Avalos 		if ((r = mac_init(mac)) != 0)
1000e9778795SPeter Avalos 			return r;
1001e9778795SPeter Avalos 	}
100218de8d7fSPeter Avalos 	mac->enabled = 1;
1003ee116499SAntonio Huete Jimenez 	DBG(debug_f("cipher_init: %s", dir));
1004664f4763Szrj 	cipher_free(*ccp);
1005664f4763Szrj 	*ccp = NULL;
1006ce74bacaSMatthew Dillon 	if ((r = cipher_init(ccp, enc->cipher, enc->key, enc->key_len,
100736e94dc5SPeter Avalos 	    enc->iv, enc->iv_len, crypt_type)) != 0)
1008e9778795SPeter Avalos 		return r;
1009e9778795SPeter Avalos 	if (!state->cipher_warning_done &&
1010ce74bacaSMatthew Dillon 	    (wmsg = cipher_warning_message(*ccp)) != NULL) {
1011e9778795SPeter Avalos 		error("Warning: %s", wmsg);
1012e9778795SPeter Avalos 		state->cipher_warning_done = 1;
1013e9778795SPeter Avalos 	}
101418de8d7fSPeter Avalos 	/* Deleting the keys does not gain extra security */
101536e94dc5SPeter Avalos 	/* explicit_bzero(enc->iv,  enc->block_size);
101636e94dc5SPeter Avalos 	   explicit_bzero(enc->key, enc->key_len);
101736e94dc5SPeter Avalos 	   explicit_bzero(mac->key, mac->key_len); */
101818de8d7fSPeter Avalos 	if ((comp->type == COMP_ZLIB ||
101940c002afSPeter Avalos 	    (comp->type == COMP_DELAYED &&
1020e9778795SPeter Avalos 	    state->after_authentication)) && comp->enabled == 0) {
1021e9778795SPeter Avalos 		if ((r = ssh_packet_init_compression(ssh)) < 0)
1022e9778795SPeter Avalos 			return r;
1023e9778795SPeter Avalos 		if (mode == MODE_OUT) {
1024e9778795SPeter Avalos 			if ((r = start_compression_out(ssh, 6)) != 0)
1025e9778795SPeter Avalos 				return r;
1026e9778795SPeter Avalos 		} else {
1027e9778795SPeter Avalos 			if ((r = start_compression_in(ssh)) != 0)
1028e9778795SPeter Avalos 				return r;
1029e9778795SPeter Avalos 		}
103018de8d7fSPeter Avalos 		comp->enabled = 1;
103118de8d7fSPeter Avalos 	}
103218de8d7fSPeter Avalos 	/*
103318de8d7fSPeter Avalos 	 * The 2^(blocksize*2) limit is too expensive for 3DES,
1034ce74bacaSMatthew Dillon 	 * so enforce a 1GB limit for small blocksizes.
1035ce74bacaSMatthew Dillon 	 * See RFC4344 section 3.2.
103618de8d7fSPeter Avalos 	 */
103718de8d7fSPeter Avalos 	if (enc->block_size >= 16)
103818de8d7fSPeter Avalos 		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
103918de8d7fSPeter Avalos 	else
104018de8d7fSPeter Avalos 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1041e9778795SPeter Avalos 	if (state->rekey_limit)
1042ce74bacaSMatthew Dillon 		*max_blocks = MINIMUM(*max_blocks,
1043e9778795SPeter Avalos 		    state->rekey_limit / enc->block_size);
1044664f4763Szrj 	debug("rekey %s after %llu blocks", dir,
1045664f4763Szrj 	    (unsigned long long)*max_blocks);
1046e9778795SPeter Avalos 	return 0;
1047e9778795SPeter Avalos }
1048e9778795SPeter Avalos 
1049e9778795SPeter Avalos #define MAX_PACKETS	(1U<<31)
1050e9778795SPeter Avalos static int
ssh_packet_need_rekeying(struct ssh * ssh,u_int outbound_packet_len)1051e9778795SPeter Avalos ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
1052e9778795SPeter Avalos {
1053e9778795SPeter Avalos 	struct session_state *state = ssh->state;
1054e9778795SPeter Avalos 	u_int32_t out_blocks;
1055e9778795SPeter Avalos 
1056e9778795SPeter Avalos 	/* XXX client can't cope with rekeying pre-auth */
1057e9778795SPeter Avalos 	if (!state->after_authentication)
1058e9778795SPeter Avalos 		return 0;
1059e9778795SPeter Avalos 
1060e9778795SPeter Avalos 	/* Haven't keyed yet or KEX in progress. */
1061664f4763Szrj 	if (ssh_packet_is_rekeying(ssh))
1062e9778795SPeter Avalos 		return 0;
1063e9778795SPeter Avalos 
1064e9778795SPeter Avalos 	/* Peer can't rekey */
1065e9778795SPeter Avalos 	if (ssh->compat & SSH_BUG_NOREKEY)
1066e9778795SPeter Avalos 		return 0;
1067e9778795SPeter Avalos 
1068e9778795SPeter Avalos 	/*
1069e9778795SPeter Avalos 	 * Permit one packet in or out per rekey - this allows us to
1070e9778795SPeter Avalos 	 * make progress when rekey limits are very small.
1071e9778795SPeter Avalos 	 */
1072e9778795SPeter Avalos 	if (state->p_send.packets == 0 && state->p_read.packets == 0)
1073e9778795SPeter Avalos 		return 0;
1074e9778795SPeter Avalos 
1075e9778795SPeter Avalos 	/* Time-based rekeying */
1076e9778795SPeter Avalos 	if (state->rekey_interval != 0 &&
1077ce74bacaSMatthew Dillon 	    (int64_t)state->rekey_time + state->rekey_interval <= monotime())
1078e9778795SPeter Avalos 		return 1;
1079e9778795SPeter Avalos 
1080ce74bacaSMatthew Dillon 	/*
1081ce74bacaSMatthew Dillon 	 * Always rekey when MAX_PACKETS sent in either direction
1082ce74bacaSMatthew Dillon 	 * As per RFC4344 section 3.1 we do this after 2^31 packets.
1083ce74bacaSMatthew Dillon 	 */
1084e9778795SPeter Avalos 	if (state->p_send.packets > MAX_PACKETS ||
1085e9778795SPeter Avalos 	    state->p_read.packets > MAX_PACKETS)
1086e9778795SPeter Avalos 		return 1;
1087e9778795SPeter Avalos 
1088664f4763Szrj 	/* Rekey after (cipher-specific) maximum blocks */
1089ce74bacaSMatthew Dillon 	out_blocks = ROUNDUP(outbound_packet_len,
1090e9778795SPeter Avalos 	    state->newkeys[MODE_OUT]->enc.block_size);
1091e9778795SPeter Avalos 	return (state->max_blocks_out &&
1092e9778795SPeter Avalos 	    (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
1093e9778795SPeter Avalos 	    (state->max_blocks_in &&
1094e9778795SPeter Avalos 	    (state->p_read.blocks > state->max_blocks_in));
109518de8d7fSPeter Avalos }
109618de8d7fSPeter Avalos 
109750a69bb5SSascha Wildner int
ssh_packet_check_rekey(struct ssh * ssh)109850a69bb5SSascha Wildner ssh_packet_check_rekey(struct ssh *ssh)
109950a69bb5SSascha Wildner {
110050a69bb5SSascha Wildner 	if (!ssh_packet_need_rekeying(ssh, 0))
110150a69bb5SSascha Wildner 		return 0;
110250a69bb5SSascha Wildner 	debug3_f("rekex triggered");
110350a69bb5SSascha Wildner 	return kex_start_rekex(ssh);
110450a69bb5SSascha Wildner }
110550a69bb5SSascha Wildner 
110618de8d7fSPeter Avalos /*
110718de8d7fSPeter Avalos  * Delayed compression for SSH2 is enabled after authentication:
110818de8d7fSPeter Avalos  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
110918de8d7fSPeter Avalos  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
111018de8d7fSPeter Avalos  */
1111e9778795SPeter Avalos static int
ssh_packet_enable_delayed_compress(struct ssh * ssh)1112e9778795SPeter Avalos ssh_packet_enable_delayed_compress(struct ssh *ssh)
111318de8d7fSPeter Avalos {
1114e9778795SPeter Avalos 	struct session_state *state = ssh->state;
1115e9778795SPeter Avalos 	struct sshcomp *comp = NULL;
1116e9778795SPeter Avalos 	int r, mode;
111718de8d7fSPeter Avalos 
111818de8d7fSPeter Avalos 	/*
111918de8d7fSPeter Avalos 	 * Remember that we are past the authentication step, so rekeying
112018de8d7fSPeter Avalos 	 * with COMP_DELAYED will turn on compression immediately.
112118de8d7fSPeter Avalos 	 */
1122e9778795SPeter Avalos 	state->after_authentication = 1;
112318de8d7fSPeter Avalos 	for (mode = 0; mode < MODE_MAX; mode++) {
112418de8d7fSPeter Avalos 		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1125e9778795SPeter Avalos 		if (state->newkeys[mode] == NULL)
112618de8d7fSPeter Avalos 			continue;
1127e9778795SPeter Avalos 		comp = &state->newkeys[mode]->comp;
112818de8d7fSPeter Avalos 		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1129e9778795SPeter Avalos 			if ((r = ssh_packet_init_compression(ssh)) != 0)
1130e9778795SPeter Avalos 				return r;
1131e9778795SPeter Avalos 			if (mode == MODE_OUT) {
1132e9778795SPeter Avalos 				if ((r = start_compression_out(ssh, 6)) != 0)
1133e9778795SPeter Avalos 					return r;
1134e9778795SPeter Avalos 			} else {
1135e9778795SPeter Avalos 				if ((r = start_compression_in(ssh)) != 0)
1136e9778795SPeter Avalos 					return r;
1137e9778795SPeter Avalos 			}
113818de8d7fSPeter Avalos 			comp->enabled = 1;
113918de8d7fSPeter Avalos 		}
114018de8d7fSPeter Avalos 	}
1141e9778795SPeter Avalos 	return 0;
1142e9778795SPeter Avalos }
1143e9778795SPeter Avalos 
1144e9778795SPeter Avalos /* Used to mute debug logging for noisy packet types */
1145ce74bacaSMatthew Dillon int
ssh_packet_log_type(u_char type)1146e9778795SPeter Avalos ssh_packet_log_type(u_char type)
1147e9778795SPeter Avalos {
1148e9778795SPeter Avalos 	switch (type) {
1149*ba1276acSMatthew Dillon 	case SSH2_MSG_PING:
1150*ba1276acSMatthew Dillon 	case SSH2_MSG_PONG:
1151e9778795SPeter Avalos 	case SSH2_MSG_CHANNEL_DATA:
1152e9778795SPeter Avalos 	case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1153e9778795SPeter Avalos 	case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1154e9778795SPeter Avalos 		return 0;
1155e9778795SPeter Avalos 	default:
1156e9778795SPeter Avalos 		return 1;
1157e9778795SPeter Avalos 	}
115818de8d7fSPeter Avalos }
115918de8d7fSPeter Avalos 
116018de8d7fSPeter Avalos /*
116118de8d7fSPeter Avalos  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
116218de8d7fSPeter Avalos  */
1163e9778795SPeter Avalos int
ssh_packet_send2_wrapped(struct ssh * ssh)1164e9778795SPeter Avalos ssh_packet_send2_wrapped(struct ssh *ssh)
116518de8d7fSPeter Avalos {
1166e9778795SPeter Avalos 	struct session_state *state = ssh->state;
1167e9778795SPeter Avalos 	u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1168e9778795SPeter Avalos 	u_char tmp, padlen, pad = 0;
1169e9778795SPeter Avalos 	u_int authlen = 0, aadlen = 0;
1170e9778795SPeter Avalos 	u_int len;
1171e9778795SPeter Avalos 	struct sshenc *enc   = NULL;
1172e9778795SPeter Avalos 	struct sshmac *mac   = NULL;
1173e9778795SPeter Avalos 	struct sshcomp *comp = NULL;
1174e9778795SPeter Avalos 	int r, block_size;
117518de8d7fSPeter Avalos 
1176e9778795SPeter Avalos 	if (state->newkeys[MODE_OUT] != NULL) {
1177e9778795SPeter Avalos 		enc  = &state->newkeys[MODE_OUT]->enc;
1178e9778795SPeter Avalos 		mac  = &state->newkeys[MODE_OUT]->mac;
1179e9778795SPeter Avalos 		comp = &state->newkeys[MODE_OUT]->comp;
118036e94dc5SPeter Avalos 		/* disable mac for authenticated encryption */
118136e94dc5SPeter Avalos 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
118236e94dc5SPeter Avalos 			mac = NULL;
118318de8d7fSPeter Avalos 	}
118418de8d7fSPeter Avalos 	block_size = enc ? enc->block_size : 8;
118536e94dc5SPeter Avalos 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
118618de8d7fSPeter Avalos 
1187e9778795SPeter Avalos 	type = (sshbuf_ptr(state->outgoing_packet))[5];
1188e9778795SPeter Avalos 	if (ssh_packet_log_type(type))
1189e9778795SPeter Avalos 		debug3("send packet: type %u", type);
119018de8d7fSPeter Avalos #ifdef PACKET_DEBUG
119118de8d7fSPeter Avalos 	fprintf(stderr, "plain:     ");
1192e9778795SPeter Avalos 	sshbuf_dump(state->outgoing_packet, stderr);
119318de8d7fSPeter Avalos #endif
119418de8d7fSPeter Avalos 
119518de8d7fSPeter Avalos 	if (comp && comp->enabled) {
1196e9778795SPeter Avalos 		len = sshbuf_len(state->outgoing_packet);
119718de8d7fSPeter Avalos 		/* skip header, compress only payload */
1198e9778795SPeter Avalos 		if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1199e9778795SPeter Avalos 			goto out;
1200e9778795SPeter Avalos 		sshbuf_reset(state->compression_buffer);
1201e9778795SPeter Avalos 		if ((r = compress_buffer(ssh, state->outgoing_packet,
1202e9778795SPeter Avalos 		    state->compression_buffer)) != 0)
1203e9778795SPeter Avalos 			goto out;
1204e9778795SPeter Avalos 		sshbuf_reset(state->outgoing_packet);
1205e9778795SPeter Avalos 		if ((r = sshbuf_put(state->outgoing_packet,
1206e9778795SPeter Avalos 		    "\0\0\0\0\0", 5)) != 0 ||
1207e9778795SPeter Avalos 		    (r = sshbuf_putb(state->outgoing_packet,
1208e9778795SPeter Avalos 		    state->compression_buffer)) != 0)
1209e9778795SPeter Avalos 			goto out;
1210e9778795SPeter Avalos 		DBG(debug("compression: raw %d compressed %zd", len,
1211e9778795SPeter Avalos 		    sshbuf_len(state->outgoing_packet)));
121218de8d7fSPeter Avalos 	}
121318de8d7fSPeter Avalos 
121418de8d7fSPeter Avalos 	/* sizeof (packet_len + pad_len + payload) */
1215e9778795SPeter Avalos 	len = sshbuf_len(state->outgoing_packet);
121618de8d7fSPeter Avalos 
121718de8d7fSPeter Avalos 	/*
121818de8d7fSPeter Avalos 	 * calc size of padding, alloc space, get random data,
121918de8d7fSPeter Avalos 	 * minimum padding is 4 bytes
122018de8d7fSPeter Avalos 	 */
122136e94dc5SPeter Avalos 	len -= aadlen; /* packet length is not encrypted for EtM modes */
122218de8d7fSPeter Avalos 	padlen = block_size - (len % block_size);
122318de8d7fSPeter Avalos 	if (padlen < 4)
122418de8d7fSPeter Avalos 		padlen += block_size;
1225e9778795SPeter Avalos 	if (state->extra_pad) {
1226e9778795SPeter Avalos 		tmp = state->extra_pad;
1227e9778795SPeter Avalos 		state->extra_pad =
1228ce74bacaSMatthew Dillon 		    ROUNDUP(state->extra_pad, block_size);
1229e9778795SPeter Avalos 		/* check if roundup overflowed */
1230e9778795SPeter Avalos 		if (state->extra_pad < tmp)
1231e9778795SPeter Avalos 			return SSH_ERR_INVALID_ARGUMENT;
1232e9778795SPeter Avalos 		tmp = (len + padlen) % state->extra_pad;
1233e9778795SPeter Avalos 		/* Check whether pad calculation below will underflow */
1234e9778795SPeter Avalos 		if (tmp > state->extra_pad)
1235e9778795SPeter Avalos 			return SSH_ERR_INVALID_ARGUMENT;
1236e9778795SPeter Avalos 		pad = state->extra_pad - tmp;
123750a69bb5SSascha Wildner 		DBG(debug3_f("adding %d (len %d padlen %d extra_pad %d)",
123850a69bb5SSascha Wildner 		    pad, len, padlen, state->extra_pad));
1239e9778795SPeter Avalos 		tmp = padlen;
124018de8d7fSPeter Avalos 		padlen += pad;
1241e9778795SPeter Avalos 		/* Check whether padlen calculation overflowed */
1242e9778795SPeter Avalos 		if (padlen < tmp)
1243e9778795SPeter Avalos 			return SSH_ERR_INVALID_ARGUMENT; /* overflow */
1244e9778795SPeter Avalos 		state->extra_pad = 0;
124518de8d7fSPeter Avalos 	}
1246e9778795SPeter Avalos 	if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1247e9778795SPeter Avalos 		goto out;
1248ce74bacaSMatthew Dillon 	if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
124918de8d7fSPeter Avalos 		/* random padding */
1250e9778795SPeter Avalos 		arc4random_buf(cp, padlen);
125118de8d7fSPeter Avalos 	} else {
125218de8d7fSPeter Avalos 		/* clear padding */
125336e94dc5SPeter Avalos 		explicit_bzero(cp, padlen);
125418de8d7fSPeter Avalos 	}
125536e94dc5SPeter Avalos 	/* sizeof (packet_len + pad_len + payload + padding) */
1256e9778795SPeter Avalos 	len = sshbuf_len(state->outgoing_packet);
1257e9778795SPeter Avalos 	cp = sshbuf_mutable_ptr(state->outgoing_packet);
1258e9778795SPeter Avalos 	if (cp == NULL) {
1259e9778795SPeter Avalos 		r = SSH_ERR_INTERNAL_ERROR;
1260e9778795SPeter Avalos 		goto out;
1261e9778795SPeter Avalos 	}
126236e94dc5SPeter Avalos 	/* packet_length includes payload, padding and padding length field */
1263e9778795SPeter Avalos 	POKE_U32(cp, len - 4);
126418de8d7fSPeter Avalos 	cp[4] = padlen;
126536e94dc5SPeter Avalos 	DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
126636e94dc5SPeter Avalos 	    len, padlen, aadlen));
126718de8d7fSPeter Avalos 
126818de8d7fSPeter Avalos 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
126936e94dc5SPeter Avalos 	if (mac && mac->enabled && !mac->etm) {
1270e9778795SPeter Avalos 		if ((r = mac_compute(mac, state->p_send.seqnr,
1271e9778795SPeter Avalos 		    sshbuf_ptr(state->outgoing_packet), len,
1272e9778795SPeter Avalos 		    macbuf, sizeof(macbuf))) != 0)
1273e9778795SPeter Avalos 			goto out;
1274e9778795SPeter Avalos 		DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
127518de8d7fSPeter Avalos 	}
127618de8d7fSPeter Avalos 	/* encrypt packet and append to output buffer. */
1277e9778795SPeter Avalos 	if ((r = sshbuf_reserve(state->output,
1278e9778795SPeter Avalos 	    sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1279e9778795SPeter Avalos 		goto out;
1280ce74bacaSMatthew Dillon 	if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
1281e9778795SPeter Avalos 	    sshbuf_ptr(state->outgoing_packet),
1282e9778795SPeter Avalos 	    len - aadlen, aadlen, authlen)) != 0)
1283e9778795SPeter Avalos 		goto out;
128418de8d7fSPeter Avalos 	/* append unencrypted MAC */
128536e94dc5SPeter Avalos 	if (mac && mac->enabled) {
128636e94dc5SPeter Avalos 		if (mac->etm) {
128736e94dc5SPeter Avalos 			/* EtM: compute mac over aadlen + cipher text */
1288e9778795SPeter Avalos 			if ((r = mac_compute(mac, state->p_send.seqnr,
1289e9778795SPeter Avalos 			    cp, len, macbuf, sizeof(macbuf))) != 0)
1290e9778795SPeter Avalos 				goto out;
129136e94dc5SPeter Avalos 			DBG(debug("done calc MAC(EtM) out #%d",
1292e9778795SPeter Avalos 			    state->p_send.seqnr));
129336e94dc5SPeter Avalos 		}
1294e9778795SPeter Avalos 		if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1295e9778795SPeter Avalos 			goto out;
129636e94dc5SPeter Avalos 	}
129718de8d7fSPeter Avalos #ifdef PACKET_DEBUG
129818de8d7fSPeter Avalos 	fprintf(stderr, "encrypted: ");
1299e9778795SPeter Avalos 	sshbuf_dump(state->output, stderr);
130018de8d7fSPeter Avalos #endif
130118de8d7fSPeter Avalos 	/* increment sequence number for outgoing packets */
1302*ba1276acSMatthew Dillon 	if (++state->p_send.seqnr == 0) {
1303*ba1276acSMatthew Dillon 		if ((ssh->kex->flags & KEX_INITIAL) != 0) {
1304*ba1276acSMatthew Dillon 			ssh_packet_disconnect(ssh, "outgoing sequence number "
1305*ba1276acSMatthew Dillon 			    "wrapped during initial key exchange");
1306*ba1276acSMatthew Dillon 		}
130718de8d7fSPeter Avalos 		logit("outgoing seqnr wraps around");
1308*ba1276acSMatthew Dillon 	}
1309e9778795SPeter Avalos 	if (++state->p_send.packets == 0)
1310e9778795SPeter Avalos 		if (!(ssh->compat & SSH_BUG_NOREKEY))
1311e9778795SPeter Avalos 			return SSH_ERR_NEED_REKEY;
1312e9778795SPeter Avalos 	state->p_send.blocks += len / block_size;
1313e9778795SPeter Avalos 	state->p_send.bytes += len;
1314e9778795SPeter Avalos 	sshbuf_reset(state->outgoing_packet);
131518de8d7fSPeter Avalos 
1316*ba1276acSMatthew Dillon 	if (type == SSH2_MSG_NEWKEYS && ssh->kex->kex_strict) {
1317*ba1276acSMatthew Dillon 		debug_f("resetting send seqnr %u", state->p_send.seqnr);
1318*ba1276acSMatthew Dillon 		state->p_send.seqnr = 0;
1319*ba1276acSMatthew Dillon 	}
1320*ba1276acSMatthew Dillon 
132118de8d7fSPeter Avalos 	if (type == SSH2_MSG_NEWKEYS)
1322e9778795SPeter Avalos 		r = ssh_set_newkeys(ssh, MODE_OUT);
1323e9778795SPeter Avalos 	else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1324e9778795SPeter Avalos 		r = ssh_packet_enable_delayed_compress(ssh);
1325e9778795SPeter Avalos 	else
1326e9778795SPeter Avalos 		r = 0;
1327e9778795SPeter Avalos  out:
1328e9778795SPeter Avalos 	return r;
132918de8d7fSPeter Avalos }
133018de8d7fSPeter Avalos 
1331e9778795SPeter Avalos /* returns non-zero if the specified packet type is usec by KEX */
1332e9778795SPeter Avalos static int
ssh_packet_type_is_kex(u_char type)1333e9778795SPeter Avalos ssh_packet_type_is_kex(u_char type)
133418de8d7fSPeter Avalos {
1335e9778795SPeter Avalos 	return
1336e9778795SPeter Avalos 	    type >= SSH2_MSG_TRANSPORT_MIN &&
1337e9778795SPeter Avalos 	    type <= SSH2_MSG_TRANSPORT_MAX &&
1338e9778795SPeter Avalos 	    type != SSH2_MSG_SERVICE_REQUEST &&
1339e9778795SPeter Avalos 	    type != SSH2_MSG_SERVICE_ACCEPT &&
1340e9778795SPeter Avalos 	    type != SSH2_MSG_EXT_INFO;
134118de8d7fSPeter Avalos }
1342e9778795SPeter Avalos 
1343e9778795SPeter Avalos int
ssh_packet_send2(struct ssh * ssh)1344e9778795SPeter Avalos ssh_packet_send2(struct ssh *ssh)
1345e9778795SPeter Avalos {
1346e9778795SPeter Avalos 	struct session_state *state = ssh->state;
1347e9778795SPeter Avalos 	struct packet *p;
1348e9778795SPeter Avalos 	u_char type;
1349e9778795SPeter Avalos 	int r, need_rekey;
1350e9778795SPeter Avalos 
1351e9778795SPeter Avalos 	if (sshbuf_len(state->outgoing_packet) < 6)
1352e9778795SPeter Avalos 		return SSH_ERR_INTERNAL_ERROR;
1353e9778795SPeter Avalos 	type = sshbuf_ptr(state->outgoing_packet)[5];
1354e9778795SPeter Avalos 	need_rekey = !ssh_packet_type_is_kex(type) &&
1355e9778795SPeter Avalos 	    ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1356e9778795SPeter Avalos 
1357e9778795SPeter Avalos 	/*
1358e9778795SPeter Avalos 	 * During rekeying we can only send key exchange messages.
1359e9778795SPeter Avalos 	 * Queue everything else.
1360e9778795SPeter Avalos 	 */
1361e9778795SPeter Avalos 	if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
1362e9778795SPeter Avalos 		if (need_rekey)
136350a69bb5SSascha Wildner 			debug3_f("rekex triggered");
1364e9778795SPeter Avalos 		debug("enqueue packet: %u", type);
1365e9778795SPeter Avalos 		p = calloc(1, sizeof(*p));
1366e9778795SPeter Avalos 		if (p == NULL)
1367e9778795SPeter Avalos 			return SSH_ERR_ALLOC_FAIL;
1368e9778795SPeter Avalos 		p->type = type;
1369e9778795SPeter Avalos 		p->payload = state->outgoing_packet;
1370e9778795SPeter Avalos 		TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1371e9778795SPeter Avalos 		state->outgoing_packet = sshbuf_new();
1372e9778795SPeter Avalos 		if (state->outgoing_packet == NULL)
1373e9778795SPeter Avalos 			return SSH_ERR_ALLOC_FAIL;
1374e9778795SPeter Avalos 		if (need_rekey) {
1375e9778795SPeter Avalos 			/*
1376e9778795SPeter Avalos 			 * This packet triggered a rekey, so send the
1377e9778795SPeter Avalos 			 * KEXINIT now.
1378e9778795SPeter Avalos 			 * NB. reenters this function via kex_start_rekex().
1379e9778795SPeter Avalos 			 */
1380e9778795SPeter Avalos 			return kex_start_rekex(ssh);
1381e9778795SPeter Avalos 		}
1382e9778795SPeter Avalos 		return 0;
138318de8d7fSPeter Avalos 	}
138418de8d7fSPeter Avalos 
138518de8d7fSPeter Avalos 	/* rekeying starts with sending KEXINIT */
138618de8d7fSPeter Avalos 	if (type == SSH2_MSG_KEXINIT)
1387e9778795SPeter Avalos 		state->rekeying = 1;
138818de8d7fSPeter Avalos 
1389e9778795SPeter Avalos 	if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1390e9778795SPeter Avalos 		return r;
139118de8d7fSPeter Avalos 
139218de8d7fSPeter Avalos 	/* after a NEWKEYS message we can send the complete queue */
139318de8d7fSPeter Avalos 	if (type == SSH2_MSG_NEWKEYS) {
1394e9778795SPeter Avalos 		state->rekeying = 0;
1395e9778795SPeter Avalos 		state->rekey_time = monotime();
1396e9778795SPeter Avalos 		while ((p = TAILQ_FIRST(&state->outgoing))) {
139718de8d7fSPeter Avalos 			type = p->type;
1398e9778795SPeter Avalos 			/*
1399e9778795SPeter Avalos 			 * If this packet triggers a rekex, then skip the
1400e9778795SPeter Avalos 			 * remaining packets in the queue for now.
1401e9778795SPeter Avalos 			 * NB. re-enters this function via kex_start_rekex.
1402e9778795SPeter Avalos 			 */
1403e9778795SPeter Avalos 			if (ssh_packet_need_rekeying(ssh,
1404e9778795SPeter Avalos 			    sshbuf_len(p->payload))) {
140550a69bb5SSascha Wildner 				debug3_f("queued packet triggered rekex");
1406e9778795SPeter Avalos 				return kex_start_rekex(ssh);
1407e9778795SPeter Avalos 			}
140818de8d7fSPeter Avalos 			debug("dequeue packet: %u", type);
1409e9778795SPeter Avalos 			sshbuf_free(state->outgoing_packet);
1410e9778795SPeter Avalos 			state->outgoing_packet = p->payload;
1411e9778795SPeter Avalos 			TAILQ_REMOVE(&state->outgoing, p, next);
1412e9778795SPeter Avalos 			memset(p, 0, sizeof(*p));
141336e94dc5SPeter Avalos 			free(p);
1414e9778795SPeter Avalos 			if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
1415e9778795SPeter Avalos 				return r;
141618de8d7fSPeter Avalos 		}
141718de8d7fSPeter Avalos 	}
1418e9778795SPeter Avalos 	return 0;
141918de8d7fSPeter Avalos }
142018de8d7fSPeter Avalos 
142118de8d7fSPeter Avalos /*
142218de8d7fSPeter Avalos  * Waits until a packet has been received, and returns its type.  Note that
142318de8d7fSPeter Avalos  * no other data is processed until this returns, so this function should not
142418de8d7fSPeter Avalos  * be used during the interactive session.
142518de8d7fSPeter Avalos  */
142618de8d7fSPeter Avalos 
142718de8d7fSPeter Avalos int
ssh_packet_read_seqnr(struct ssh * ssh,u_char * typep,u_int32_t * seqnr_p)1428e9778795SPeter Avalos ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
142918de8d7fSPeter Avalos {
1430e9778795SPeter Avalos 	struct session_state *state = ssh->state;
1431*ba1276acSMatthew Dillon 	int len, r, ms_remain = 0;
1432ee116499SAntonio Huete Jimenez 	struct pollfd pfd;
143318de8d7fSPeter Avalos 	char buf[8192];
1434ee116499SAntonio Huete Jimenez 	struct timeval start;
1435ee116499SAntonio Huete Jimenez 	struct timespec timespec, *timespecp = NULL;
143618de8d7fSPeter Avalos 
143718de8d7fSPeter Avalos 	DBG(debug("packet_read()"));
143818de8d7fSPeter Avalos 
1439e9778795SPeter Avalos 	/*
1440e9778795SPeter Avalos 	 * Since we are blocking, ensure that all written packets have
1441e9778795SPeter Avalos 	 * been sent.
1442e9778795SPeter Avalos 	 */
1443e9778795SPeter Avalos 	if ((r = ssh_packet_write_wait(ssh)) != 0)
1444e9778795SPeter Avalos 		goto out;
144518de8d7fSPeter Avalos 
144618de8d7fSPeter Avalos 	/* Stay in the loop until we have received a complete packet. */
144718de8d7fSPeter Avalos 	for (;;) {
144818de8d7fSPeter Avalos 		/* Try to read a packet from the buffer. */
1449*ba1276acSMatthew Dillon 		if ((r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p)) != 0)
1450e9778795SPeter Avalos 			break;
145118de8d7fSPeter Avalos 		/* If we got a packet, return it. */
1452e9778795SPeter Avalos 		if (*typep != SSH_MSG_NONE)
1453e9778795SPeter Avalos 			break;
145418de8d7fSPeter Avalos 		/*
145518de8d7fSPeter Avalos 		 * Otherwise, wait for some data to arrive, add it to the
145618de8d7fSPeter Avalos 		 * buffer, and try again.
145718de8d7fSPeter Avalos 		 */
1458ee116499SAntonio Huete Jimenez 		pfd.fd = state->connection_in;
1459ee116499SAntonio Huete Jimenez 		pfd.events = POLLIN;
146018de8d7fSPeter Avalos 
1461e9778795SPeter Avalos 		if (state->packet_timeout_ms > 0) {
1462e9778795SPeter Avalos 			ms_remain = state->packet_timeout_ms;
1463ee116499SAntonio Huete Jimenez 			timespecp = &timespec;
146418de8d7fSPeter Avalos 		}
146518de8d7fSPeter Avalos 		/* Wait for some data to arrive. */
146618de8d7fSPeter Avalos 		for (;;) {
14670cbfa66cSDaniel Fojt 			if (state->packet_timeout_ms > 0) {
1468ee116499SAntonio Huete Jimenez 				ms_to_timespec(&timespec, ms_remain);
1469664f4763Szrj 				monotime_tv(&start);
147018de8d7fSPeter Avalos 			}
1471ee116499SAntonio Huete Jimenez 			if ((r = ppoll(&pfd, 1, timespecp, NULL)) >= 0)
147218de8d7fSPeter Avalos 				break;
147318de8d7fSPeter Avalos 			if (errno != EAGAIN && errno != EINTR &&
1474664f4763Szrj 			    errno != EWOULDBLOCK) {
1475664f4763Szrj 				r = SSH_ERR_SYSTEM_ERROR;
1476664f4763Szrj 				goto out;
1477664f4763Szrj 			}
14780cbfa66cSDaniel Fojt 			if (state->packet_timeout_ms <= 0)
147918de8d7fSPeter Avalos 				continue;
148018de8d7fSPeter Avalos 			ms_subtract_diff(&start, &ms_remain);
148118de8d7fSPeter Avalos 			if (ms_remain <= 0) {
1482e9778795SPeter Avalos 				r = 0;
148318de8d7fSPeter Avalos 				break;
148418de8d7fSPeter Avalos 			}
148518de8d7fSPeter Avalos 		}
1486ce74bacaSMatthew Dillon 		if (r == 0) {
1487ce74bacaSMatthew Dillon 			r = SSH_ERR_CONN_TIMEOUT;
1488ce74bacaSMatthew Dillon 			goto out;
1489ce74bacaSMatthew Dillon 		}
149018de8d7fSPeter Avalos 		/* Read data from the socket. */
1491e9778795SPeter Avalos 		len = read(state->connection_in, buf, sizeof(buf));
149218de8d7fSPeter Avalos 		if (len == 0) {
1493e9778795SPeter Avalos 			r = SSH_ERR_CONN_CLOSED;
1494e9778795SPeter Avalos 			goto out;
149518de8d7fSPeter Avalos 		}
14960cbfa66cSDaniel Fojt 		if (len == -1) {
1497e9778795SPeter Avalos 			r = SSH_ERR_SYSTEM_ERROR;
1498e9778795SPeter Avalos 			goto out;
1499e9778795SPeter Avalos 		}
1500e9778795SPeter Avalos 
150118de8d7fSPeter Avalos 		/* Append it to the buffer. */
1502e9778795SPeter Avalos 		if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1503e9778795SPeter Avalos 			goto out;
150418de8d7fSPeter Avalos 	}
1505e9778795SPeter Avalos  out:
1506e9778795SPeter Avalos 	return r;
150718de8d7fSPeter Avalos }
150818de8d7fSPeter Avalos 
150918de8d7fSPeter Avalos int
ssh_packet_read(struct ssh * ssh)1510e9778795SPeter Avalos ssh_packet_read(struct ssh *ssh)
151118de8d7fSPeter Avalos {
1512e9778795SPeter Avalos 	u_char type;
1513e9778795SPeter Avalos 	int r;
1514e9778795SPeter Avalos 
1515e9778795SPeter Avalos 	if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
151650a69bb5SSascha Wildner 		fatal_fr(r, "read");
1517e9778795SPeter Avalos 	return type;
151818de8d7fSPeter Avalos }
151918de8d7fSPeter Avalos 
1520ce74bacaSMatthew Dillon static int
ssh_packet_read_poll2_mux(struct ssh * ssh,u_char * typep,u_int32_t * seqnr_p)1521ce74bacaSMatthew Dillon ssh_packet_read_poll2_mux(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
152218de8d7fSPeter Avalos {
1523e9778795SPeter Avalos 	struct session_state *state = ssh->state;
1524e9778795SPeter Avalos 	const u_char *cp;
1525ce74bacaSMatthew Dillon 	size_t need;
1526e9778795SPeter Avalos 	int r;
1527e9778795SPeter Avalos 
1528ce74bacaSMatthew Dillon 	if (ssh->kex)
1529ce74bacaSMatthew Dillon 		return SSH_ERR_INTERNAL_ERROR;
1530e9778795SPeter Avalos 	*typep = SSH_MSG_NONE;
1531ce74bacaSMatthew Dillon 	cp = sshbuf_ptr(state->input);
1532ce74bacaSMatthew Dillon 	if (state->packlen == 0) {
1533ce74bacaSMatthew Dillon 		if (sshbuf_len(state->input) < 4 + 1)
1534ce74bacaSMatthew Dillon 			return 0; /* packet is incomplete */
1535ce74bacaSMatthew Dillon 		state->packlen = PEEK_U32(cp);
1536ce74bacaSMatthew Dillon 		if (state->packlen < 4 + 1 ||
1537ce74bacaSMatthew Dillon 		    state->packlen > PACKET_MAX_SIZE)
1538ce74bacaSMatthew Dillon 			return SSH_ERR_MESSAGE_INCOMPLETE;
1539e9778795SPeter Avalos 	}
1540ce74bacaSMatthew Dillon 	need = state->packlen + 4;
1541ce74bacaSMatthew Dillon 	if (sshbuf_len(state->input) < need)
1542ce74bacaSMatthew Dillon 		return 0; /* packet is incomplete */
1543e9778795SPeter Avalos 	sshbuf_reset(state->incoming_packet);
1544ce74bacaSMatthew Dillon 	if ((r = sshbuf_put(state->incoming_packet, cp + 4,
1545ce74bacaSMatthew Dillon 	    state->packlen)) != 0 ||
1546ce74bacaSMatthew Dillon 	    (r = sshbuf_consume(state->input, need)) != 0 ||
1547ce74bacaSMatthew Dillon 	    (r = sshbuf_get_u8(state->incoming_packet, NULL)) != 0 ||
1548ce74bacaSMatthew Dillon 	    (r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1549e9778795SPeter Avalos 		return r;
1550ce74bacaSMatthew Dillon 	if (ssh_packet_log_type(*typep))
155150a69bb5SSascha Wildner 		debug3_f("type %u", *typep);
1552ce74bacaSMatthew Dillon 	/* sshbuf_dump(state->incoming_packet, stderr); */
1553ce74bacaSMatthew Dillon 	/* reset for next packet */
1554ce74bacaSMatthew Dillon 	state->packlen = 0;
1555e9778795SPeter Avalos 	return r;
1556e9778795SPeter Avalos }
1557e9778795SPeter Avalos 
1558e9778795SPeter Avalos int
ssh_packet_read_poll2(struct ssh * ssh,u_char * typep,u_int32_t * seqnr_p)1559e9778795SPeter Avalos ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
156018de8d7fSPeter Avalos {
1561e9778795SPeter Avalos 	struct session_state *state = ssh->state;
156218de8d7fSPeter Avalos 	u_int padlen, need;
1563e9778795SPeter Avalos 	u_char *cp;
1564e9778795SPeter Avalos 	u_int maclen, aadlen = 0, authlen = 0, block_size;
1565e9778795SPeter Avalos 	struct sshenc *enc   = NULL;
1566e9778795SPeter Avalos 	struct sshmac *mac   = NULL;
1567e9778795SPeter Avalos 	struct sshcomp *comp = NULL;
1568e9778795SPeter Avalos 	int r;
156918de8d7fSPeter Avalos 
1570ce74bacaSMatthew Dillon 	if (state->mux)
1571ce74bacaSMatthew Dillon 		return ssh_packet_read_poll2_mux(ssh, typep, seqnr_p);
1572ce74bacaSMatthew Dillon 
1573e9778795SPeter Avalos 	*typep = SSH_MSG_NONE;
1574cb5eb4f1SPeter Avalos 
1575e9778795SPeter Avalos 	if (state->packet_discard)
1576e9778795SPeter Avalos 		return 0;
1577e9778795SPeter Avalos 
1578e9778795SPeter Avalos 	if (state->newkeys[MODE_IN] != NULL) {
1579e9778795SPeter Avalos 		enc  = &state->newkeys[MODE_IN]->enc;
1580e9778795SPeter Avalos 		mac  = &state->newkeys[MODE_IN]->mac;
1581e9778795SPeter Avalos 		comp = &state->newkeys[MODE_IN]->comp;
158236e94dc5SPeter Avalos 		/* disable mac for authenticated encryption */
158336e94dc5SPeter Avalos 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
158436e94dc5SPeter Avalos 			mac = NULL;
158518de8d7fSPeter Avalos 	}
158618de8d7fSPeter Avalos 	maclen = mac && mac->enabled ? mac->mac_len : 0;
158718de8d7fSPeter Avalos 	block_size = enc ? enc->block_size : 8;
158836e94dc5SPeter Avalos 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
158918de8d7fSPeter Avalos 
1590e9778795SPeter Avalos 	if (aadlen && state->packlen == 0) {
1591ce74bacaSMatthew Dillon 		if (cipher_get_length(state->receive_context,
1592e9778795SPeter Avalos 		    &state->packlen, state->p_read.seqnr,
1593e9778795SPeter Avalos 		    sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
1594e9778795SPeter Avalos 			return 0;
1595e9778795SPeter Avalos 		if (state->packlen < 1 + 4 ||
1596e9778795SPeter Avalos 		    state->packlen > PACKET_MAX_SIZE) {
159736e94dc5SPeter Avalos #ifdef PACKET_DEBUG
1598e9778795SPeter Avalos 			sshbuf_dump(state->input, stderr);
159936e94dc5SPeter Avalos #endif
1600e9778795SPeter Avalos 			logit("Bad packet length %u.", state->packlen);
1601e9778795SPeter Avalos 			if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1602e9778795SPeter Avalos 				return r;
1603e9778795SPeter Avalos 			return SSH_ERR_CONN_CORRUPT;
160436e94dc5SPeter Avalos 		}
1605e9778795SPeter Avalos 		sshbuf_reset(state->incoming_packet);
1606e9778795SPeter Avalos 	} else if (state->packlen == 0) {
160718de8d7fSPeter Avalos 		/*
160818de8d7fSPeter Avalos 		 * check if input size is less than the cipher block size,
160918de8d7fSPeter Avalos 		 * decrypt first block and extract length of incoming packet
161018de8d7fSPeter Avalos 		 */
1611e9778795SPeter Avalos 		if (sshbuf_len(state->input) < block_size)
1612e9778795SPeter Avalos 			return 0;
1613e9778795SPeter Avalos 		sshbuf_reset(state->incoming_packet);
1614e9778795SPeter Avalos 		if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1615e9778795SPeter Avalos 		    &cp)) != 0)
1616e9778795SPeter Avalos 			goto out;
1617ce74bacaSMatthew Dillon 		if ((r = cipher_crypt(state->receive_context,
1618e9778795SPeter Avalos 		    state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1619e9778795SPeter Avalos 		    block_size, 0, 0)) != 0)
1620e9778795SPeter Avalos 			goto out;
1621e9778795SPeter Avalos 		state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1622e9778795SPeter Avalos 		if (state->packlen < 1 + 4 ||
1623e9778795SPeter Avalos 		    state->packlen > PACKET_MAX_SIZE) {
162418de8d7fSPeter Avalos #ifdef PACKET_DEBUG
1625e9778795SPeter Avalos 			fprintf(stderr, "input: \n");
1626e9778795SPeter Avalos 			sshbuf_dump(state->input, stderr);
1627e9778795SPeter Avalos 			fprintf(stderr, "incoming_packet: \n");
1628e9778795SPeter Avalos 			sshbuf_dump(state->incoming_packet, stderr);
162918de8d7fSPeter Avalos #endif
1630e9778795SPeter Avalos 			logit("Bad packet length %u.", state->packlen);
1631e9778795SPeter Avalos 			return ssh_packet_start_discard(ssh, enc, mac, 0,
1632cb5eb4f1SPeter Avalos 			    PACKET_MAX_SIZE);
163318de8d7fSPeter Avalos 		}
1634e9778795SPeter Avalos 		if ((r = sshbuf_consume(state->input, block_size)) != 0)
1635e9778795SPeter Avalos 			goto out;
163618de8d7fSPeter Avalos 	}
1637e9778795SPeter Avalos 	DBG(debug("input: packet len %u", state->packlen+4));
1638e9778795SPeter Avalos 
163936e94dc5SPeter Avalos 	if (aadlen) {
164036e94dc5SPeter Avalos 		/* only the payload is encrypted */
1641e9778795SPeter Avalos 		need = state->packlen;
164236e94dc5SPeter Avalos 	} else {
164336e94dc5SPeter Avalos 		/*
164436e94dc5SPeter Avalos 		 * the payload size and the payload are encrypted, but we
164536e94dc5SPeter Avalos 		 * have a partial packet of block_size bytes
164636e94dc5SPeter Avalos 		 */
1647e9778795SPeter Avalos 		need = 4 + state->packlen - block_size;
164836e94dc5SPeter Avalos 	}
164936e94dc5SPeter Avalos 	DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
165036e94dc5SPeter Avalos 	    " aadlen %d", block_size, need, maclen, authlen, aadlen));
1651cb5eb4f1SPeter Avalos 	if (need % block_size != 0) {
1652cb5eb4f1SPeter Avalos 		logit("padding error: need %d block %d mod %d",
165318de8d7fSPeter Avalos 		    need, block_size, need % block_size);
1654e9778795SPeter Avalos 		return ssh_packet_start_discard(ssh, enc, mac, 0,
1655cb5eb4f1SPeter Avalos 		    PACKET_MAX_SIZE - block_size);
1656cb5eb4f1SPeter Avalos 	}
165718de8d7fSPeter Avalos 	/*
165818de8d7fSPeter Avalos 	 * check if the entire packet has been received and
165936e94dc5SPeter Avalos 	 * decrypt into incoming_packet:
166036e94dc5SPeter Avalos 	 * 'aadlen' bytes are unencrypted, but authenticated.
166136e94dc5SPeter Avalos 	 * 'need' bytes are encrypted, followed by either
166236e94dc5SPeter Avalos 	 * 'authlen' bytes of authentication tag or
166336e94dc5SPeter Avalos 	 * 'maclen' bytes of message authentication code.
166418de8d7fSPeter Avalos 	 */
1665e9778795SPeter Avalos 	if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1666e9778795SPeter Avalos 		return 0; /* packet is incomplete */
166718de8d7fSPeter Avalos #ifdef PACKET_DEBUG
166818de8d7fSPeter Avalos 	fprintf(stderr, "read_poll enc/full: ");
1669e9778795SPeter Avalos 	sshbuf_dump(state->input, stderr);
167018de8d7fSPeter Avalos #endif
1671e9778795SPeter Avalos 	/* EtM: check mac over encrypted input */
1672e9778795SPeter Avalos 	if (mac && mac->enabled && mac->etm) {
1673e9778795SPeter Avalos 		if ((r = mac_check(mac, state->p_read.seqnr,
1674e9778795SPeter Avalos 		    sshbuf_ptr(state->input), aadlen + need,
1675e9778795SPeter Avalos 		    sshbuf_ptr(state->input) + aadlen + need + authlen,
1676e9778795SPeter Avalos 		    maclen)) != 0) {
1677e9778795SPeter Avalos 			if (r == SSH_ERR_MAC_INVALID)
1678e9778795SPeter Avalos 				logit("Corrupted MAC on input.");
1679e9778795SPeter Avalos 			goto out;
1680e9778795SPeter Avalos 		}
1681e9778795SPeter Avalos 	}
1682e9778795SPeter Avalos 	if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1683e9778795SPeter Avalos 	    &cp)) != 0)
1684e9778795SPeter Avalos 		goto out;
1685ce74bacaSMatthew Dillon 	if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
1686e9778795SPeter Avalos 	    sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1687e9778795SPeter Avalos 		goto out;
1688e9778795SPeter Avalos 	if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1689e9778795SPeter Avalos 		goto out;
169018de8d7fSPeter Avalos 	if (mac && mac->enabled) {
1691e9778795SPeter Avalos 		/* Not EtM: check MAC over cleartext */
1692e9778795SPeter Avalos 		if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
1693e9778795SPeter Avalos 		    sshbuf_ptr(state->incoming_packet),
1694e9778795SPeter Avalos 		    sshbuf_len(state->incoming_packet),
1695e9778795SPeter Avalos 		    sshbuf_ptr(state->input), maclen)) != 0) {
1696e9778795SPeter Avalos 			if (r != SSH_ERR_MAC_INVALID)
1697e9778795SPeter Avalos 				goto out;
1698cb5eb4f1SPeter Avalos 			logit("Corrupted MAC on input.");
1699ce74bacaSMatthew Dillon 			if (need + block_size > PACKET_MAX_SIZE)
1700e9778795SPeter Avalos 				return SSH_ERR_INTERNAL_ERROR;
1701e9778795SPeter Avalos 			return ssh_packet_start_discard(ssh, enc, mac,
1702e9778795SPeter Avalos 			    sshbuf_len(state->incoming_packet),
1703ce74bacaSMatthew Dillon 			    PACKET_MAX_SIZE - need - block_size);
1704cb5eb4f1SPeter Avalos 		}
1705e9778795SPeter Avalos 		/* Remove MAC from input buffer */
1706e9778795SPeter Avalos 		DBG(debug("MAC #%d ok", state->p_read.seqnr));
1707e9778795SPeter Avalos 		if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1708e9778795SPeter Avalos 			goto out;
170918de8d7fSPeter Avalos 	}
1710*ba1276acSMatthew Dillon 
171118de8d7fSPeter Avalos 	if (seqnr_p != NULL)
1712e9778795SPeter Avalos 		*seqnr_p = state->p_read.seqnr;
1713*ba1276acSMatthew Dillon 	if (++state->p_read.seqnr == 0) {
1714*ba1276acSMatthew Dillon 		if ((ssh->kex->flags & KEX_INITIAL) != 0) {
1715*ba1276acSMatthew Dillon 			ssh_packet_disconnect(ssh, "incoming sequence number "
1716*ba1276acSMatthew Dillon 			    "wrapped during initial key exchange");
1717*ba1276acSMatthew Dillon 		}
171818de8d7fSPeter Avalos 		logit("incoming seqnr wraps around");
1719*ba1276acSMatthew Dillon 	}
1720e9778795SPeter Avalos 	if (++state->p_read.packets == 0)
1721e9778795SPeter Avalos 		if (!(ssh->compat & SSH_BUG_NOREKEY))
1722e9778795SPeter Avalos 			return SSH_ERR_NEED_REKEY;
1723e9778795SPeter Avalos 	state->p_read.blocks += (state->packlen + 4) / block_size;
1724e9778795SPeter Avalos 	state->p_read.bytes += state->packlen + 4;
172518de8d7fSPeter Avalos 
172618de8d7fSPeter Avalos 	/* get padlen */
1727e9778795SPeter Avalos 	padlen = sshbuf_ptr(state->incoming_packet)[4];
172818de8d7fSPeter Avalos 	DBG(debug("input: padlen %d", padlen));
1729e9778795SPeter Avalos 	if (padlen < 4)	{
1730e9778795SPeter Avalos 		if ((r = sshpkt_disconnect(ssh,
1731e9778795SPeter Avalos 		    "Corrupted padlen %d on input.", padlen)) != 0 ||
1732e9778795SPeter Avalos 		    (r = ssh_packet_write_wait(ssh)) != 0)
1733e9778795SPeter Avalos 			return r;
1734e9778795SPeter Avalos 		return SSH_ERR_CONN_CORRUPT;
1735e9778795SPeter Avalos 	}
173618de8d7fSPeter Avalos 
173718de8d7fSPeter Avalos 	/* skip packet size + padlen, discard padding */
1738e9778795SPeter Avalos 	if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1739e9778795SPeter Avalos 	    ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1740e9778795SPeter Avalos 		goto out;
174118de8d7fSPeter Avalos 
1742e9778795SPeter Avalos 	DBG(debug("input: len before de-compress %zd",
1743e9778795SPeter Avalos 	    sshbuf_len(state->incoming_packet)));
174418de8d7fSPeter Avalos 	if (comp && comp->enabled) {
1745e9778795SPeter Avalos 		sshbuf_reset(state->compression_buffer);
1746e9778795SPeter Avalos 		if ((r = uncompress_buffer(ssh, state->incoming_packet,
1747e9778795SPeter Avalos 		    state->compression_buffer)) != 0)
1748e9778795SPeter Avalos 			goto out;
1749e9778795SPeter Avalos 		sshbuf_reset(state->incoming_packet);
1750e9778795SPeter Avalos 		if ((r = sshbuf_putb(state->incoming_packet,
1751e9778795SPeter Avalos 		    state->compression_buffer)) != 0)
1752e9778795SPeter Avalos 			goto out;
1753e9778795SPeter Avalos 		DBG(debug("input: len after de-compress %zd",
1754e9778795SPeter Avalos 		    sshbuf_len(state->incoming_packet)));
175518de8d7fSPeter Avalos 	}
175618de8d7fSPeter Avalos 	/*
175718de8d7fSPeter Avalos 	 * get packet type, implies consume.
175818de8d7fSPeter Avalos 	 * return length of payload (without type field)
175918de8d7fSPeter Avalos 	 */
1760e9778795SPeter Avalos 	if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1761e9778795SPeter Avalos 		goto out;
1762e9778795SPeter Avalos 	if (ssh_packet_log_type(*typep))
1763e9778795SPeter Avalos 		debug3("receive packet: type %u", *typep);
1764*ba1276acSMatthew Dillon 	if (*typep < SSH2_MSG_MIN) {
1765e9778795SPeter Avalos 		if ((r = sshpkt_disconnect(ssh,
1766e9778795SPeter Avalos 		    "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1767e9778795SPeter Avalos 		    (r = ssh_packet_write_wait(ssh)) != 0)
1768e9778795SPeter Avalos 			return r;
1769e9778795SPeter Avalos 		return SSH_ERR_PROTOCOL_ERROR;
1770e9778795SPeter Avalos 	}
1771ce74bacaSMatthew Dillon 	if (state->hook_in != NULL &&
1772ce74bacaSMatthew Dillon 	    (r = state->hook_in(ssh, state->incoming_packet, typep,
1773ce74bacaSMatthew Dillon 	    state->hook_in_ctx)) != 0)
1774ce74bacaSMatthew Dillon 		return r;
1775ce74bacaSMatthew Dillon 	if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1776e9778795SPeter Avalos 		r = ssh_packet_enable_delayed_compress(ssh);
1777e9778795SPeter Avalos 	else
1778e9778795SPeter Avalos 		r = 0;
177918de8d7fSPeter Avalos #ifdef PACKET_DEBUG
1780e9778795SPeter Avalos 	fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1781e9778795SPeter Avalos 	sshbuf_dump(state->incoming_packet, stderr);
178218de8d7fSPeter Avalos #endif
178318de8d7fSPeter Avalos 	/* reset for next packet */
1784e9778795SPeter Avalos 	state->packlen = 0;
1785*ba1276acSMatthew Dillon 	if (*typep == SSH2_MSG_NEWKEYS && ssh->kex->kex_strict) {
1786*ba1276acSMatthew Dillon 		debug_f("resetting read seqnr %u", state->p_read.seqnr);
1787*ba1276acSMatthew Dillon 		state->p_read.seqnr = 0;
1788*ba1276acSMatthew Dillon 	}
1789e9778795SPeter Avalos 
179050a69bb5SSascha Wildner 	if ((r = ssh_packet_check_rekey(ssh)) != 0)
1791e9778795SPeter Avalos 		return r;
1792e9778795SPeter Avalos  out:
1793e9778795SPeter Avalos 	return r;
179418de8d7fSPeter Avalos }
179518de8d7fSPeter Avalos 
179618de8d7fSPeter Avalos int
ssh_packet_read_poll_seqnr(struct ssh * ssh,u_char * typep,u_int32_t * seqnr_p)1797e9778795SPeter Avalos ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
179818de8d7fSPeter Avalos {
1799e9778795SPeter Avalos 	struct session_state *state = ssh->state;
180018de8d7fSPeter Avalos 	u_int reason, seqnr;
1801e9778795SPeter Avalos 	int r;
1802e9778795SPeter Avalos 	u_char *msg;
1803*ba1276acSMatthew Dillon 	const u_char *d;
1804*ba1276acSMatthew Dillon 	size_t len;
180518de8d7fSPeter Avalos 
180618de8d7fSPeter Avalos 	for (;;) {
1807e9778795SPeter Avalos 		msg = NULL;
1808e9778795SPeter Avalos 		r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1809e9778795SPeter Avalos 		if (r != 0)
1810e9778795SPeter Avalos 			return r;
1811*ba1276acSMatthew Dillon 		if (*typep == 0) {
1812*ba1276acSMatthew Dillon 			/* no message ready */
1813*ba1276acSMatthew Dillon 			return 0;
1814*ba1276acSMatthew Dillon 		}
1815e9778795SPeter Avalos 		state->keep_alive_timeouts = 0;
1816e9778795SPeter Avalos 		DBG(debug("received packet type %d", *typep));
1817*ba1276acSMatthew Dillon 
1818*ba1276acSMatthew Dillon 		/* Always process disconnect messages */
1819*ba1276acSMatthew Dillon 		if (*typep == SSH2_MSG_DISCONNECT) {
1820*ba1276acSMatthew Dillon 			if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1821*ba1276acSMatthew Dillon 			    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1822*ba1276acSMatthew Dillon 				return r;
1823*ba1276acSMatthew Dillon 			/* Ignore normal client exit notifications */
1824*ba1276acSMatthew Dillon 			do_log2(ssh->state->server_side &&
1825*ba1276acSMatthew Dillon 			    reason == SSH2_DISCONNECT_BY_APPLICATION ?
1826*ba1276acSMatthew Dillon 			    SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1827*ba1276acSMatthew Dillon 			    "Received disconnect from %s port %d:"
1828*ba1276acSMatthew Dillon 			    "%u: %.400s", ssh_remote_ipaddr(ssh),
1829*ba1276acSMatthew Dillon 			    ssh_remote_port(ssh), reason, msg);
1830*ba1276acSMatthew Dillon 			free(msg);
1831*ba1276acSMatthew Dillon 			return SSH_ERR_DISCONNECTED;
183218de8d7fSPeter Avalos 		}
1833*ba1276acSMatthew Dillon 
1834*ba1276acSMatthew Dillon 		/*
1835*ba1276acSMatthew Dillon 		 * Do not implicitly handle any messages here during initial
1836*ba1276acSMatthew Dillon 		 * KEX when in strict mode. They will be need to be allowed
1837*ba1276acSMatthew Dillon 		 * explicitly by the KEX dispatch table or they will generate
1838*ba1276acSMatthew Dillon 		 * protocol errors.
1839*ba1276acSMatthew Dillon 		 */
1840*ba1276acSMatthew Dillon 		if (ssh->kex != NULL &&
1841*ba1276acSMatthew Dillon 		    (ssh->kex->flags & KEX_INITIAL) && ssh->kex->kex_strict)
1842*ba1276acSMatthew Dillon 			return 0;
1843*ba1276acSMatthew Dillon 		/* Implicitly handle transport-level messages */
1844e9778795SPeter Avalos 		switch (*typep) {
184518de8d7fSPeter Avalos 		case SSH2_MSG_IGNORE:
184618de8d7fSPeter Avalos 			debug3("Received SSH2_MSG_IGNORE");
184718de8d7fSPeter Avalos 			break;
184818de8d7fSPeter Avalos 		case SSH2_MSG_DEBUG:
1849e9778795SPeter Avalos 			if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1850e9778795SPeter Avalos 			    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1851e9778795SPeter Avalos 			    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
185236e94dc5SPeter Avalos 				free(msg);
1853e9778795SPeter Avalos 				return r;
1854e9778795SPeter Avalos 			}
1855e9778795SPeter Avalos 			debug("Remote: %.900s", msg);
185636e94dc5SPeter Avalos 			free(msg);
185718de8d7fSPeter Avalos 			break;
185818de8d7fSPeter Avalos 		case SSH2_MSG_UNIMPLEMENTED:
1859e9778795SPeter Avalos 			if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1860e9778795SPeter Avalos 				return r;
186118de8d7fSPeter Avalos 			debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
186218de8d7fSPeter Avalos 			    seqnr);
186318de8d7fSPeter Avalos 			break;
1864*ba1276acSMatthew Dillon 		case SSH2_MSG_PING:
1865*ba1276acSMatthew Dillon 			if ((r = sshpkt_get_string_direct(ssh, &d, &len)) != 0)
1866*ba1276acSMatthew Dillon 				return r;
1867*ba1276acSMatthew Dillon 			DBG(debug("Received SSH2_MSG_PING len %zu", len));
1868*ba1276acSMatthew Dillon 			if ((r = sshpkt_start(ssh, SSH2_MSG_PONG)) != 0 ||
1869*ba1276acSMatthew Dillon 			    (r = sshpkt_put_string(ssh, d, len)) != 0 ||
1870*ba1276acSMatthew Dillon 			    (r = sshpkt_send(ssh)) != 0)
1871*ba1276acSMatthew Dillon 				return r;
1872*ba1276acSMatthew Dillon 			break;
1873*ba1276acSMatthew Dillon 		case SSH2_MSG_PONG:
1874*ba1276acSMatthew Dillon 			if ((r = sshpkt_get_string_direct(ssh,
1875*ba1276acSMatthew Dillon 			    NULL, &len)) != 0)
1876*ba1276acSMatthew Dillon 				return r;
1877*ba1276acSMatthew Dillon 			DBG(debug("Received SSH2_MSG_PONG len %zu", len));
1878*ba1276acSMatthew Dillon 			break;
187918de8d7fSPeter Avalos 		default:
1880e9778795SPeter Avalos 			return 0;
188118de8d7fSPeter Avalos 		}
188218de8d7fSPeter Avalos 	}
188318de8d7fSPeter Avalos }
188418de8d7fSPeter Avalos 
188518de8d7fSPeter Avalos /*
1886ee116499SAntonio Huete Jimenez  * Buffers the supplied input data. This is intended to be used together
1887ee116499SAntonio Huete Jimenez  * with packet_read_poll().
188818de8d7fSPeter Avalos  */
1889e9778795SPeter Avalos int
ssh_packet_process_incoming(struct ssh * ssh,const char * buf,u_int len)1890e9778795SPeter Avalos ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
189118de8d7fSPeter Avalos {
1892e9778795SPeter Avalos 	struct session_state *state = ssh->state;
1893e9778795SPeter Avalos 	int r;
1894e9778795SPeter Avalos 
1895e9778795SPeter Avalos 	if (state->packet_discard) {
1896e9778795SPeter Avalos 		state->keep_alive_timeouts = 0; /* ?? */
1897e9778795SPeter Avalos 		if (len >= state->packet_discard) {
1898e9778795SPeter Avalos 			if ((r = ssh_packet_stop_discard(ssh)) != 0)
1899e9778795SPeter Avalos 				return r;
1900cb5eb4f1SPeter Avalos 		}
1901e9778795SPeter Avalos 		state->packet_discard -= len;
1902e9778795SPeter Avalos 		return 0;
190318de8d7fSPeter Avalos 	}
1904ee116499SAntonio Huete Jimenez 	if ((r = sshbuf_put(state->input, buf, len)) != 0)
1905e9778795SPeter Avalos 		return r;
190618de8d7fSPeter Avalos 
1907e9778795SPeter Avalos 	return 0;
190818de8d7fSPeter Avalos }
190918de8d7fSPeter Avalos 
1910ee116499SAntonio Huete Jimenez /* Reads and buffers data from the specified fd */
1911ee116499SAntonio Huete Jimenez int
ssh_packet_process_read(struct ssh * ssh,int fd)1912ee116499SAntonio Huete Jimenez ssh_packet_process_read(struct ssh *ssh, int fd)
1913ee116499SAntonio Huete Jimenez {
1914ee116499SAntonio Huete Jimenez 	struct session_state *state = ssh->state;
1915ee116499SAntonio Huete Jimenez 	int r;
1916ee116499SAntonio Huete Jimenez 	size_t rlen;
1917ee116499SAntonio Huete Jimenez 
1918ee116499SAntonio Huete Jimenez 	if ((r = sshbuf_read(fd, state->input, PACKET_MAX_SIZE, &rlen)) != 0)
1919ee116499SAntonio Huete Jimenez 		return r;
1920ee116499SAntonio Huete Jimenez 
1921ee116499SAntonio Huete Jimenez 	if (state->packet_discard) {
1922ee116499SAntonio Huete Jimenez 		if ((r = sshbuf_consume_end(state->input, rlen)) != 0)
1923ee116499SAntonio Huete Jimenez 			return r;
1924ee116499SAntonio Huete Jimenez 		state->keep_alive_timeouts = 0; /* ?? */
1925ee116499SAntonio Huete Jimenez 		if (rlen >= state->packet_discard) {
1926ee116499SAntonio Huete Jimenez 			if ((r = ssh_packet_stop_discard(ssh)) != 0)
1927ee116499SAntonio Huete Jimenez 				return r;
1928ee116499SAntonio Huete Jimenez 		}
1929ee116499SAntonio Huete Jimenez 		state->packet_discard -= rlen;
1930ee116499SAntonio Huete Jimenez 		return 0;
1931ee116499SAntonio Huete Jimenez 	}
1932ee116499SAntonio Huete Jimenez 	return 0;
1933ee116499SAntonio Huete Jimenez }
1934ee116499SAntonio Huete Jimenez 
193518de8d7fSPeter Avalos int
ssh_packet_remaining(struct ssh * ssh)1936e9778795SPeter Avalos ssh_packet_remaining(struct ssh *ssh)
193718de8d7fSPeter Avalos {
1938e9778795SPeter Avalos 	return sshbuf_len(ssh->state->incoming_packet);
19399f304aafSPeter Avalos }
19409f304aafSPeter Avalos 
194118de8d7fSPeter Avalos /*
194218de8d7fSPeter Avalos  * Sends a diagnostic message from the server to the client.  This message
194318de8d7fSPeter Avalos  * can be sent at any time (but not while constructing another message). The
194418de8d7fSPeter Avalos  * message is printed immediately, but only if the client is being executed
194518de8d7fSPeter Avalos  * in verbose mode.  These messages are primarily intended to ease debugging
194618de8d7fSPeter Avalos  * authentication problems.   The length of the formatted message must not
1947e9778795SPeter Avalos  * exceed 1024 bytes.  This will automatically call ssh_packet_write_wait.
194818de8d7fSPeter Avalos  */
194918de8d7fSPeter Avalos void
ssh_packet_send_debug(struct ssh * ssh,const char * fmt,...)1950e9778795SPeter Avalos ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
195118de8d7fSPeter Avalos {
195218de8d7fSPeter Avalos 	char buf[1024];
195318de8d7fSPeter Avalos 	va_list args;
1954e9778795SPeter Avalos 	int r;
195518de8d7fSPeter Avalos 
1956ce74bacaSMatthew Dillon 	if ((ssh->compat & SSH_BUG_DEBUG))
195718de8d7fSPeter Avalos 		return;
195818de8d7fSPeter Avalos 
195918de8d7fSPeter Avalos 	va_start(args, fmt);
196018de8d7fSPeter Avalos 	vsnprintf(buf, sizeof(buf), fmt, args);
196118de8d7fSPeter Avalos 	va_end(args);
196218de8d7fSPeter Avalos 
1963664f4763Szrj 	debug3("sending debug message: %s", buf);
1964664f4763Szrj 
1965e9778795SPeter Avalos 	if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
1966e9778795SPeter Avalos 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
1967e9778795SPeter Avalos 	    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
1968e9778795SPeter Avalos 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1969ce74bacaSMatthew Dillon 	    (r = sshpkt_send(ssh)) != 0 ||
1970ce74bacaSMatthew Dillon 	    (r = ssh_packet_write_wait(ssh)) != 0)
197150a69bb5SSascha Wildner 		fatal_fr(r, "send DEBUG");
197218de8d7fSPeter Avalos }
1973ce74bacaSMatthew Dillon 
1974664f4763Szrj void
sshpkt_fmt_connection_id(struct ssh * ssh,char * s,size_t l)1975664f4763Szrj sshpkt_fmt_connection_id(struct ssh *ssh, char *s, size_t l)
1976ce74bacaSMatthew Dillon {
1977ce74bacaSMatthew Dillon 	snprintf(s, l, "%.200s%s%s port %d",
1978ce74bacaSMatthew Dillon 	    ssh->log_preamble ? ssh->log_preamble : "",
1979ce74bacaSMatthew Dillon 	    ssh->log_preamble ? " " : "",
1980ce74bacaSMatthew Dillon 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1981e9778795SPeter Avalos }
1982e9778795SPeter Avalos 
1983e9778795SPeter Avalos /*
1984e9778795SPeter Avalos  * Pretty-print connection-terminating errors and exit.
1985e9778795SPeter Avalos  */
1986664f4763Szrj static void
sshpkt_vfatal(struct ssh * ssh,int r,const char * fmt,va_list ap)1987664f4763Szrj sshpkt_vfatal(struct ssh *ssh, int r, const char *fmt, va_list ap)
1988e9778795SPeter Avalos {
1989664f4763Szrj 	char *tag = NULL, remote_id[512];
19900cbfa66cSDaniel Fojt 	int oerrno = errno;
1991ce74bacaSMatthew Dillon 
1992664f4763Szrj 	sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1993ce74bacaSMatthew Dillon 
1994e9778795SPeter Avalos 	switch (r) {
1995e9778795SPeter Avalos 	case SSH_ERR_CONN_CLOSED:
1996ce74bacaSMatthew Dillon 		ssh_packet_clear_keys(ssh);
1997ce74bacaSMatthew Dillon 		logdie("Connection closed by %s", remote_id);
1998e9778795SPeter Avalos 	case SSH_ERR_CONN_TIMEOUT:
1999ce74bacaSMatthew Dillon 		ssh_packet_clear_keys(ssh);
2000ce74bacaSMatthew Dillon 		logdie("Connection %s %s timed out",
2001ce74bacaSMatthew Dillon 		    ssh->state->server_side ? "from" : "to", remote_id);
2002e9778795SPeter Avalos 	case SSH_ERR_DISCONNECTED:
2003ce74bacaSMatthew Dillon 		ssh_packet_clear_keys(ssh);
2004ce74bacaSMatthew Dillon 		logdie("Disconnected from %s", remote_id);
2005e9778795SPeter Avalos 	case SSH_ERR_SYSTEM_ERROR:
2006ce74bacaSMatthew Dillon 		if (errno == ECONNRESET) {
2007ce74bacaSMatthew Dillon 			ssh_packet_clear_keys(ssh);
2008ce74bacaSMatthew Dillon 			logdie("Connection reset by %s", remote_id);
2009ce74bacaSMatthew Dillon 		}
2010e9778795SPeter Avalos 		/* FALLTHROUGH */
2011e9778795SPeter Avalos 	case SSH_ERR_NO_CIPHER_ALG_MATCH:
2012e9778795SPeter Avalos 	case SSH_ERR_NO_MAC_ALG_MATCH:
2013e9778795SPeter Avalos 	case SSH_ERR_NO_COMPRESS_ALG_MATCH:
2014e9778795SPeter Avalos 	case SSH_ERR_NO_KEX_ALG_MATCH:
2015e9778795SPeter Avalos 	case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
2016*ba1276acSMatthew Dillon 		if (ssh->kex && ssh->kex->failed_choice) {
2017ce74bacaSMatthew Dillon 			ssh_packet_clear_keys(ssh);
20180cbfa66cSDaniel Fojt 			errno = oerrno;
2019ce74bacaSMatthew Dillon 			logdie("Unable to negotiate with %s: %s. "
2020ce74bacaSMatthew Dillon 			    "Their offer: %s", remote_id, ssh_err(r),
2021e9778795SPeter Avalos 			    ssh->kex->failed_choice);
2022e9778795SPeter Avalos 		}
2023e9778795SPeter Avalos 		/* FALLTHROUGH */
2024e9778795SPeter Avalos 	default:
2025664f4763Szrj 		if (vasprintf(&tag, fmt, ap) == -1) {
2026664f4763Szrj 			ssh_packet_clear_keys(ssh);
202750a69bb5SSascha Wildner 			logdie_f("could not allocate failure message");
2028664f4763Szrj 		}
2029ce74bacaSMatthew Dillon 		ssh_packet_clear_keys(ssh);
20300cbfa66cSDaniel Fojt 		errno = oerrno;
203150a69bb5SSascha Wildner 		logdie_r(r, "%s%sConnection %s %s",
2032e9778795SPeter Avalos 		    tag != NULL ? tag : "", tag != NULL ? ": " : "",
203350a69bb5SSascha Wildner 		    ssh->state->server_side ? "from" : "to", remote_id);
2034e9778795SPeter Avalos 	}
203518de8d7fSPeter Avalos }
203618de8d7fSPeter Avalos 
2037664f4763Szrj void
sshpkt_fatal(struct ssh * ssh,int r,const char * fmt,...)2038664f4763Szrj sshpkt_fatal(struct ssh *ssh, int r, const char *fmt, ...)
2039664f4763Szrj {
2040664f4763Szrj 	va_list ap;
2041664f4763Szrj 
2042664f4763Szrj 	va_start(ap, fmt);
2043664f4763Szrj 	sshpkt_vfatal(ssh, r, fmt, ap);
2044664f4763Szrj 	/* NOTREACHED */
2045664f4763Szrj 	va_end(ap);
204650a69bb5SSascha Wildner 	logdie_f("should have exited");
2047664f4763Szrj }
2048664f4763Szrj 
204918de8d7fSPeter Avalos /*
205018de8d7fSPeter Avalos  * Logs the error plus constructs and sends a disconnect packet, closes the
205118de8d7fSPeter Avalos  * connection, and exits.  This function never returns. The error message
205218de8d7fSPeter Avalos  * should not contain a newline.  The length of the formatted message must
205318de8d7fSPeter Avalos  * not exceed 1024 bytes.
205418de8d7fSPeter Avalos  */
205518de8d7fSPeter Avalos void
ssh_packet_disconnect(struct ssh * ssh,const char * fmt,...)2056e9778795SPeter Avalos ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
205718de8d7fSPeter Avalos {
2058ce74bacaSMatthew Dillon 	char buf[1024], remote_id[512];
205918de8d7fSPeter Avalos 	va_list args;
206018de8d7fSPeter Avalos 	static int disconnecting = 0;
2061e9778795SPeter Avalos 	int r;
206218de8d7fSPeter Avalos 
206318de8d7fSPeter Avalos 	if (disconnecting)	/* Guard against recursive invocations. */
206418de8d7fSPeter Avalos 		fatal("packet_disconnect called recursively.");
206518de8d7fSPeter Avalos 	disconnecting = 1;
206618de8d7fSPeter Avalos 
206718de8d7fSPeter Avalos 	/*
206818de8d7fSPeter Avalos 	 * Format the message.  Note that the caller must make sure the
206918de8d7fSPeter Avalos 	 * message is of limited size.
207018de8d7fSPeter Avalos 	 */
2071664f4763Szrj 	sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
207218de8d7fSPeter Avalos 	va_start(args, fmt);
207318de8d7fSPeter Avalos 	vsnprintf(buf, sizeof(buf), fmt, args);
207418de8d7fSPeter Avalos 	va_end(args);
207518de8d7fSPeter Avalos 
207618de8d7fSPeter Avalos 	/* Display the error locally */
2077ce74bacaSMatthew Dillon 	logit("Disconnecting %s: %.100s", remote_id, buf);
207818de8d7fSPeter Avalos 
2079e9778795SPeter Avalos 	/*
2080e9778795SPeter Avalos 	 * Send the disconnect message to the other side, and wait
2081e9778795SPeter Avalos 	 * for it to get sent.
2082e9778795SPeter Avalos 	 */
2083e9778795SPeter Avalos 	if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
2084664f4763Szrj 		sshpkt_fatal(ssh, r, "%s", __func__);
208518de8d7fSPeter Avalos 
2086e9778795SPeter Avalos 	if ((r = ssh_packet_write_wait(ssh)) != 0)
2087664f4763Szrj 		sshpkt_fatal(ssh, r, "%s", __func__);
208818de8d7fSPeter Avalos 
208918de8d7fSPeter Avalos 	/* Close the connection. */
2090e9778795SPeter Avalos 	ssh_packet_close(ssh);
209118de8d7fSPeter Avalos 	cleanup_exit(255);
209218de8d7fSPeter Avalos }
209318de8d7fSPeter Avalos 
2094e9778795SPeter Avalos /*
2095e9778795SPeter Avalos  * Checks if there is any buffered output, and tries to write some of
2096e9778795SPeter Avalos  * the output.
2097e9778795SPeter Avalos  */
2098e9778795SPeter Avalos int
ssh_packet_write_poll(struct ssh * ssh)2099e9778795SPeter Avalos ssh_packet_write_poll(struct ssh *ssh)
210018de8d7fSPeter Avalos {
2101e9778795SPeter Avalos 	struct session_state *state = ssh->state;
2102e9778795SPeter Avalos 	int len = sshbuf_len(state->output);
2103e9778795SPeter Avalos 	int r;
210418de8d7fSPeter Avalos 
210518de8d7fSPeter Avalos 	if (len > 0) {
2106e9778795SPeter Avalos 		len = write(state->connection_out,
2107e9778795SPeter Avalos 		    sshbuf_ptr(state->output), len);
210818de8d7fSPeter Avalos 		if (len == -1) {
210918de8d7fSPeter Avalos 			if (errno == EINTR || errno == EAGAIN ||
211018de8d7fSPeter Avalos 			    errno == EWOULDBLOCK)
2111e9778795SPeter Avalos 				return 0;
2112e9778795SPeter Avalos 			return SSH_ERR_SYSTEM_ERROR;
211318de8d7fSPeter Avalos 		}
2114e9778795SPeter Avalos 		if (len == 0)
2115e9778795SPeter Avalos 			return SSH_ERR_CONN_CLOSED;
2116e9778795SPeter Avalos 		if ((r = sshbuf_consume(state->output, len)) != 0)
2117e9778795SPeter Avalos 			return r;
211818de8d7fSPeter Avalos 	}
2119e9778795SPeter Avalos 	return 0;
212018de8d7fSPeter Avalos }
212118de8d7fSPeter Avalos 
212218de8d7fSPeter Avalos /*
212318de8d7fSPeter Avalos  * Calls packet_write_poll repeatedly until all pending output data has been
212418de8d7fSPeter Avalos  * written.
212518de8d7fSPeter Avalos  */
2126e9778795SPeter Avalos int
ssh_packet_write_wait(struct ssh * ssh)2127e9778795SPeter Avalos ssh_packet_write_wait(struct ssh *ssh)
212818de8d7fSPeter Avalos {
2129e9778795SPeter Avalos 	int ret, r, ms_remain = 0;
2130ee116499SAntonio Huete Jimenez 	struct timeval start;
2131ee116499SAntonio Huete Jimenez 	struct timespec timespec, *timespecp = NULL;
2132e9778795SPeter Avalos 	struct session_state *state = ssh->state;
2133ee116499SAntonio Huete Jimenez 	struct pollfd pfd;
213418de8d7fSPeter Avalos 
2135ee116499SAntonio Huete Jimenez 	if ((r = ssh_packet_write_poll(ssh)) != 0)
2136e9778795SPeter Avalos 		return r;
2137e9778795SPeter Avalos 	while (ssh_packet_have_data_to_write(ssh)) {
2138ee116499SAntonio Huete Jimenez 		pfd.fd = state->connection_out;
2139ee116499SAntonio Huete Jimenez 		pfd.events = POLLOUT;
214018de8d7fSPeter Avalos 
2141e9778795SPeter Avalos 		if (state->packet_timeout_ms > 0) {
2142e9778795SPeter Avalos 			ms_remain = state->packet_timeout_ms;
2143ee116499SAntonio Huete Jimenez 			timespecp = &timespec;
214418de8d7fSPeter Avalos 		}
214518de8d7fSPeter Avalos 		for (;;) {
21460cbfa66cSDaniel Fojt 			if (state->packet_timeout_ms > 0) {
2147ee116499SAntonio Huete Jimenez 				ms_to_timespec(&timespec, ms_remain);
2148664f4763Szrj 				monotime_tv(&start);
214918de8d7fSPeter Avalos 			}
2150ee116499SAntonio Huete Jimenez 			if ((ret = ppoll(&pfd, 1, timespecp, NULL)) >= 0)
215118de8d7fSPeter Avalos 				break;
215218de8d7fSPeter Avalos 			if (errno != EAGAIN && errno != EINTR &&
215318de8d7fSPeter Avalos 			    errno != EWOULDBLOCK)
215418de8d7fSPeter Avalos 				break;
21550cbfa66cSDaniel Fojt 			if (state->packet_timeout_ms <= 0)
215618de8d7fSPeter Avalos 				continue;
215718de8d7fSPeter Avalos 			ms_subtract_diff(&start, &ms_remain);
215818de8d7fSPeter Avalos 			if (ms_remain <= 0) {
215918de8d7fSPeter Avalos 				ret = 0;
216018de8d7fSPeter Avalos 				break;
216118de8d7fSPeter Avalos 			}
216218de8d7fSPeter Avalos 		}
2163ee116499SAntonio Huete Jimenez 		if (ret == 0)
2164e9778795SPeter Avalos 			return SSH_ERR_CONN_TIMEOUT;
2165ee116499SAntonio Huete Jimenez 		if ((r = ssh_packet_write_poll(ssh)) != 0)
2166e9778795SPeter Avalos 			return r;
2167e9778795SPeter Avalos 	}
2168e9778795SPeter Avalos 	return 0;
216918de8d7fSPeter Avalos }
217018de8d7fSPeter Avalos 
217118de8d7fSPeter Avalos /* Returns true if there is buffered data to write to the connection. */
217218de8d7fSPeter Avalos 
217318de8d7fSPeter Avalos int
ssh_packet_have_data_to_write(struct ssh * ssh)2174e9778795SPeter Avalos ssh_packet_have_data_to_write(struct ssh *ssh)
217518de8d7fSPeter Avalos {
2176e9778795SPeter Avalos 	return sshbuf_len(ssh->state->output) != 0;
217718de8d7fSPeter Avalos }
217818de8d7fSPeter Avalos 
217918de8d7fSPeter Avalos /* Returns true if there is not too much data to write to the connection. */
218018de8d7fSPeter Avalos 
218118de8d7fSPeter Avalos int
ssh_packet_not_very_much_data_to_write(struct ssh * ssh)2182e9778795SPeter Avalos ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
218318de8d7fSPeter Avalos {
2184e9778795SPeter Avalos 	if (ssh->state->interactive_mode)
2185e9778795SPeter Avalos 		return sshbuf_len(ssh->state->output) < 16384;
218618de8d7fSPeter Avalos 	else
2187e9778795SPeter Avalos 		return sshbuf_len(ssh->state->output) < 128 * 1024;
218818de8d7fSPeter Avalos }
218918de8d7fSPeter Avalos 
2190*ba1276acSMatthew Dillon /*
2191*ba1276acSMatthew Dillon  * returns true when there are at most a few keystrokes of data to write
2192*ba1276acSMatthew Dillon  * and the connection is in interactive mode.
2193*ba1276acSMatthew Dillon  */
2194*ba1276acSMatthew Dillon 
2195*ba1276acSMatthew Dillon int
ssh_packet_interactive_data_to_write(struct ssh * ssh)2196*ba1276acSMatthew Dillon ssh_packet_interactive_data_to_write(struct ssh *ssh)
2197*ba1276acSMatthew Dillon {
2198*ba1276acSMatthew Dillon 	return ssh->state->interactive_mode &&
2199*ba1276acSMatthew Dillon 	    sshbuf_len(ssh->state->output) < 256;
2200*ba1276acSMatthew Dillon }
2201*ba1276acSMatthew Dillon 
2202e9778795SPeter Avalos void
ssh_packet_set_tos(struct ssh * ssh,int tos)2203e9778795SPeter Avalos ssh_packet_set_tos(struct ssh *ssh, int tos)
220418de8d7fSPeter Avalos {
2205ce74bacaSMatthew Dillon 	if (!ssh_packet_connection_is_on_socket(ssh) || tos == INT_MAX)
220618de8d7fSPeter Avalos 		return;
220750a69bb5SSascha Wildner 	set_sock_tos(ssh->state->connection_in, tos);
220818de8d7fSPeter Avalos }
220918de8d7fSPeter Avalos 
221018de8d7fSPeter Avalos /* Informs that the current session is interactive.  Sets IP flags for that. */
221118de8d7fSPeter Avalos 
221218de8d7fSPeter Avalos void
ssh_packet_set_interactive(struct ssh * ssh,int interactive,int qos_interactive,int qos_bulk)2213e9778795SPeter Avalos ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
221418de8d7fSPeter Avalos {
2215e9778795SPeter Avalos 	struct session_state *state = ssh->state;
2216e9778795SPeter Avalos 
2217e9778795SPeter Avalos 	if (state->set_interactive_called)
221818de8d7fSPeter Avalos 		return;
2219e9778795SPeter Avalos 	state->set_interactive_called = 1;
222018de8d7fSPeter Avalos 
222118de8d7fSPeter Avalos 	/* Record that we are in interactive mode. */
2222e9778795SPeter Avalos 	state->interactive_mode = interactive;
222318de8d7fSPeter Avalos 
222418de8d7fSPeter Avalos 	/* Only set socket options if using a socket.  */
2225e9778795SPeter Avalos 	if (!ssh_packet_connection_is_on_socket(ssh))
222618de8d7fSPeter Avalos 		return;
2227e9778795SPeter Avalos 	set_nodelay(state->connection_in);
222850a69bb5SSascha Wildner 	ssh_packet_set_tos(ssh, interactive ? qos_interactive : qos_bulk);
222918de8d7fSPeter Avalos }
223018de8d7fSPeter Avalos 
223118de8d7fSPeter Avalos /* Returns true if the current connection is interactive. */
223218de8d7fSPeter Avalos 
223318de8d7fSPeter Avalos int
ssh_packet_is_interactive(struct ssh * ssh)2234e9778795SPeter Avalos ssh_packet_is_interactive(struct ssh *ssh)
223518de8d7fSPeter Avalos {
2236e9778795SPeter Avalos 	return ssh->state->interactive_mode;
223718de8d7fSPeter Avalos }
223818de8d7fSPeter Avalos 
223918de8d7fSPeter Avalos int
ssh_packet_set_maxsize(struct ssh * ssh,u_int s)2240e9778795SPeter Avalos ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
224118de8d7fSPeter Avalos {
2242e9778795SPeter Avalos 	struct session_state *state = ssh->state;
2243e9778795SPeter Avalos 
2244e9778795SPeter Avalos 	if (state->set_maxsize_called) {
2245ee116499SAntonio Huete Jimenez 		logit_f("called twice: old %d new %d",
2246e9778795SPeter Avalos 		    state->max_packet_size, s);
224718de8d7fSPeter Avalos 		return -1;
224818de8d7fSPeter Avalos 	}
224918de8d7fSPeter Avalos 	if (s < 4 * 1024 || s > 1024 * 1024) {
2250ee116499SAntonio Huete Jimenez 		logit_f("bad size %d", s);
225118de8d7fSPeter Avalos 		return -1;
225218de8d7fSPeter Avalos 	}
2253e9778795SPeter Avalos 	state->set_maxsize_called = 1;
2254ee116499SAntonio Huete Jimenez 	debug_f("setting to %d", s);
2255e9778795SPeter Avalos 	state->max_packet_size = s;
225618de8d7fSPeter Avalos 	return s;
225718de8d7fSPeter Avalos }
225818de8d7fSPeter Avalos 
225940c002afSPeter Avalos int
ssh_packet_inc_alive_timeouts(struct ssh * ssh)2260e9778795SPeter Avalos ssh_packet_inc_alive_timeouts(struct ssh *ssh)
226140c002afSPeter Avalos {
2262e9778795SPeter Avalos 	return ++ssh->state->keep_alive_timeouts;
226340c002afSPeter Avalos }
226440c002afSPeter Avalos 
226540c002afSPeter Avalos void
ssh_packet_set_alive_timeouts(struct ssh * ssh,int ka)2266e9778795SPeter Avalos ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
226740c002afSPeter Avalos {
2268e9778795SPeter Avalos 	ssh->state->keep_alive_timeouts = ka;
226940c002afSPeter Avalos }
227040c002afSPeter Avalos 
227140c002afSPeter Avalos u_int
ssh_packet_get_maxsize(struct ssh * ssh)2272e9778795SPeter Avalos ssh_packet_get_maxsize(struct ssh *ssh)
227340c002afSPeter Avalos {
2274e9778795SPeter Avalos 	return ssh->state->max_packet_size;
227518de8d7fSPeter Avalos }
227618de8d7fSPeter Avalos 
227718de8d7fSPeter Avalos void
ssh_packet_set_rekey_limits(struct ssh * ssh,u_int64_t bytes,u_int32_t seconds)2278ce74bacaSMatthew Dillon ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, u_int32_t seconds)
227918de8d7fSPeter Avalos {
2280ce74bacaSMatthew Dillon 	debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
2281ce74bacaSMatthew Dillon 	    (unsigned int)seconds);
2282e9778795SPeter Avalos 	ssh->state->rekey_limit = bytes;
2283e9778795SPeter Avalos 	ssh->state->rekey_interval = seconds;
228436e94dc5SPeter Avalos }
228536e94dc5SPeter Avalos 
228636e94dc5SPeter Avalos time_t
ssh_packet_get_rekey_timeout(struct ssh * ssh)2287e9778795SPeter Avalos ssh_packet_get_rekey_timeout(struct ssh *ssh)
228836e94dc5SPeter Avalos {
228936e94dc5SPeter Avalos 	time_t seconds;
229036e94dc5SPeter Avalos 
2291e9778795SPeter Avalos 	seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
229236e94dc5SPeter Avalos 	    monotime();
229336e94dc5SPeter Avalos 	return (seconds <= 0 ? 1 : seconds);
229418de8d7fSPeter Avalos }
229518de8d7fSPeter Avalos 
229618de8d7fSPeter Avalos void
ssh_packet_set_server(struct ssh * ssh)2297e9778795SPeter Avalos ssh_packet_set_server(struct ssh *ssh)
229818de8d7fSPeter Avalos {
2299e9778795SPeter Avalos 	ssh->state->server_side = 1;
2300664f4763Szrj 	ssh->kex->server = 1; /* XXX unify? */
230118de8d7fSPeter Avalos }
230218de8d7fSPeter Avalos 
230318de8d7fSPeter Avalos void
ssh_packet_set_authenticated(struct ssh * ssh)2304e9778795SPeter Avalos ssh_packet_set_authenticated(struct ssh *ssh)
230518de8d7fSPeter Avalos {
2306e9778795SPeter Avalos 	ssh->state->after_authentication = 1;
230740c002afSPeter Avalos }
230840c002afSPeter Avalos 
230940c002afSPeter Avalos void *
ssh_packet_get_input(struct ssh * ssh)2310e9778795SPeter Avalos ssh_packet_get_input(struct ssh *ssh)
231140c002afSPeter Avalos {
2312e9778795SPeter Avalos 	return (void *)ssh->state->input;
231340c002afSPeter Avalos }
231440c002afSPeter Avalos 
231540c002afSPeter Avalos void *
ssh_packet_get_output(struct ssh * ssh)2316e9778795SPeter Avalos ssh_packet_get_output(struct ssh *ssh)
231740c002afSPeter Avalos {
2318e9778795SPeter Avalos 	return (void *)ssh->state->output;
231918de8d7fSPeter Avalos }
232036e94dc5SPeter Avalos 
232136e94dc5SPeter Avalos /* Reset after_authentication and reset compression in post-auth privsep */
2322e9778795SPeter Avalos static int
ssh_packet_set_postauth(struct ssh * ssh)2323e9778795SPeter Avalos ssh_packet_set_postauth(struct ssh *ssh)
232436e94dc5SPeter Avalos {
2325ce74bacaSMatthew Dillon 	int r;
232636e94dc5SPeter Avalos 
232750a69bb5SSascha Wildner 	debug_f("called");
232836e94dc5SPeter Avalos 	/* This was set in net child, but is not visible in user child */
2329e9778795SPeter Avalos 	ssh->state->after_authentication = 1;
2330e9778795SPeter Avalos 	ssh->state->rekeying = 0;
2331ce74bacaSMatthew Dillon 	if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
2332e9778795SPeter Avalos 		return r;
2333e9778795SPeter Avalos 	return 0;
2334e9778795SPeter Avalos }
2335e9778795SPeter Avalos 
2336e9778795SPeter Avalos /* Packet state (de-)serialization for privsep */
2337e9778795SPeter Avalos 
2338e9778795SPeter Avalos /* turn kex into a blob for packet state serialization */
2339e9778795SPeter Avalos static int
kex_to_blob(struct sshbuf * m,struct kex * kex)2340e9778795SPeter Avalos kex_to_blob(struct sshbuf *m, struct kex *kex)
2341e9778795SPeter Avalos {
2342e9778795SPeter Avalos 	int r;
2343e9778795SPeter Avalos 
234450a69bb5SSascha Wildner 	if ((r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2345664f4763Szrj 	    (r = sshbuf_put_cstring(m, kex->hostkey_alg)) != 0 ||
2346e9778795SPeter Avalos 	    (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2347664f4763Szrj 	    (r = sshbuf_put_u32(m, kex->hostkey_nid)) != 0 ||
2348e9778795SPeter Avalos 	    (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2349*ba1276acSMatthew Dillon 	    (r = sshbuf_put_u32(m, kex->kex_strict)) != 0 ||
2350e9778795SPeter Avalos 	    (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2351e9778795SPeter Avalos 	    (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2352664f4763Szrj 	    (r = sshbuf_put_stringb(m, kex->client_version)) != 0 ||
2353664f4763Szrj 	    (r = sshbuf_put_stringb(m, kex->server_version)) != 0 ||
235450a69bb5SSascha Wildner 	    (r = sshbuf_put_stringb(m, kex->session_id)) != 0 ||
2355664f4763Szrj 	    (r = sshbuf_put_u32(m, kex->flags)) != 0)
2356e9778795SPeter Avalos 		return r;
2357e9778795SPeter Avalos 	return 0;
2358e9778795SPeter Avalos }
2359e9778795SPeter Avalos 
2360e9778795SPeter Avalos /* turn key exchange results into a blob for packet state serialization */
2361e9778795SPeter Avalos static int
newkeys_to_blob(struct sshbuf * m,struct ssh * ssh,int mode)2362e9778795SPeter Avalos newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2363e9778795SPeter Avalos {
2364e9778795SPeter Avalos 	struct sshbuf *b;
2365e9778795SPeter Avalos 	struct sshcipher_ctx *cc;
2366e9778795SPeter Avalos 	struct sshcomp *comp;
2367e9778795SPeter Avalos 	struct sshenc *enc;
2368e9778795SPeter Avalos 	struct sshmac *mac;
2369e9778795SPeter Avalos 	struct newkeys *newkey;
2370e9778795SPeter Avalos 	int r;
2371e9778795SPeter Avalos 
2372e9778795SPeter Avalos 	if ((newkey = ssh->state->newkeys[mode]) == NULL)
2373e9778795SPeter Avalos 		return SSH_ERR_INTERNAL_ERROR;
2374e9778795SPeter Avalos 	enc = &newkey->enc;
2375e9778795SPeter Avalos 	mac = &newkey->mac;
2376e9778795SPeter Avalos 	comp = &newkey->comp;
2377ce74bacaSMatthew Dillon 	cc = (mode == MODE_OUT) ? ssh->state->send_context :
2378ce74bacaSMatthew Dillon 	    ssh->state->receive_context;
2379e9778795SPeter Avalos 	if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2380e9778795SPeter Avalos 		return r;
2381e9778795SPeter Avalos 	if ((b = sshbuf_new()) == NULL)
2382e9778795SPeter Avalos 		return SSH_ERR_ALLOC_FAIL;
2383e9778795SPeter Avalos 	if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2384e9778795SPeter Avalos 	    (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2385e9778795SPeter Avalos 	    (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2386e9778795SPeter Avalos 	    (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2387e9778795SPeter Avalos 	    (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2388e9778795SPeter Avalos 		goto out;
2389e9778795SPeter Avalos 	if (cipher_authlen(enc->cipher) == 0) {
2390e9778795SPeter Avalos 		if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2391e9778795SPeter Avalos 		    (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2392e9778795SPeter Avalos 		    (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2393e9778795SPeter Avalos 			goto out;
2394e9778795SPeter Avalos 	}
2395e9778795SPeter Avalos 	if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2396e9778795SPeter Avalos 	    (r = sshbuf_put_cstring(b, comp->name)) != 0)
2397e9778795SPeter Avalos 		goto out;
2398e9778795SPeter Avalos 	r = sshbuf_put_stringb(m, b);
2399e9778795SPeter Avalos  out:
2400e9778795SPeter Avalos 	sshbuf_free(b);
2401e9778795SPeter Avalos 	return r;
2402e9778795SPeter Avalos }
2403e9778795SPeter Avalos 
2404e9778795SPeter Avalos /* serialize packet state into a blob */
2405e9778795SPeter Avalos int
ssh_packet_get_state(struct ssh * ssh,struct sshbuf * m)2406e9778795SPeter Avalos ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2407e9778795SPeter Avalos {
2408e9778795SPeter Avalos 	struct session_state *state = ssh->state;
2409ce74bacaSMatthew Dillon 	int r;
2410e9778795SPeter Avalos 
2411e9778795SPeter Avalos 	if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2412e9778795SPeter Avalos 	    (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2413e9778795SPeter Avalos 	    (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2414e9778795SPeter Avalos 	    (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2415e9778795SPeter Avalos 	    (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2416e9778795SPeter Avalos 	    (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2417e9778795SPeter Avalos 	    (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2418e9778795SPeter Avalos 	    (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2419e9778795SPeter Avalos 	    (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2420e9778795SPeter Avalos 	    (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2421e9778795SPeter Avalos 	    (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2422e9778795SPeter Avalos 	    (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2423ce74bacaSMatthew Dillon 	    (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0 ||
2424e9778795SPeter Avalos 	    (r = sshbuf_put_stringb(m, state->input)) != 0 ||
2425e9778795SPeter Avalos 	    (r = sshbuf_put_stringb(m, state->output)) != 0)
2426e9778795SPeter Avalos 		return r;
2427e9778795SPeter Avalos 
2428e9778795SPeter Avalos 	return 0;
2429e9778795SPeter Avalos }
2430e9778795SPeter Avalos 
2431e9778795SPeter Avalos /* restore key exchange results from blob for packet state de-serialization */
2432e9778795SPeter Avalos static int
newkeys_from_blob(struct sshbuf * m,struct ssh * ssh,int mode)2433e9778795SPeter Avalos newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2434e9778795SPeter Avalos {
2435e9778795SPeter Avalos 	struct sshbuf *b = NULL;
2436e9778795SPeter Avalos 	struct sshcomp *comp;
2437e9778795SPeter Avalos 	struct sshenc *enc;
2438e9778795SPeter Avalos 	struct sshmac *mac;
2439e9778795SPeter Avalos 	struct newkeys *newkey = NULL;
2440e9778795SPeter Avalos 	size_t keylen, ivlen, maclen;
2441e9778795SPeter Avalos 	int r;
2442e9778795SPeter Avalos 
2443e9778795SPeter Avalos 	if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2444e9778795SPeter Avalos 		r = SSH_ERR_ALLOC_FAIL;
2445e9778795SPeter Avalos 		goto out;
2446e9778795SPeter Avalos 	}
2447e9778795SPeter Avalos 	if ((r = sshbuf_froms(m, &b)) != 0)
2448e9778795SPeter Avalos 		goto out;
2449e9778795SPeter Avalos #ifdef DEBUG_PK
2450e9778795SPeter Avalos 	sshbuf_dump(b, stderr);
2451e9778795SPeter Avalos #endif
2452e9778795SPeter Avalos 	enc = &newkey->enc;
2453e9778795SPeter Avalos 	mac = &newkey->mac;
2454e9778795SPeter Avalos 	comp = &newkey->comp;
2455e9778795SPeter Avalos 
2456e9778795SPeter Avalos 	if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2457e9778795SPeter Avalos 	    (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2458e9778795SPeter Avalos 	    (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2459e9778795SPeter Avalos 	    (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2460e9778795SPeter Avalos 	    (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2461e9778795SPeter Avalos 		goto out;
2462ce74bacaSMatthew Dillon 	if ((enc->cipher = cipher_by_name(enc->name)) == NULL) {
2463ce74bacaSMatthew Dillon 		r = SSH_ERR_INVALID_FORMAT;
2464ce74bacaSMatthew Dillon 		goto out;
2465ce74bacaSMatthew Dillon 	}
2466e9778795SPeter Avalos 	if (cipher_authlen(enc->cipher) == 0) {
2467e9778795SPeter Avalos 		if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2468e9778795SPeter Avalos 			goto out;
2469e9778795SPeter Avalos 		if ((r = mac_setup(mac, mac->name)) != 0)
2470e9778795SPeter Avalos 			goto out;
2471e9778795SPeter Avalos 		if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2472e9778795SPeter Avalos 		    (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2473e9778795SPeter Avalos 			goto out;
2474e9778795SPeter Avalos 		if (maclen > mac->key_len) {
2475e9778795SPeter Avalos 			r = SSH_ERR_INVALID_FORMAT;
2476e9778795SPeter Avalos 			goto out;
2477e9778795SPeter Avalos 		}
2478e9778795SPeter Avalos 		mac->key_len = maclen;
2479e9778795SPeter Avalos 	}
2480e9778795SPeter Avalos 	if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2481e9778795SPeter Avalos 	    (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2482e9778795SPeter Avalos 		goto out;
2483e9778795SPeter Avalos 	if (sshbuf_len(b) != 0) {
2484e9778795SPeter Avalos 		r = SSH_ERR_INVALID_FORMAT;
2485e9778795SPeter Avalos 		goto out;
2486e9778795SPeter Avalos 	}
2487e9778795SPeter Avalos 	enc->key_len = keylen;
2488e9778795SPeter Avalos 	enc->iv_len = ivlen;
2489e9778795SPeter Avalos 	ssh->kex->newkeys[mode] = newkey;
2490e9778795SPeter Avalos 	newkey = NULL;
2491e9778795SPeter Avalos 	r = 0;
2492e9778795SPeter Avalos  out:
2493e9778795SPeter Avalos 	free(newkey);
2494e9778795SPeter Avalos 	sshbuf_free(b);
2495e9778795SPeter Avalos 	return r;
2496e9778795SPeter Avalos }
2497e9778795SPeter Avalos 
2498e9778795SPeter Avalos /* restore kex from blob for packet state de-serialization */
2499e9778795SPeter Avalos static int
kex_from_blob(struct sshbuf * m,struct kex ** kexp)2500e9778795SPeter Avalos kex_from_blob(struct sshbuf *m, struct kex **kexp)
2501e9778795SPeter Avalos {
2502e9778795SPeter Avalos 	struct kex *kex;
2503e9778795SPeter Avalos 	int r;
2504e9778795SPeter Avalos 
2505664f4763Szrj 	if ((kex = kex_new()) == NULL)
2506664f4763Szrj 		return SSH_ERR_ALLOC_FAIL;
250750a69bb5SSascha Wildner 	if ((r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2508664f4763Szrj 	    (r = sshbuf_get_cstring(m, &kex->hostkey_alg, NULL)) != 0 ||
2509e9778795SPeter Avalos 	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2510664f4763Szrj 	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_nid)) != 0 ||
2511e9778795SPeter Avalos 	    (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2512*ba1276acSMatthew Dillon 	    (r = sshbuf_get_u32(m, &kex->kex_strict)) != 0 ||
2513e9778795SPeter Avalos 	    (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2514e9778795SPeter Avalos 	    (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2515664f4763Szrj 	    (r = sshbuf_get_stringb(m, kex->client_version)) != 0 ||
2516664f4763Szrj 	    (r = sshbuf_get_stringb(m, kex->server_version)) != 0 ||
251750a69bb5SSascha Wildner 	    (r = sshbuf_get_stringb(m, kex->session_id)) != 0 ||
2518664f4763Szrj 	    (r = sshbuf_get_u32(m, &kex->flags)) != 0)
2519e9778795SPeter Avalos 		goto out;
2520e9778795SPeter Avalos 	kex->server = 1;
2521e9778795SPeter Avalos 	kex->done = 1;
2522e9778795SPeter Avalos 	r = 0;
2523e9778795SPeter Avalos  out:
2524e9778795SPeter Avalos 	if (r != 0 || kexp == NULL) {
2525664f4763Szrj 		kex_free(kex);
2526e9778795SPeter Avalos 		if (kexp != NULL)
2527e9778795SPeter Avalos 			*kexp = NULL;
2528e9778795SPeter Avalos 	} else {
2529664f4763Szrj 		kex_free(*kexp);
2530e9778795SPeter Avalos 		*kexp = kex;
2531e9778795SPeter Avalos 	}
2532e9778795SPeter Avalos 	return r;
2533e9778795SPeter Avalos }
2534e9778795SPeter Avalos 
2535e9778795SPeter Avalos /*
2536e9778795SPeter Avalos  * Restore packet state from content of blob 'm' (de-serialization).
2537e9778795SPeter Avalos  * Note that 'm' will be partially consumed on parsing or any other errors.
2538e9778795SPeter Avalos  */
2539e9778795SPeter Avalos int
ssh_packet_set_state(struct ssh * ssh,struct sshbuf * m)2540e9778795SPeter Avalos ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2541e9778795SPeter Avalos {
2542e9778795SPeter Avalos 	struct session_state *state = ssh->state;
2543ce74bacaSMatthew Dillon 	const u_char *input, *output;
2544ce74bacaSMatthew Dillon 	size_t ilen, olen;
2545e9778795SPeter Avalos 	int r;
2546e9778795SPeter Avalos 
2547e9778795SPeter Avalos 	if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2548e9778795SPeter Avalos 	    (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2549e9778795SPeter Avalos 	    (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2550e9778795SPeter Avalos 	    (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2551e9778795SPeter Avalos 	    (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2552e9778795SPeter Avalos 	    (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2553e9778795SPeter Avalos 	    (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2554e9778795SPeter Avalos 	    (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2555e9778795SPeter Avalos 	    (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2556e9778795SPeter Avalos 	    (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2557e9778795SPeter Avalos 	    (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2558e9778795SPeter Avalos 	    (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2559e9778795SPeter Avalos 	    (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2560e9778795SPeter Avalos 		return r;
2561e9778795SPeter Avalos 	/*
256250a69bb5SSascha Wildner 	 * We set the time here so that in post-auth privsep child we
2563e9778795SPeter Avalos 	 * count from the completion of the authentication.
2564e9778795SPeter Avalos 	 */
2565e9778795SPeter Avalos 	state->rekey_time = monotime();
2566e9778795SPeter Avalos 	/* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2567e9778795SPeter Avalos 	if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2568e9778795SPeter Avalos 	    (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2569e9778795SPeter Avalos 		return r;
2570e9778795SPeter Avalos 
2571ce74bacaSMatthew Dillon 	if ((r = ssh_packet_set_postauth(ssh)) != 0)
2572e9778795SPeter Avalos 		return r;
2573e9778795SPeter Avalos 
2574e9778795SPeter Avalos 	sshbuf_reset(state->input);
2575e9778795SPeter Avalos 	sshbuf_reset(state->output);
2576e9778795SPeter Avalos 	if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2577e9778795SPeter Avalos 	    (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2578e9778795SPeter Avalos 	    (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2579e9778795SPeter Avalos 	    (r = sshbuf_put(state->output, output, olen)) != 0)
2580e9778795SPeter Avalos 		return r;
2581e9778795SPeter Avalos 
2582e9778795SPeter Avalos 	if (sshbuf_len(m))
2583e9778795SPeter Avalos 		return SSH_ERR_INVALID_FORMAT;
258450a69bb5SSascha Wildner 	debug3_f("done");
2585e9778795SPeter Avalos 	return 0;
2586e9778795SPeter Avalos }
2587e9778795SPeter Avalos 
2588e9778795SPeter Avalos /* NEW API */
2589e9778795SPeter Avalos 
2590e9778795SPeter Avalos /* put data to the outgoing packet */
2591e9778795SPeter Avalos 
2592e9778795SPeter Avalos int
sshpkt_put(struct ssh * ssh,const void * v,size_t len)2593e9778795SPeter Avalos sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2594e9778795SPeter Avalos {
2595e9778795SPeter Avalos 	return sshbuf_put(ssh->state->outgoing_packet, v, len);
2596e9778795SPeter Avalos }
2597e9778795SPeter Avalos 
2598e9778795SPeter Avalos int
sshpkt_putb(struct ssh * ssh,const struct sshbuf * b)2599e9778795SPeter Avalos sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2600e9778795SPeter Avalos {
2601e9778795SPeter Avalos 	return sshbuf_putb(ssh->state->outgoing_packet, b);
2602e9778795SPeter Avalos }
2603e9778795SPeter Avalos 
2604e9778795SPeter Avalos int
sshpkt_put_u8(struct ssh * ssh,u_char val)2605e9778795SPeter Avalos sshpkt_put_u8(struct ssh *ssh, u_char val)
2606e9778795SPeter Avalos {
2607e9778795SPeter Avalos 	return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2608e9778795SPeter Avalos }
2609e9778795SPeter Avalos 
2610e9778795SPeter Avalos int
sshpkt_put_u32(struct ssh * ssh,u_int32_t val)2611e9778795SPeter Avalos sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2612e9778795SPeter Avalos {
2613e9778795SPeter Avalos 	return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2614e9778795SPeter Avalos }
2615e9778795SPeter Avalos 
2616e9778795SPeter Avalos int
sshpkt_put_u64(struct ssh * ssh,u_int64_t val)2617e9778795SPeter Avalos sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2618e9778795SPeter Avalos {
2619e9778795SPeter Avalos 	return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2620e9778795SPeter Avalos }
2621e9778795SPeter Avalos 
2622e9778795SPeter Avalos int
sshpkt_put_string(struct ssh * ssh,const void * v,size_t len)2623e9778795SPeter Avalos sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2624e9778795SPeter Avalos {
2625e9778795SPeter Avalos 	return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2626e9778795SPeter Avalos }
2627e9778795SPeter Avalos 
2628e9778795SPeter Avalos int
sshpkt_put_cstring(struct ssh * ssh,const void * v)2629e9778795SPeter Avalos sshpkt_put_cstring(struct ssh *ssh, const void *v)
2630e9778795SPeter Avalos {
2631e9778795SPeter Avalos 	return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2632e9778795SPeter Avalos }
2633e9778795SPeter Avalos 
2634e9778795SPeter Avalos int
sshpkt_put_stringb(struct ssh * ssh,const struct sshbuf * v)2635e9778795SPeter Avalos sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2636e9778795SPeter Avalos {
2637e9778795SPeter Avalos 	return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2638e9778795SPeter Avalos }
2639e9778795SPeter Avalos 
2640664f4763Szrj int
sshpkt_getb_froms(struct ssh * ssh,struct sshbuf ** valp)2641664f4763Szrj sshpkt_getb_froms(struct ssh *ssh, struct sshbuf **valp)
2642664f4763Szrj {
2643664f4763Szrj 	return sshbuf_froms(ssh->state->incoming_packet, valp);
2644664f4763Szrj }
2645664f4763Szrj 
2646e9778795SPeter Avalos #ifdef WITH_OPENSSL
2647e9778795SPeter Avalos #ifdef OPENSSL_HAS_ECC
2648e9778795SPeter Avalos int
sshpkt_put_ec(struct ssh * ssh,const EC_POINT * v,const EC_GROUP * g)2649e9778795SPeter Avalos sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2650e9778795SPeter Avalos {
2651e9778795SPeter Avalos 	return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2652e9778795SPeter Avalos }
2653e9778795SPeter Avalos #endif /* OPENSSL_HAS_ECC */
2654e9778795SPeter Avalos 
2655e9778795SPeter Avalos 
2656e9778795SPeter Avalos int
sshpkt_put_bignum2(struct ssh * ssh,const BIGNUM * v)2657e9778795SPeter Avalos sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2658e9778795SPeter Avalos {
2659e9778795SPeter Avalos 	return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2660e9778795SPeter Avalos }
2661e9778795SPeter Avalos #endif /* WITH_OPENSSL */
2662e9778795SPeter Avalos 
2663e9778795SPeter Avalos /* fetch data from the incoming packet */
2664e9778795SPeter Avalos 
2665e9778795SPeter Avalos int
sshpkt_get(struct ssh * ssh,void * valp,size_t len)2666e9778795SPeter Avalos sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2667e9778795SPeter Avalos {
2668e9778795SPeter Avalos 	return sshbuf_get(ssh->state->incoming_packet, valp, len);
2669e9778795SPeter Avalos }
2670e9778795SPeter Avalos 
2671e9778795SPeter Avalos int
sshpkt_get_u8(struct ssh * ssh,u_char * valp)2672e9778795SPeter Avalos sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2673e9778795SPeter Avalos {
2674e9778795SPeter Avalos 	return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2675e9778795SPeter Avalos }
2676e9778795SPeter Avalos 
2677e9778795SPeter Avalos int
sshpkt_get_u32(struct ssh * ssh,u_int32_t * valp)2678e9778795SPeter Avalos sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2679e9778795SPeter Avalos {
2680e9778795SPeter Avalos 	return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2681e9778795SPeter Avalos }
2682e9778795SPeter Avalos 
2683e9778795SPeter Avalos int
sshpkt_get_u64(struct ssh * ssh,u_int64_t * valp)2684e9778795SPeter Avalos sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2685e9778795SPeter Avalos {
2686e9778795SPeter Avalos 	return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2687e9778795SPeter Avalos }
2688e9778795SPeter Avalos 
2689e9778795SPeter Avalos int
sshpkt_get_string(struct ssh * ssh,u_char ** valp,size_t * lenp)2690e9778795SPeter Avalos sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2691e9778795SPeter Avalos {
2692e9778795SPeter Avalos 	return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2693e9778795SPeter Avalos }
2694e9778795SPeter Avalos 
2695e9778795SPeter Avalos int
sshpkt_get_string_direct(struct ssh * ssh,const u_char ** valp,size_t * lenp)2696e9778795SPeter Avalos sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2697e9778795SPeter Avalos {
2698e9778795SPeter Avalos 	return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2699e9778795SPeter Avalos }
2700e9778795SPeter Avalos 
2701e9778795SPeter Avalos int
sshpkt_peek_string_direct(struct ssh * ssh,const u_char ** valp,size_t * lenp)2702ce74bacaSMatthew Dillon sshpkt_peek_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2703ce74bacaSMatthew Dillon {
2704ce74bacaSMatthew Dillon 	return sshbuf_peek_string_direct(ssh->state->incoming_packet, valp, lenp);
2705ce74bacaSMatthew Dillon }
2706ce74bacaSMatthew Dillon 
2707ce74bacaSMatthew Dillon int
sshpkt_get_cstring(struct ssh * ssh,char ** valp,size_t * lenp)2708e9778795SPeter Avalos sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2709e9778795SPeter Avalos {
2710e9778795SPeter Avalos 	return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2711e9778795SPeter Avalos }
2712e9778795SPeter Avalos 
2713e9778795SPeter Avalos #ifdef WITH_OPENSSL
2714e9778795SPeter Avalos #ifdef OPENSSL_HAS_ECC
2715e9778795SPeter Avalos int
sshpkt_get_ec(struct ssh * ssh,EC_POINT * v,const EC_GROUP * g)2716e9778795SPeter Avalos sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2717e9778795SPeter Avalos {
2718e9778795SPeter Avalos 	return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2719e9778795SPeter Avalos }
2720e9778795SPeter Avalos #endif /* OPENSSL_HAS_ECC */
2721e9778795SPeter Avalos 
2722e9778795SPeter Avalos int
sshpkt_get_bignum2(struct ssh * ssh,BIGNUM ** valp)2723664f4763Szrj sshpkt_get_bignum2(struct ssh *ssh, BIGNUM **valp)
2724e9778795SPeter Avalos {
2725664f4763Szrj 	return sshbuf_get_bignum2(ssh->state->incoming_packet, valp);
2726e9778795SPeter Avalos }
2727e9778795SPeter Avalos #endif /* WITH_OPENSSL */
2728e9778795SPeter Avalos 
2729e9778795SPeter Avalos int
sshpkt_get_end(struct ssh * ssh)2730e9778795SPeter Avalos sshpkt_get_end(struct ssh *ssh)
2731e9778795SPeter Avalos {
2732e9778795SPeter Avalos 	if (sshbuf_len(ssh->state->incoming_packet) > 0)
2733e9778795SPeter Avalos 		return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2734e9778795SPeter Avalos 	return 0;
2735e9778795SPeter Avalos }
2736e9778795SPeter Avalos 
2737e9778795SPeter Avalos const u_char *
sshpkt_ptr(struct ssh * ssh,size_t * lenp)2738e9778795SPeter Avalos sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2739e9778795SPeter Avalos {
2740e9778795SPeter Avalos 	if (lenp != NULL)
2741e9778795SPeter Avalos 		*lenp = sshbuf_len(ssh->state->incoming_packet);
2742e9778795SPeter Avalos 	return sshbuf_ptr(ssh->state->incoming_packet);
2743e9778795SPeter Avalos }
2744e9778795SPeter Avalos 
2745e9778795SPeter Avalos /* start a new packet */
2746e9778795SPeter Avalos 
2747e9778795SPeter Avalos int
sshpkt_start(struct ssh * ssh,u_char type)2748e9778795SPeter Avalos sshpkt_start(struct ssh *ssh, u_char type)
2749e9778795SPeter Avalos {
2750ce74bacaSMatthew Dillon 	u_char buf[6]; /* u32 packet length, u8 pad len, u8 type */
2751e9778795SPeter Avalos 
2752e9778795SPeter Avalos 	DBG(debug("packet_start[%d]", type));
2753ce74bacaSMatthew Dillon 	memset(buf, 0, sizeof(buf));
2754ce74bacaSMatthew Dillon 	buf[sizeof(buf) - 1] = type;
2755e9778795SPeter Avalos 	sshbuf_reset(ssh->state->outgoing_packet);
2756ce74bacaSMatthew Dillon 	return sshbuf_put(ssh->state->outgoing_packet, buf, sizeof(buf));
2757ce74bacaSMatthew Dillon }
2758ce74bacaSMatthew Dillon 
2759ce74bacaSMatthew Dillon static int
ssh_packet_send_mux(struct ssh * ssh)2760ce74bacaSMatthew Dillon ssh_packet_send_mux(struct ssh *ssh)
2761ce74bacaSMatthew Dillon {
2762ce74bacaSMatthew Dillon 	struct session_state *state = ssh->state;
2763ce74bacaSMatthew Dillon 	u_char type, *cp;
2764ce74bacaSMatthew Dillon 	size_t len;
2765ce74bacaSMatthew Dillon 	int r;
2766ce74bacaSMatthew Dillon 
2767ce74bacaSMatthew Dillon 	if (ssh->kex)
2768ce74bacaSMatthew Dillon 		return SSH_ERR_INTERNAL_ERROR;
2769ce74bacaSMatthew Dillon 	len = sshbuf_len(state->outgoing_packet);
2770ce74bacaSMatthew Dillon 	if (len < 6)
2771ce74bacaSMatthew Dillon 		return SSH_ERR_INTERNAL_ERROR;
2772ce74bacaSMatthew Dillon 	cp = sshbuf_mutable_ptr(state->outgoing_packet);
2773ce74bacaSMatthew Dillon 	type = cp[5];
2774ce74bacaSMatthew Dillon 	if (ssh_packet_log_type(type))
277550a69bb5SSascha Wildner 		debug3_f("type %u", type);
2776ce74bacaSMatthew Dillon 	/* drop everything, but the connection protocol */
2777ce74bacaSMatthew Dillon 	if (type >= SSH2_MSG_CONNECTION_MIN &&
2778ce74bacaSMatthew Dillon 	    type <= SSH2_MSG_CONNECTION_MAX) {
2779ce74bacaSMatthew Dillon 		POKE_U32(cp, len - 4);
2780ce74bacaSMatthew Dillon 		if ((r = sshbuf_putb(state->output,
2781ce74bacaSMatthew Dillon 		    state->outgoing_packet)) != 0)
2782ce74bacaSMatthew Dillon 			return r;
2783ce74bacaSMatthew Dillon 		/* sshbuf_dump(state->output, stderr); */
2784ce74bacaSMatthew Dillon 	}
2785ce74bacaSMatthew Dillon 	sshbuf_reset(state->outgoing_packet);
2786ce74bacaSMatthew Dillon 	return 0;
2787ce74bacaSMatthew Dillon }
2788ce74bacaSMatthew Dillon 
2789ce74bacaSMatthew Dillon /*
2790ce74bacaSMatthew Dillon  * 9.2.  Ignored Data Message
2791ce74bacaSMatthew Dillon  *
2792ce74bacaSMatthew Dillon  *   byte      SSH_MSG_IGNORE
2793ce74bacaSMatthew Dillon  *   string    data
2794ce74bacaSMatthew Dillon  *
2795ce74bacaSMatthew Dillon  * All implementations MUST understand (and ignore) this message at any
2796ce74bacaSMatthew Dillon  * time (after receiving the protocol version). No implementation is
2797ce74bacaSMatthew Dillon  * required to send them. This message can be used as an additional
2798ce74bacaSMatthew Dillon  * protection measure against advanced traffic analysis techniques.
2799ce74bacaSMatthew Dillon  */
2800ce74bacaSMatthew Dillon int
sshpkt_msg_ignore(struct ssh * ssh,u_int nbytes)2801ce74bacaSMatthew Dillon sshpkt_msg_ignore(struct ssh *ssh, u_int nbytes)
2802ce74bacaSMatthew Dillon {
2803ce74bacaSMatthew Dillon 	u_int32_t rnd = 0;
2804ce74bacaSMatthew Dillon 	int r;
2805ce74bacaSMatthew Dillon 	u_int i;
2806ce74bacaSMatthew Dillon 
2807ce74bacaSMatthew Dillon 	if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2808ce74bacaSMatthew Dillon 	    (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2809ce74bacaSMatthew Dillon 		return r;
2810ce74bacaSMatthew Dillon 	for (i = 0; i < nbytes; i++) {
2811ce74bacaSMatthew Dillon 		if (i % 4 == 0)
2812ce74bacaSMatthew Dillon 			rnd = arc4random();
2813ce74bacaSMatthew Dillon 		if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2814ce74bacaSMatthew Dillon 			return r;
2815ce74bacaSMatthew Dillon 		rnd >>= 8;
2816ce74bacaSMatthew Dillon 	}
2817ce74bacaSMatthew Dillon 	return 0;
2818e9778795SPeter Avalos }
2819e9778795SPeter Avalos 
2820e9778795SPeter Avalos /* send it */
2821e9778795SPeter Avalos 
2822e9778795SPeter Avalos int
sshpkt_send(struct ssh * ssh)2823e9778795SPeter Avalos sshpkt_send(struct ssh *ssh)
2824e9778795SPeter Avalos {
2825ce74bacaSMatthew Dillon 	if (ssh->state && ssh->state->mux)
2826ce74bacaSMatthew Dillon 		return ssh_packet_send_mux(ssh);
2827e9778795SPeter Avalos 	return ssh_packet_send2(ssh);
2828e9778795SPeter Avalos }
2829e9778795SPeter Avalos 
2830e9778795SPeter Avalos int
sshpkt_disconnect(struct ssh * ssh,const char * fmt,...)2831e9778795SPeter Avalos sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
2832e9778795SPeter Avalos {
2833e9778795SPeter Avalos 	char buf[1024];
2834e9778795SPeter Avalos 	va_list args;
2835e9778795SPeter Avalos 	int r;
2836e9778795SPeter Avalos 
2837e9778795SPeter Avalos 	va_start(args, fmt);
2838e9778795SPeter Avalos 	vsnprintf(buf, sizeof(buf), fmt, args);
2839e9778795SPeter Avalos 	va_end(args);
2840e9778795SPeter Avalos 
2841*ba1276acSMatthew Dillon 	debug2_f("sending SSH2_MSG_DISCONNECT: %s", buf);
2842e9778795SPeter Avalos 	if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
2843e9778795SPeter Avalos 	    (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
2844e9778795SPeter Avalos 	    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2845e9778795SPeter Avalos 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2846e9778795SPeter Avalos 	    (r = sshpkt_send(ssh)) != 0)
2847e9778795SPeter Avalos 		return r;
2848e9778795SPeter Avalos 	return 0;
2849e9778795SPeter Avalos }
2850e9778795SPeter Avalos 
2851e9778795SPeter Avalos /* roundup current message to pad bytes */
2852e9778795SPeter Avalos int
sshpkt_add_padding(struct ssh * ssh,u_char pad)2853e9778795SPeter Avalos sshpkt_add_padding(struct ssh *ssh, u_char pad)
2854e9778795SPeter Avalos {
2855e9778795SPeter Avalos 	ssh->state->extra_pad = pad;
2856e9778795SPeter Avalos 	return 0;
285736e94dc5SPeter Avalos }
2858