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