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