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