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