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