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