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