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