xref: /netbsd-src/crypto/external/bsd/openssh/dist/packet.c (revision 9469f4f13c84743995b7d51c506f9c9849ba30de)
1 /*	$NetBSD: packet.c,v 1.52 2024/09/24 21:32:18 christos Exp $	*/
2 /* $OpenBSD: packet.c,v 1.317 2024/08/23 04:51:00 deraadt 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.52 2024/09/24 21:32:18 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_DELAYED && state->after_authentication)) &&
1001 	    comp->enabled == 0) {
1002 		if ((r = ssh_packet_init_compression(ssh)) < 0)
1003 			return r;
1004 		if (mode == MODE_OUT) {
1005 			if ((r = start_compression_out(ssh, 6)) != 0)
1006 				return r;
1007 		} else {
1008 			if ((r = start_compression_in(ssh)) != 0)
1009 				return r;
1010 		}
1011 		comp->enabled = 1;
1012 	}
1013 	/*
1014 	 * The 2^(blocksize*2) limit is too expensive for 3DES,
1015 	 * so enforce a 1GB limit for small blocksizes.
1016 	 * See RFC4344 section 3.2.
1017 	 */
1018 	if (enc->block_size >= 16)
1019 		*max_blocks = (u_int64_t)1 << (enc->block_size*2);
1020 	else
1021 		*max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1022 	if (state->rekey_limit)
1023 		*max_blocks = MINIMUM(*max_blocks,
1024 		    state->rekey_limit / enc->block_size);
1025 	debug("rekey %s after %llu blocks", dir,
1026 	    (unsigned long long)*max_blocks);
1027 	return 0;
1028 }
1029 
1030 #define MAX_PACKETS	(1U<<31)
1031 static int
1032 ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
1033 {
1034 	struct session_state *state = ssh->state;
1035 	u_int32_t out_blocks;
1036 
1037 	/* XXX client can't cope with rekeying pre-auth */
1038 	if (!state->after_authentication)
1039 		return 0;
1040 
1041 	/* Haven't keyed yet or KEX in progress. */
1042 	if (ssh_packet_is_rekeying(ssh))
1043 		return 0;
1044 
1045 	/* Peer can't rekey */
1046 	if (ssh->compat & SSH_BUG_NOREKEY)
1047 		return 0;
1048 
1049 	/*
1050 	 * Permit one packet in or out per rekey - this allows us to
1051 	 * make progress when rekey limits are very small.
1052 	 */
1053 	if (state->p_send.packets == 0 && state->p_read.packets == 0)
1054 		return 0;
1055 
1056 	/* Time-based rekeying */
1057 	if (state->rekey_interval != 0 &&
1058 	    (int64_t)state->rekey_time + state->rekey_interval <= monotime())
1059 		return 1;
1060 
1061 	/*
1062 	 * Always rekey when MAX_PACKETS sent in either direction
1063 	 * As per RFC4344 section 3.1 we do this after 2^31 packets.
1064 	 */
1065 	if (state->p_send.packets > MAX_PACKETS ||
1066 	    state->p_read.packets > MAX_PACKETS)
1067 		return 1;
1068 
1069 	/* Rekey after (cipher-specific) maximum blocks */
1070 	out_blocks = ROUNDUP(outbound_packet_len,
1071 	    state->newkeys[MODE_OUT]->enc.block_size);
1072 	return (state->max_blocks_out &&
1073 	    (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
1074 	    (state->max_blocks_in &&
1075 	    (state->p_read.blocks > state->max_blocks_in));
1076 }
1077 
1078 int
1079 ssh_packet_check_rekey(struct ssh *ssh)
1080 {
1081 	if (!ssh_packet_need_rekeying(ssh, 0))
1082 		return 0;
1083 	debug3_f("rekex triggered");
1084 	return kex_start_rekex(ssh);
1085 }
1086 
1087 /*
1088  * Delayed compression for SSH2 is enabled after authentication:
1089  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1090  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
1091  */
1092 static int
1093 ssh_packet_enable_delayed_compress(struct ssh *ssh)
1094 {
1095 	struct session_state *state = ssh->state;
1096 	struct sshcomp *comp = NULL;
1097 	int r, mode;
1098 
1099 	/*
1100 	 * Remember that we are past the authentication step, so rekeying
1101 	 * with COMP_DELAYED will turn on compression immediately.
1102 	 */
1103 	state->after_authentication = 1;
1104 	for (mode = 0; mode < MODE_MAX; mode++) {
1105 		/* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1106 		if (state->newkeys[mode] == NULL)
1107 			continue;
1108 		comp = &state->newkeys[mode]->comp;
1109 		if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1110 			if ((r = ssh_packet_init_compression(ssh)) != 0)
1111 				return r;
1112 			if (mode == MODE_OUT) {
1113 				if ((r = start_compression_out(ssh, 6)) != 0)
1114 					return r;
1115 			} else {
1116 				if ((r = start_compression_in(ssh)) != 0)
1117 					return r;
1118 			}
1119 			comp->enabled = 1;
1120 		}
1121 	}
1122 	return 0;
1123 }
1124 
1125 /* Used to mute debug logging for noisy packet types */
1126 int
1127 ssh_packet_log_type(u_char type)
1128 {
1129 	switch (type) {
1130 	case SSH2_MSG_PING:
1131 	case SSH2_MSG_PONG:
1132 	case SSH2_MSG_CHANNEL_DATA:
1133 	case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1134 	case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1135 		return 0;
1136 	default:
1137 		return 1;
1138 	}
1139 }
1140 
1141 /*
1142  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
1143  */
1144 int
1145 ssh_packet_send2_wrapped(struct ssh *ssh)
1146 {
1147 	struct session_state *state = ssh->state;
1148 	u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1149 	u_char tmp, padlen, pad = 0;
1150 	u_int authlen = 0, aadlen = 0;
1151 	u_int len;
1152 	struct sshenc *enc   = NULL;
1153 	struct sshmac *mac   = NULL;
1154 	struct sshcomp *comp = NULL;
1155 	int r, block_size;
1156 
1157 	if (state->newkeys[MODE_OUT] != NULL) {
1158 		enc  = &state->newkeys[MODE_OUT]->enc;
1159 		mac  = &state->newkeys[MODE_OUT]->mac;
1160 		comp = &state->newkeys[MODE_OUT]->comp;
1161 		/* disable mac for authenticated encryption */
1162 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
1163 			mac = NULL;
1164 	}
1165 	block_size = enc ? enc->block_size : 8;
1166 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1167 
1168 	type = (sshbuf_ptr(state->outgoing_packet))[5];
1169 	if (ssh_packet_log_type(type))
1170 		debug3("send packet: type %u", type);
1171 #ifdef PACKET_DEBUG
1172 	fprintf(stderr, "plain:     ");
1173 	sshbuf_dump(state->outgoing_packet, stderr);
1174 #endif
1175 
1176 	if (comp && comp->enabled) {
1177 		len = sshbuf_len(state->outgoing_packet);
1178 		/* skip header, compress only payload */
1179 		if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
1180 			goto out;
1181 		sshbuf_reset(state->compression_buffer);
1182 		if ((r = compress_buffer(ssh, state->outgoing_packet,
1183 		    state->compression_buffer)) != 0)
1184 			goto out;
1185 		sshbuf_reset(state->outgoing_packet);
1186 		if ((r = sshbuf_put(state->outgoing_packet,
1187 		    "\0\0\0\0\0", 5)) != 0 ||
1188 		    (r = sshbuf_putb(state->outgoing_packet,
1189 		    state->compression_buffer)) != 0)
1190 			goto out;
1191 		DBG(debug("compression: raw %d compressed %zd", len,
1192 		    sshbuf_len(state->outgoing_packet)));
1193 	}
1194 
1195 	/* sizeof (packet_len + pad_len + payload) */
1196 	len = sshbuf_len(state->outgoing_packet);
1197 
1198 	/*
1199 	 * calc size of padding, alloc space, get random data,
1200 	 * minimum padding is 4 bytes
1201 	 */
1202 	len -= aadlen; /* packet length is not encrypted for EtM modes */
1203 	padlen = block_size - (len % block_size);
1204 	if (padlen < 4)
1205 		padlen += block_size;
1206 	if (state->extra_pad) {
1207 		tmp = state->extra_pad;
1208 		state->extra_pad =
1209 		    ROUNDUP(state->extra_pad, block_size);
1210 		/* check if roundup overflowed */
1211 		if (state->extra_pad < tmp)
1212 			return SSH_ERR_INVALID_ARGUMENT;
1213 		tmp = (len + padlen) % state->extra_pad;
1214 		/* Check whether pad calculation below will underflow */
1215 		if (tmp > state->extra_pad)
1216 			return SSH_ERR_INVALID_ARGUMENT;
1217 		pad = state->extra_pad - tmp;
1218 		DBG(debug3_f("adding %d (len %d padlen %d extra_pad %d)",
1219 		    pad, len, padlen, state->extra_pad));
1220 		tmp = padlen;
1221 		padlen += pad;
1222 		/* Check whether padlen calculation overflowed */
1223 		if (padlen < tmp)
1224 			return SSH_ERR_INVALID_ARGUMENT; /* overflow */
1225 		state->extra_pad = 0;
1226 	}
1227 	if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
1228 		goto out;
1229 	if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
1230 		/* random padding */
1231 		arc4random_buf(cp, padlen);
1232 	} else {
1233 		/* clear padding */
1234 		explicit_bzero(cp, padlen);
1235 	}
1236 	/* sizeof (packet_len + pad_len + payload + padding) */
1237 	len = sshbuf_len(state->outgoing_packet);
1238 	cp = sshbuf_mutable_ptr(state->outgoing_packet);
1239 	if (cp == NULL) {
1240 		r = SSH_ERR_INTERNAL_ERROR;
1241 		goto out;
1242 	}
1243 	/* packet_length includes payload, padding and padding length field */
1244 	POKE_U32(cp, len - 4);
1245 	cp[4] = padlen;
1246 	DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
1247 	    len, padlen, aadlen));
1248 
1249 	/* compute MAC over seqnr and packet(length fields, payload, padding) */
1250 	if (mac && mac->enabled && !mac->etm) {
1251 		if ((r = mac_compute(mac, state->p_send.seqnr,
1252 		    sshbuf_ptr(state->outgoing_packet), len,
1253 		    macbuf, sizeof(macbuf))) != 0)
1254 			goto out;
1255 		DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1256 	}
1257 	/* encrypt packet and append to output buffer. */
1258 	if ((r = sshbuf_reserve(state->output,
1259 	    sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
1260 		goto out;
1261 	if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
1262 	    sshbuf_ptr(state->outgoing_packet),
1263 	    len - aadlen, aadlen, authlen)) != 0)
1264 		goto out;
1265 	/* append unencrypted MAC */
1266 	if (mac && mac->enabled) {
1267 		if (mac->etm) {
1268 			/* EtM: compute mac over aadlen + cipher text */
1269 			if ((r = mac_compute(mac, state->p_send.seqnr,
1270 			    cp, len, macbuf, sizeof(macbuf))) != 0)
1271 				goto out;
1272 			DBG(debug("done calc MAC(EtM) out #%d",
1273 			    state->p_send.seqnr));
1274 		}
1275 		if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
1276 			goto out;
1277 	}
1278 #ifdef PACKET_DEBUG
1279 	fprintf(stderr, "encrypted: ");
1280 	sshbuf_dump(state->output, stderr);
1281 #endif
1282 	/* increment sequence number for outgoing packets */
1283 	if (++state->p_send.seqnr == 0) {
1284 		if ((ssh->kex->flags & KEX_INITIAL) != 0) {
1285 			ssh_packet_disconnect(ssh, "outgoing sequence number "
1286 			    "wrapped during initial key exchange");
1287 		}
1288 		logit("outgoing seqnr wraps around");
1289 	}
1290 	if (++state->p_send.packets == 0)
1291 		if (!(ssh->compat & SSH_BUG_NOREKEY))
1292 			return SSH_ERR_NEED_REKEY;
1293 	state->p_send.blocks += len / block_size;
1294 	state->p_send.bytes += len;
1295 	sshbuf_reset(state->outgoing_packet);
1296 
1297 	if (type == SSH2_MSG_NEWKEYS && ssh->kex->kex_strict) {
1298 		debug_f("resetting send seqnr %u", state->p_send.seqnr);
1299 		state->p_send.seqnr = 0;
1300 	}
1301 
1302 	if (type == SSH2_MSG_NEWKEYS)
1303 		r = ssh_set_newkeys(ssh, MODE_OUT);
1304 	else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
1305 		r = ssh_packet_enable_delayed_compress(ssh);
1306 	else
1307 		r = 0;
1308  out:
1309 	if (r < 0)
1310 		return r;
1311 	else
1312 		return len - 4;
1313 }
1314 
1315 /* returns non-zero if the specified packet type is usec by KEX */
1316 static int
1317 ssh_packet_type_is_kex(u_char type)
1318 {
1319 	return
1320 	    type >= SSH2_MSG_TRANSPORT_MIN &&
1321 	    type <= SSH2_MSG_TRANSPORT_MAX &&
1322 	    type != SSH2_MSG_SERVICE_REQUEST &&
1323 	    type != SSH2_MSG_SERVICE_ACCEPT &&
1324 	    type != SSH2_MSG_EXT_INFO;
1325 }
1326 
1327 int
1328 ssh_packet_send2(struct ssh *ssh)
1329 {
1330 	struct session_state *state = ssh->state;
1331 	struct packet *p;
1332 	u_char type;
1333 	int r, need_rekey;
1334 	int packet_length;
1335 
1336 	if (sshbuf_len(state->outgoing_packet) < 6)
1337 		return SSH_ERR_INTERNAL_ERROR;
1338 	type = sshbuf_ptr(state->outgoing_packet)[5];
1339 	need_rekey = !ssh_packet_type_is_kex(type) &&
1340 	    ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1341 
1342 	/*
1343 	 * During rekeying we can only send key exchange messages.
1344 	 * Queue everything else.
1345 	 */
1346 	if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
1347 		if (need_rekey)
1348 			debug3_f("rekex triggered");
1349 		debug("enqueue packet: %u", type);
1350 		p = calloc(1, sizeof(*p));
1351 		if (p == NULL)
1352 			return SSH_ERR_ALLOC_FAIL;
1353 		p->type = type;
1354 		p->payload = state->outgoing_packet;
1355 		TAILQ_INSERT_TAIL(&state->outgoing, p, next);
1356 		state->outgoing_packet = sshbuf_new();
1357 		if (state->outgoing_packet == NULL)
1358 			return SSH_ERR_ALLOC_FAIL;
1359 		if (need_rekey) {
1360 			/*
1361 			 * This packet triggered a rekey, so send the
1362 			 * KEXINIT now.
1363 			 * NB. reenters this function via kex_start_rekex().
1364 			 */
1365 			return kex_start_rekex(ssh);
1366 		}
1367 		return 0;
1368 	}
1369 
1370 	/* rekeying starts with sending KEXINIT */
1371 	if (type == SSH2_MSG_KEXINIT)
1372 		state->rekeying = 1;
1373 
1374 	if ((r = ssh_packet_send2_wrapped(ssh)) < 0)
1375 		return r;
1376 
1377 	packet_length = r;
1378 
1379 	/* after a NEWKEYS message we can send the complete queue */
1380 	if (type == SSH2_MSG_NEWKEYS) {
1381 		state->rekeying = 0;
1382 		state->rekey_time = monotime();
1383 		while ((p = TAILQ_FIRST(&state->outgoing))) {
1384 			type = p->type;
1385 			/*
1386 			 * If this packet triggers a rekex, then skip the
1387 			 * remaining packets in the queue for now.
1388 			 * NB. re-enters this function via kex_start_rekex.
1389 			 */
1390 			if (ssh_packet_need_rekeying(ssh,
1391 			    sshbuf_len(p->payload))) {
1392 				debug3_f("queued packet triggered rekex");
1393 				return kex_start_rekex(ssh);
1394 			}
1395 			debug("dequeue packet: %u", type);
1396 			sshbuf_free(state->outgoing_packet);
1397 			state->outgoing_packet = p->payload;
1398 			TAILQ_REMOVE(&state->outgoing, p, next);
1399 			memset(p, 0, sizeof(*p));
1400 			free(p);
1401 			if ((r = ssh_packet_send2_wrapped(ssh)) < 0)
1402 				return r;
1403 			packet_length += r;
1404 		}
1405 	}
1406 	return packet_length;
1407 }
1408 
1409 /*
1410  * Waits until a packet has been received, and returns its type.  Note that
1411  * no other data is processed until this returns, so this function should not
1412  * be used during the interactive session.
1413  */
1414 
1415 int
1416 ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1417 {
1418 	struct session_state *state = ssh->state;
1419 	int len, r, ms_remain = 0;
1420 	struct pollfd pfd;
1421 	char buf[8192];
1422 	struct timeval start;
1423 	struct timespec timespec, *timespecp = NULL;
1424 
1425 	DBG(debug("packet_read()"));
1426 
1427 	/*
1428 	 * Since we are blocking, ensure that all written packets have
1429 	 * been sent.
1430 	 */
1431 	if ((r = ssh_packet_write_wait(ssh)) < 0)
1432 		goto out;
1433 
1434 	/* Stay in the loop until we have received a complete packet. */
1435 	for (;;) {
1436 		/* Try to read a packet from the buffer. */
1437 		if ((r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p)) != 0)
1438 			break;
1439 		/* If we got a packet, return it. */
1440 		if (*typep != SSH_MSG_NONE)
1441 			break;
1442 		/*
1443 		 * Otherwise, wait for some data to arrive, add it to the
1444 		 * buffer, and try again.
1445 		 */
1446 		pfd.fd = state->connection_in;
1447 		pfd.events = POLLIN;
1448 
1449 		if (state->packet_timeout_ms > 0) {
1450 			ms_remain = state->packet_timeout_ms;
1451 			timespecp = &timespec;
1452 		}
1453 		/* Wait for some data to arrive. */
1454 		for (;;) {
1455 			if (state->packet_timeout_ms > 0) {
1456 				ms_to_timespec(&timespec, ms_remain);
1457 				monotime_tv(&start);
1458 			}
1459 			if ((r = ppoll(&pfd, 1, timespecp, NULL)) >= 0)
1460 				break;
1461 			if (errno != EAGAIN && errno != EINTR) {
1462 				r = SSH_ERR_SYSTEM_ERROR;
1463 				goto out;
1464 			}
1465 			if (state->packet_timeout_ms <= 0)
1466 				continue;
1467 			ms_subtract_diff(&start, &ms_remain);
1468 			if (ms_remain <= 0) {
1469 				r = 0;
1470 				break;
1471 			}
1472 		}
1473 		if (r == 0) {
1474 			r = SSH_ERR_CONN_TIMEOUT;
1475 			goto out;
1476 		}
1477 		/* Read data from the socket. */
1478 		len = read(state->connection_in, buf, sizeof(buf));
1479 		if (len == 0) {
1480 			r = SSH_ERR_CONN_CLOSED;
1481 			goto out;
1482 		}
1483 		if (len == -1) {
1484 			r = SSH_ERR_SYSTEM_ERROR;
1485 			goto out;
1486 		}
1487 
1488 		/* Append it to the buffer. */
1489 		if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1490 			goto out;
1491 	}
1492  out:
1493 	return r;
1494 }
1495 
1496 int
1497 ssh_packet_read(struct ssh *ssh)
1498 {
1499 	u_char type;
1500 	int r;
1501 
1502 	if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
1503 		fatal_fr(r, "read");
1504 	return type;
1505 }
1506 
1507 static int
1508 ssh_packet_read_poll2_mux(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1509 {
1510 	struct session_state *state = ssh->state;
1511 	const u_char *cp;
1512 	size_t need;
1513 	int r;
1514 
1515 	if (ssh->kex)
1516 		return SSH_ERR_INTERNAL_ERROR;
1517 	*typep = SSH_MSG_NONE;
1518 	cp = sshbuf_ptr(state->input);
1519 	if (state->packlen == 0) {
1520 		if (sshbuf_len(state->input) < 4 + 1)
1521 			return 0; /* packet is incomplete */
1522 		state->packlen = PEEK_U32(cp);
1523 		if (state->packlen < 4 + 1 ||
1524 		    state->packlen > PACKET_MAX_SIZE)
1525 			return SSH_ERR_MESSAGE_INCOMPLETE;
1526 	}
1527 	need = state->packlen + 4;
1528 	if (sshbuf_len(state->input) < need)
1529 		return 0; /* packet is incomplete */
1530 	sshbuf_reset(state->incoming_packet);
1531 	if ((r = sshbuf_put(state->incoming_packet, cp + 4,
1532 	    state->packlen)) != 0 ||
1533 	    (r = sshbuf_consume(state->input, need)) != 0 ||
1534 	    (r = sshbuf_get_u8(state->incoming_packet, NULL)) != 0 ||
1535 	    (r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1536 		return r;
1537 	if (ssh_packet_log_type(*typep))
1538 		debug3_f("type %u", *typep);
1539 	/* sshbuf_dump(state->incoming_packet, stderr); */
1540 	/* reset for next packet */
1541 	state->packlen = 0;
1542 	return r;
1543 }
1544 
1545 int
1546 ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1547 {
1548 	struct session_state *state = ssh->state;
1549 	u_int padlen, need;
1550 	u_char *cp;
1551 	u_int maclen, aadlen = 0, authlen = 0, block_size;
1552 	struct sshenc *enc   = NULL;
1553 	struct sshmac *mac   = NULL;
1554 	struct sshcomp *comp = NULL;
1555 	int r;
1556 
1557 	if (state->mux)
1558 		return ssh_packet_read_poll2_mux(ssh, typep, seqnr_p);
1559 
1560 	*typep = SSH_MSG_NONE;
1561 
1562 	if (state->packet_discard)
1563 		return 0;
1564 
1565 	if (state->newkeys[MODE_IN] != NULL) {
1566 		enc  = &state->newkeys[MODE_IN]->enc;
1567 		mac  = &state->newkeys[MODE_IN]->mac;
1568 		comp = &state->newkeys[MODE_IN]->comp;
1569 		/* disable mac for authenticated encryption */
1570 		if ((authlen = cipher_authlen(enc->cipher)) != 0)
1571 			mac = NULL;
1572 	}
1573 	maclen = mac && mac->enabled ? mac->mac_len : 0;
1574 	block_size = enc ? enc->block_size : 8;
1575 	aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1576 
1577 	if (aadlen && state->packlen == 0) {
1578 		if (cipher_get_length(state->receive_context,
1579 		    &state->packlen, state->p_read.seqnr,
1580 		    sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
1581 			return 0;
1582 		if (state->packlen < 1 + 4 ||
1583 		    state->packlen > PACKET_MAX_SIZE) {
1584 #ifdef PACKET_DEBUG
1585 			sshbuf_dump(state->input, stderr);
1586 #endif
1587 			logit("Bad packet length %u.", state->packlen);
1588 			if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
1589 				return r;
1590 			return SSH_ERR_CONN_CORRUPT;
1591 		}
1592 		sshbuf_reset(state->incoming_packet);
1593 	} else if (state->packlen == 0) {
1594 		/*
1595 		 * check if input size is less than the cipher block size,
1596 		 * decrypt first block and extract length of incoming packet
1597 		 */
1598 		if (sshbuf_len(state->input) < block_size)
1599 			return 0;
1600 		sshbuf_reset(state->incoming_packet);
1601 		if ((r = sshbuf_reserve(state->incoming_packet, block_size,
1602 		    &cp)) != 0)
1603 			goto out;
1604 		if ((r = cipher_crypt(state->receive_context,
1605 		    state->p_send.seqnr, cp, sshbuf_ptr(state->input),
1606 		    block_size, 0, 0)) != 0)
1607 			goto out;
1608 		state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
1609 		if (state->packlen < 1 + 4 ||
1610 		    state->packlen > PACKET_MAX_SIZE) {
1611 #ifdef PACKET_DEBUG
1612 			fprintf(stderr, "input: \n");
1613 			sshbuf_dump(state->input, stderr);
1614 			fprintf(stderr, "incoming_packet: \n");
1615 			sshbuf_dump(state->incoming_packet, stderr);
1616 #endif
1617 			logit("Bad packet length %u.", state->packlen);
1618 			return ssh_packet_start_discard(ssh, enc, mac, 0,
1619 			    PACKET_MAX_SIZE);
1620 		}
1621 		if ((r = sshbuf_consume(state->input, block_size)) != 0)
1622 			goto out;
1623 	}
1624 	DBG(debug("input: packet len %u", state->packlen+4));
1625 
1626 	if (aadlen) {
1627 		/* only the payload is encrypted */
1628 		need = state->packlen;
1629 	} else {
1630 		/*
1631 		 * the payload size and the payload are encrypted, but we
1632 		 * have a partial packet of block_size bytes
1633 		 */
1634 		need = 4 + state->packlen - block_size;
1635 	}
1636 	DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
1637 	    " aadlen %d", block_size, need, maclen, authlen, aadlen));
1638 	if (need % block_size != 0) {
1639 		logit("padding error: need %d block %d mod %d",
1640 		    need, block_size, need % block_size);
1641 		return ssh_packet_start_discard(ssh, enc, mac, 0,
1642 		    PACKET_MAX_SIZE - block_size);
1643 	}
1644 	/*
1645 	 * check if the entire packet has been received and
1646 	 * decrypt into incoming_packet:
1647 	 * 'aadlen' bytes are unencrypted, but authenticated.
1648 	 * 'need' bytes are encrypted, followed by either
1649 	 * 'authlen' bytes of authentication tag or
1650 	 * 'maclen' bytes of message authentication code.
1651 	 */
1652 	if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1653 		return 0; /* packet is incomplete */
1654 #ifdef PACKET_DEBUG
1655 	fprintf(stderr, "read_poll enc/full: ");
1656 	sshbuf_dump(state->input, stderr);
1657 #endif
1658 	/* EtM: check mac over encrypted input */
1659 	if (mac && mac->enabled && mac->etm) {
1660 		if ((r = mac_check(mac, state->p_read.seqnr,
1661 		    sshbuf_ptr(state->input), aadlen + need,
1662 		    sshbuf_ptr(state->input) + aadlen + need + authlen,
1663 		    maclen)) != 0) {
1664 			if (r == SSH_ERR_MAC_INVALID)
1665 				logit("Corrupted MAC on input.");
1666 			goto out;
1667 		}
1668 	}
1669 	if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
1670 	    &cp)) != 0)
1671 		goto out;
1672 	if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
1673 	    sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
1674 		goto out;
1675 	if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
1676 		goto out;
1677 	if (mac && mac->enabled) {
1678 		/* Not EtM: check MAC over cleartext */
1679 		if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
1680 		    sshbuf_ptr(state->incoming_packet),
1681 		    sshbuf_len(state->incoming_packet),
1682 		    sshbuf_ptr(state->input), maclen)) != 0) {
1683 			if (r != SSH_ERR_MAC_INVALID)
1684 				goto out;
1685 			logit("Corrupted MAC on input.");
1686 			if (need + block_size > PACKET_MAX_SIZE)
1687 				return SSH_ERR_INTERNAL_ERROR;
1688 			return ssh_packet_start_discard(ssh, enc, mac,
1689 			    sshbuf_len(state->incoming_packet),
1690 			    PACKET_MAX_SIZE - need - block_size);
1691 		}
1692 		/* Remove MAC from input buffer */
1693 		DBG(debug("MAC #%d ok", state->p_read.seqnr));
1694 		if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
1695 			goto out;
1696 	}
1697 
1698 	if (seqnr_p != NULL)
1699 		*seqnr_p = state->p_read.seqnr;
1700 	if (++state->p_read.seqnr == 0) {
1701 		if ((ssh->kex->flags & KEX_INITIAL) != 0) {
1702 			ssh_packet_disconnect(ssh, "incoming sequence number "
1703 			    "wrapped during initial key exchange");
1704 		}
1705 		logit("incoming seqnr wraps around");
1706 	}
1707 	if (++state->p_read.packets == 0)
1708 		if (!(ssh->compat & SSH_BUG_NOREKEY))
1709 			return SSH_ERR_NEED_REKEY;
1710 	state->p_read.blocks += (state->packlen + 4) / block_size;
1711 	state->p_read.bytes += state->packlen + 4;
1712 
1713 	/* get padlen */
1714 	padlen = sshbuf_ptr(state->incoming_packet)[4];
1715 	DBG(debug("input: padlen %d", padlen));
1716 	if (padlen < 4)	{
1717 		if ((r = sshpkt_disconnect(ssh,
1718 		    "Corrupted padlen %d on input.", padlen)) != 0 ||
1719 		    (r = ssh_packet_write_wait(ssh)) < 0)
1720 			return r;
1721 		return SSH_ERR_CONN_CORRUPT;
1722 	}
1723 
1724 	/* skip packet size + padlen, discard padding */
1725 	if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
1726 	    ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
1727 		goto out;
1728 
1729 	DBG(debug("input: len before de-compress %zd",
1730 	    sshbuf_len(state->incoming_packet)));
1731 	if (comp && comp->enabled) {
1732 		sshbuf_reset(state->compression_buffer);
1733 		if ((r = uncompress_buffer(ssh, state->incoming_packet,
1734 		    state->compression_buffer)) != 0)
1735 			goto out;
1736 		sshbuf_reset(state->incoming_packet);
1737 		if ((r = sshbuf_putb(state->incoming_packet,
1738 		    state->compression_buffer)) != 0)
1739 			goto out;
1740 		DBG(debug("input: len after de-compress %zd",
1741 		    sshbuf_len(state->incoming_packet)));
1742 	}
1743 	/*
1744 	 * get packet type, implies consume.
1745 	 * return length of payload (without type field)
1746 	 */
1747 	if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
1748 		goto out;
1749 	if (ssh_packet_log_type(*typep))
1750 		debug3("receive packet: type %u", *typep);
1751 	if (*typep < SSH2_MSG_MIN) {
1752 		if ((r = sshpkt_disconnect(ssh,
1753 		    "Invalid ssh2 packet type: %d", *typep)) != 0 ||
1754 		    (r = ssh_packet_write_wait(ssh)) < 0)
1755 			return r;
1756 		return SSH_ERR_PROTOCOL_ERROR;
1757 	}
1758 	if (state->hook_in != NULL &&
1759 	    (r = state->hook_in(ssh, state->incoming_packet, typep,
1760 	    state->hook_in_ctx)) != 0)
1761 		return r;
1762 	if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1763 		r = ssh_packet_enable_delayed_compress(ssh);
1764 	else
1765 		r = 0;
1766 #ifdef PACKET_DEBUG
1767 	fprintf(stderr, "read/plain[%d]:\r\n", *typep);
1768 	sshbuf_dump(state->incoming_packet, stderr);
1769 #endif
1770 	/* reset for next packet */
1771 	state->packlen = 0;
1772 	if (*typep == SSH2_MSG_NEWKEYS && ssh->kex->kex_strict) {
1773 		debug_f("resetting read seqnr %u", state->p_read.seqnr);
1774 		state->p_read.seqnr = 0;
1775 	}
1776 
1777 	if ((r = ssh_packet_check_rekey(ssh)) != 0)
1778 		return r;
1779  out:
1780 	return r;
1781 }
1782 
1783 int
1784 ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1785 {
1786 	struct session_state *state = ssh->state;
1787 	u_int reason, seqnr;
1788 	int r;
1789 	u_char *msg;
1790 	const u_char *d;
1791 	size_t len;
1792 
1793 	for (;;) {
1794 		msg = NULL;
1795 		r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
1796 		if (r != 0)
1797 			return r;
1798 		if (*typep == 0) {
1799 			/* no message ready */
1800 			return 0;
1801 		}
1802 		state->keep_alive_timeouts = 0;
1803 		DBG(debug("received packet type %d", *typep));
1804 
1805 		/* Always process disconnect messages */
1806 		if (*typep == SSH2_MSG_DISCONNECT) {
1807 			if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
1808 			    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
1809 				return r;
1810 			/* Ignore normal client exit notifications */
1811 			do_log2(ssh->state->server_side &&
1812 			    reason == SSH2_DISCONNECT_BY_APPLICATION ?
1813 			    SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1814 			    "Received disconnect from %s port %d:"
1815 			    "%u: %.400s", ssh_remote_ipaddr(ssh),
1816 			    ssh_remote_port(ssh), reason, msg);
1817 			free(msg);
1818 			return SSH_ERR_DISCONNECTED;
1819 		}
1820 
1821 		/*
1822 		 * Do not implicitly handle any messages here during initial
1823 		 * KEX when in strict mode. They will be need to be allowed
1824 		 * explicitly by the KEX dispatch table or they will generate
1825 		 * protocol errors.
1826 		 */
1827 		if (ssh->kex != NULL &&
1828 		    (ssh->kex->flags & KEX_INITIAL) && ssh->kex->kex_strict)
1829 			return 0;
1830 		/* Implicitly handle transport-level messages */
1831 		switch (*typep) {
1832 		case SSH2_MSG_IGNORE:
1833 			debug3("Received SSH2_MSG_IGNORE");
1834 			break;
1835 		case SSH2_MSG_DEBUG:
1836 			if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
1837 			    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
1838 			    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1839 				free(msg);
1840 				return r;
1841 			}
1842 			debug("Remote: %.900s", msg);
1843 			free(msg);
1844 			break;
1845 		case SSH2_MSG_UNIMPLEMENTED:
1846 			if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
1847 				return r;
1848 			debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
1849 			    seqnr);
1850 			break;
1851 		case SSH2_MSG_PING:
1852 			if ((r = sshpkt_get_string_direct(ssh, &d, &len)) != 0)
1853 				return r;
1854 			DBG(debug("Received SSH2_MSG_PING len %zu", len));
1855 			if ((r = sshpkt_start(ssh, SSH2_MSG_PONG)) != 0 ||
1856 			    (r = sshpkt_put_string(ssh, d, len)) != 0 ||
1857 			    (r = sshpkt_send(ssh)) != 0)
1858 				return r;
1859 			break;
1860 		case SSH2_MSG_PONG:
1861 			if ((r = sshpkt_get_string_direct(ssh,
1862 			    NULL, &len)) != 0)
1863 				return r;
1864 			DBG(debug("Received SSH2_MSG_PONG len %zu", len));
1865 			break;
1866 		default:
1867 			return 0;
1868 		}
1869 	}
1870 }
1871 
1872 /*
1873  * Buffers the supplied input data. This is intended to be used together
1874  * with packet_read_poll().
1875  */
1876 int
1877 ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
1878 {
1879 	struct session_state *state = ssh->state;
1880 	int r;
1881 
1882 	if (state->packet_discard) {
1883 		state->keep_alive_timeouts = 0; /* ?? */
1884 		if (len >= state->packet_discard) {
1885 			if ((r = ssh_packet_stop_discard(ssh)) != 0)
1886 				return r;
1887 		}
1888 		state->packet_discard -= len;
1889 		return 0;
1890 	}
1891 	if ((r = sshbuf_put(state->input, buf, len)) != 0)
1892 		return r;
1893 
1894 	return 0;
1895 }
1896 
1897 /* Reads and buffers data from the specified fd */
1898 int
1899 ssh_packet_process_read(struct ssh *ssh, int fd)
1900 {
1901 	struct session_state *state = ssh->state;
1902 	int r;
1903 	size_t rlen;
1904 
1905 	if ((r = sshbuf_read(fd, state->input, PACKET_MAX_SIZE, &rlen)) != 0)
1906 		return r;
1907 
1908 	if (state->packet_discard) {
1909 		if ((r = sshbuf_consume_end(state->input, rlen)) != 0)
1910 			return r;
1911 		state->keep_alive_timeouts = 0; /* ?? */
1912 		if (rlen >= state->packet_discard) {
1913 			if ((r = ssh_packet_stop_discard(ssh)) != 0)
1914 				return r;
1915 		}
1916 		state->packet_discard -= rlen;
1917 		return 0;
1918 	}
1919 	return 0;
1920 }
1921 
1922 int
1923 ssh_packet_remaining(struct ssh *ssh)
1924 {
1925 	return sshbuf_len(ssh->state->incoming_packet);
1926 }
1927 
1928 /*
1929  * Sends a diagnostic message from the server to the client.  This message
1930  * can be sent at any time (but not while constructing another message). The
1931  * message is printed immediately, but only if the client is being executed
1932  * in verbose mode.  These messages are primarily intended to ease debugging
1933  * authentication problems.   The length of the formatted message must not
1934  * exceed 1024 bytes.  This will automatically call ssh_packet_write_wait.
1935  */
1936 void __attribute__((__format__ (__printf__, 2, 3)))
1937 ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
1938 {
1939 	char buf[1024];
1940 	va_list args;
1941 	int r;
1942 
1943 	if ((ssh->compat & SSH_BUG_DEBUG))
1944 		return;
1945 
1946 	va_start(args, fmt);
1947 	vsnprintf(buf, sizeof(buf), fmt, args);
1948 	va_end(args);
1949 
1950 	debug3("sending debug message: %s", buf);
1951 
1952 	if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
1953 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
1954 	    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
1955 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1956 	    (r = sshpkt_send(ssh)) != 0 ||
1957 	    (r = ssh_packet_write_wait(ssh)) < 0)
1958 		fatal_fr(r, "send DEBUG");
1959 }
1960 
1961 void
1962 sshpkt_fmt_connection_id(struct ssh *ssh, char *s, size_t l)
1963 {
1964 	snprintf(s, l, "%.200s%s%s port %d",
1965 	    ssh->log_preamble ? ssh->log_preamble : "",
1966 	    ssh->log_preamble ? " " : "",
1967 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1968 }
1969 
1970 /*
1971  * Pretty-print connection-terminating errors and exit.
1972  */
1973 static void __attribute__((__format__ (__printf__, 3, 0)))
1974 __attribute__((__noreturn__))
1975 sshpkt_vfatal(struct ssh *ssh, int r, const char *fmt, va_list ap)
1976 {
1977 	char *tag = NULL, remote_id[512];
1978 	int oerrno = errno;
1979 
1980 	sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1981 
1982 	switch (r) {
1983 	case SSH_ERR_CONN_CLOSED:
1984 		ssh_packet_clear_keys(ssh);
1985 		logdie("Connection closed by %s", remote_id);
1986 	case SSH_ERR_CONN_TIMEOUT:
1987 		ssh_packet_clear_keys(ssh);
1988 		logdie("Connection %s %s timed out",
1989 		    ssh->state->server_side ? "from" : "to", remote_id);
1990 	case SSH_ERR_DISCONNECTED:
1991 		ssh_packet_clear_keys(ssh);
1992 		logdie("Disconnected from %s", remote_id);
1993 	case SSH_ERR_SYSTEM_ERROR:
1994 		if (errno == ECONNRESET) {
1995 			ssh_packet_clear_keys(ssh);
1996 			logdie("Connection reset by %s", remote_id);
1997 		}
1998 		/* FALLTHROUGH */
1999 	case SSH_ERR_NO_CIPHER_ALG_MATCH:
2000 	case SSH_ERR_NO_MAC_ALG_MATCH:
2001 	case SSH_ERR_NO_COMPRESS_ALG_MATCH:
2002 	case SSH_ERR_NO_KEX_ALG_MATCH:
2003 	case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
2004 		if (ssh->kex && ssh->kex->failed_choice) {
2005 			ssh_packet_clear_keys(ssh);
2006 			errno = oerrno;
2007 			logdie("Unable to negotiate with %s: %s. "
2008 			    "Their offer: %s", remote_id, ssh_err(r),
2009 			    ssh->kex->failed_choice);
2010 		}
2011 		/* FALLTHROUGH */
2012 	default:
2013 		if (vasprintf(&tag, fmt, ap) == -1) {
2014 			ssh_packet_clear_keys(ssh);
2015 			logdie_f("could not allocate failure message");
2016 		}
2017 		ssh_packet_clear_keys(ssh);
2018 		errno = oerrno;
2019 		logdie_r(r, "%s%sConnection %s %s",
2020 		    tag != NULL ? tag : "", tag != NULL ? ": " : "",
2021 		    ssh->state->server_side ? "from" : "to", remote_id);
2022 	}
2023 }
2024 
2025 void __attribute__((__format__ (__printf__, 3, 4)))
2026 __attribute__((__noreturn__))
2027 sshpkt_fatal(struct ssh *ssh, int r, const char *fmt, ...)
2028 {
2029 	va_list ap;
2030 
2031 	va_start(ap, fmt);
2032 	sshpkt_vfatal(ssh, r, fmt, ap);
2033 	/* NOTREACHED */
2034 	va_end(ap);
2035 	logdie_f("should have exited");
2036 }
2037 
2038 /*
2039  * Logs the error plus constructs and sends a disconnect packet, closes the
2040  * connection, and exits.  This function never returns. The error message
2041  * should not contain a newline.  The length of the formatted message must
2042  * not exceed 1024 bytes.
2043  */
2044 void
2045 ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
2046 {
2047 	char buf[1024], remote_id[512];
2048 	va_list args;
2049 	static int disconnecting = 0;
2050 	int r;
2051 
2052 	if (disconnecting)	/* Guard against recursive invocations. */
2053 		fatal("packet_disconnect called recursively.");
2054 	disconnecting = 1;
2055 
2056 	/*
2057 	 * Format the message.  Note that the caller must make sure the
2058 	 * message is of limited size.
2059 	 */
2060 	sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
2061 	va_start(args, fmt);
2062 	vsnprintf(buf, sizeof(buf), fmt, args);
2063 	va_end(args);
2064 
2065 	/* Display the error locally */
2066 	logit("Disconnecting %s: %.100s", remote_id, buf);
2067 
2068 	/*
2069 	 * Send the disconnect message to the other side, and wait
2070 	 * for it to get sent.
2071 	 */
2072 	if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
2073 		sshpkt_fatal(ssh, r, "%s", __func__);
2074 
2075 	if ((r = ssh_packet_write_wait(ssh)) < 0)
2076 		sshpkt_fatal(ssh, r, "%s", __func__);
2077 
2078 	/* Close the connection. */
2079 	ssh_packet_close(ssh);
2080 	cleanup_exit(254);
2081 }
2082 
2083 /*
2084  * Checks if there is any buffered output, and tries to write some of
2085  * the output.
2086  */
2087 int
2088 ssh_packet_write_poll(struct ssh *ssh)
2089 {
2090 	struct session_state *state = ssh->state;
2091 	int len = sshbuf_len(state->output);
2092 	int r;
2093 
2094 	if (len > 0) {
2095 		len = write(state->connection_out,
2096 		    sshbuf_ptr(state->output), len);
2097 		if (len == -1) {
2098 			if (errno == EINTR || errno == EAGAIN)
2099 				return 0;
2100 			return SSH_ERR_SYSTEM_ERROR;
2101 		}
2102 		if (len == 0)
2103 			return SSH_ERR_CONN_CLOSED;
2104 		if ((r = sshbuf_consume(state->output, len)) < 0)
2105 			return r;
2106 	}
2107 	return len;
2108 }
2109 
2110 /*
2111  * Calls packet_write_poll repeatedly until all pending output data has been
2112  * written.
2113  */
2114 int
2115 ssh_packet_write_wait(struct ssh *ssh)
2116 {
2117 	int ret, r, ms_remain = 0;
2118 	u_int bytes_sent = 0;
2119 	struct timeval start;
2120 	struct timespec timespec, *timespecp = NULL;
2121 	struct session_state *state = ssh->state;
2122 	struct pollfd pfd;
2123 
2124 	if ((r = ssh_packet_write_poll(ssh)) < 0)
2125 		return r;
2126 	bytes_sent += r;
2127 
2128 	while (ssh_packet_have_data_to_write(ssh)) {
2129 		pfd.fd = state->connection_out;
2130 		pfd.events = POLLOUT;
2131 
2132 		if (state->packet_timeout_ms > 0) {
2133 			ms_remain = state->packet_timeout_ms;
2134 			timespecp = &timespec;
2135 		}
2136 		for (;;) {
2137 			if (state->packet_timeout_ms > 0) {
2138 				ms_to_timespec(&timespec, ms_remain);
2139 				monotime_tv(&start);
2140 			}
2141 			if ((ret = ppoll(&pfd, 1, timespecp, NULL)) >= 0)
2142 				break;
2143 			if (errno != EAGAIN && errno != EINTR)
2144 				break;
2145 			if (state->packet_timeout_ms <= 0)
2146 				continue;
2147 			ms_subtract_diff(&start, &ms_remain);
2148 			if (ms_remain <= 0) {
2149 				ret = 0;
2150 				break;
2151 			}
2152 		}
2153 		if (ret == 0)
2154 			return SSH_ERR_CONN_TIMEOUT;
2155 		if ((r = ssh_packet_write_poll(ssh)) < 0)
2156 			return r;
2157 		bytes_sent += r;
2158 	}
2159 	return bytes_sent;
2160 }
2161 
2162 /* Returns true if there is buffered data to write to the connection. */
2163 
2164 int
2165 ssh_packet_have_data_to_write(struct ssh *ssh)
2166 {
2167 	return sshbuf_len(ssh->state->output) != 0;
2168 }
2169 
2170 /* Returns true if there is not too much data to write to the connection. */
2171 
2172 int
2173 ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
2174 {
2175 	if (ssh->state->interactive_mode)
2176 		return sshbuf_len(ssh->state->output) < 16384;
2177 	else
2178 		return sshbuf_len(ssh->state->output) < 128 * 1024;
2179 }
2180 
2181 /*
2182  * returns true when there are at most a few keystrokes of data to write
2183  * and the connection is in interactive mode.
2184  */
2185 
2186 int
2187 ssh_packet_interactive_data_to_write(struct ssh *ssh)
2188 {
2189 	return ssh->state->interactive_mode &&
2190 	    sshbuf_len(ssh->state->output) < 256;
2191 }
2192 
2193 void
2194 ssh_packet_set_tos(struct ssh *ssh, int tos)
2195 {
2196 	if (!ssh_packet_connection_is_on_socket(ssh) || tos == INT_MAX)
2197 		return;
2198 	set_sock_tos(ssh->state->connection_in, tos);
2199 }
2200 
2201 /* Informs that the current session is interactive.  Sets IP flags for that. */
2202 
2203 void
2204 ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
2205 {
2206 	struct session_state *state = ssh->state;
2207 
2208 	if (state->set_interactive_called)
2209 		return;
2210 	state->set_interactive_called = 1;
2211 
2212 	/* Record that we are in interactive mode. */
2213 	state->interactive_mode = interactive;
2214 
2215 	/* Only set socket options if using a socket.  */
2216 	if (!ssh_packet_connection_is_on_socket(ssh))
2217 		return;
2218 	set_nodelay(state->connection_in);
2219 	ssh_packet_set_tos(ssh, interactive ? qos_interactive : qos_bulk);
2220 }
2221 
2222 /* Returns true if the current connection is interactive. */
2223 
2224 int
2225 ssh_packet_is_interactive(struct ssh *ssh)
2226 {
2227 	return ssh->state->interactive_mode;
2228 }
2229 
2230 int
2231 ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
2232 {
2233 	struct session_state *state = ssh->state;
2234 
2235 	if (state->set_maxsize_called) {
2236 		logit_f("called twice: old %d new %d",
2237 		    state->max_packet_size, s);
2238 		return -1;
2239 	}
2240 	if (s < 4 * 1024 || s > 1024 * 1024) {
2241 		logit_f("bad size %d", s);
2242 		return -1;
2243 	}
2244 	state->set_maxsize_called = 1;
2245 	debug_f("setting to %d", s);
2246 	state->max_packet_size = s;
2247 	return s;
2248 }
2249 
2250 int
2251 ssh_packet_inc_alive_timeouts(struct ssh *ssh)
2252 {
2253 	return ++ssh->state->keep_alive_timeouts;
2254 }
2255 
2256 void
2257 ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
2258 {
2259 	ssh->state->keep_alive_timeouts = ka;
2260 }
2261 
2262 u_int
2263 ssh_packet_get_maxsize(struct ssh *ssh)
2264 {
2265 	return ssh->state->max_packet_size;
2266 }
2267 
2268 void
2269 ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, u_int32_t seconds)
2270 {
2271 	debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
2272 	    (unsigned int)seconds);
2273 	ssh->state->rekey_limit = bytes;
2274 	ssh->state->rekey_interval = seconds;
2275 }
2276 
2277 time_t
2278 ssh_packet_get_rekey_timeout(struct ssh *ssh)
2279 {
2280 	time_t seconds;
2281 
2282 	seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
2283 	    monotime();
2284 	return (seconds <= 0 ? 1 : seconds);
2285 }
2286 
2287 void
2288 ssh_packet_set_server(struct ssh *ssh)
2289 {
2290 	ssh->state->server_side = 1;
2291 	ssh->kex->server = 1; /* XXX unify? */
2292 }
2293 
2294 void
2295 ssh_packet_set_authenticated(struct ssh *ssh)
2296 {
2297 	ssh->state->after_authentication = 1;
2298 }
2299 
2300 void *
2301 ssh_packet_get_input(struct ssh *ssh)
2302 {
2303 	return (void *)ssh->state->input;
2304 }
2305 
2306 void *
2307 ssh_packet_get_output(struct ssh *ssh)
2308 {
2309 	return (void *)ssh->state->output;
2310 }
2311 
2312 /* Reset after_authentication and reset compression in post-auth privsep */
2313 static int
2314 ssh_packet_set_postauth(struct ssh *ssh)
2315 {
2316 	int r;
2317 
2318 	debug_f("called");
2319 	/* This was set in net child, but is not visible in user child */
2320 	ssh->state->after_authentication = 1;
2321 	ssh->state->rekeying = 0;
2322 	if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
2323 		return r;
2324 	return 0;
2325 }
2326 
2327 /* Packet state (de-)serialization for privsep */
2328 
2329 /* turn kex into a blob for packet state serialization */
2330 static int
2331 kex_to_blob(struct sshbuf *m, struct kex *kex)
2332 {
2333 	int r;
2334 
2335 	if ((r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
2336 	    (r = sshbuf_put_cstring(m, kex->hostkey_alg)) != 0 ||
2337 	    (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
2338 	    (r = sshbuf_put_u32(m, kex->hostkey_nid)) != 0 ||
2339 	    (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
2340 	    (r = sshbuf_put_u32(m, kex->kex_strict)) != 0 ||
2341 	    (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
2342 	    (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
2343 	    (r = sshbuf_put_stringb(m, kex->client_version)) != 0 ||
2344 	    (r = sshbuf_put_stringb(m, kex->server_version)) != 0 ||
2345 	    (r = sshbuf_put_stringb(m, kex->session_id)) != 0 ||
2346 	    (r = sshbuf_put_u32(m, kex->flags)) != 0)
2347 		return r;
2348 	return 0;
2349 }
2350 
2351 /* turn key exchange results into a blob for packet state serialization */
2352 static int
2353 newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2354 {
2355 	struct sshbuf *b;
2356 	struct sshcipher_ctx *cc;
2357 	struct sshcomp *comp;
2358 	struct sshenc *enc;
2359 	struct sshmac *mac;
2360 	struct newkeys *newkey;
2361 	int r;
2362 
2363 	if ((newkey = ssh->state->newkeys[mode]) == NULL)
2364 		return SSH_ERR_INTERNAL_ERROR;
2365 	enc = &newkey->enc;
2366 	mac = &newkey->mac;
2367 	comp = &newkey->comp;
2368 	cc = (mode == MODE_OUT) ? ssh->state->send_context :
2369 	    ssh->state->receive_context;
2370 	if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
2371 		return r;
2372 	if ((b = sshbuf_new()) == NULL)
2373 		return SSH_ERR_ALLOC_FAIL;
2374 	if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
2375 	    (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
2376 	    (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
2377 	    (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
2378 	    (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
2379 		goto out;
2380 	if (cipher_authlen(enc->cipher) == 0) {
2381 		if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
2382 		    (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
2383 		    (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
2384 			goto out;
2385 	}
2386 	if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
2387 	    (r = sshbuf_put_cstring(b, comp->name)) != 0)
2388 		goto out;
2389 	r = sshbuf_put_stringb(m, b);
2390  out:
2391 	sshbuf_free(b);
2392 	return r;
2393 }
2394 
2395 /* serialize packet state into a blob */
2396 int
2397 ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
2398 {
2399 	struct session_state *state = ssh->state;
2400 	int r;
2401 
2402 	if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
2403 	    (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
2404 	    (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
2405 	    (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
2406 	    (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
2407 	    (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
2408 	    (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
2409 	    (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
2410 	    (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
2411 	    (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
2412 	    (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
2413 	    (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
2414 	    (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0 ||
2415 	    (r = sshbuf_put_stringb(m, state->input)) != 0 ||
2416 	    (r = sshbuf_put_stringb(m, state->output)) != 0)
2417 		return r;
2418 
2419 	return 0;
2420 }
2421 
2422 /* restore key exchange results from blob for packet state de-serialization */
2423 static int
2424 newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
2425 {
2426 	struct sshbuf *b = NULL;
2427 	struct sshcomp *comp;
2428 	struct sshenc *enc;
2429 	struct sshmac *mac;
2430 	struct newkeys *newkey = NULL;
2431 	size_t keylen, ivlen, maclen;
2432 	int r;
2433 
2434 	if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
2435 		r = SSH_ERR_ALLOC_FAIL;
2436 		goto out;
2437 	}
2438 	if ((r = sshbuf_froms(m, &b)) != 0)
2439 		goto out;
2440 #ifdef DEBUG_PK
2441 	sshbuf_dump(b, stderr);
2442 #endif
2443 	enc = &newkey->enc;
2444 	mac = &newkey->mac;
2445 	comp = &newkey->comp;
2446 
2447 	if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
2448 	    (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
2449 	    (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
2450 	    (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
2451 	    (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
2452 		goto out;
2453 	if ((enc->cipher = cipher_by_name(enc->name)) == NULL) {
2454 		r = SSH_ERR_INVALID_FORMAT;
2455 		goto out;
2456 	}
2457 	if (cipher_authlen(enc->cipher) == 0) {
2458 		if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
2459 			goto out;
2460 		if ((r = mac_setup(mac, mac->name)) != 0)
2461 			goto out;
2462 		if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
2463 		    (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
2464 			goto out;
2465 		if (maclen > mac->key_len) {
2466 			r = SSH_ERR_INVALID_FORMAT;
2467 			goto out;
2468 		}
2469 		mac->key_len = maclen;
2470 	}
2471 	if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
2472 	    (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
2473 		goto out;
2474 	if (sshbuf_len(b) != 0) {
2475 		r = SSH_ERR_INVALID_FORMAT;
2476 		goto out;
2477 	}
2478 	enc->key_len = keylen;
2479 	enc->iv_len = ivlen;
2480 	ssh->kex->newkeys[mode] = newkey;
2481 	newkey = NULL;
2482 	r = 0;
2483  out:
2484 	free(newkey);
2485 	sshbuf_free(b);
2486 	return r;
2487 }
2488 
2489 /* restore kex from blob for packet state de-serialization */
2490 static int
2491 kex_from_blob(struct sshbuf *m, struct kex **kexp)
2492 {
2493 	struct kex *kex;
2494 	int r;
2495 
2496 	if ((kex = kex_new()) == NULL)
2497 		return SSH_ERR_ALLOC_FAIL;
2498 	if ((r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
2499 	    (r = sshbuf_get_cstring(m, &kex->hostkey_alg, NULL)) != 0 ||
2500 	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
2501 	    (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_nid)) != 0 ||
2502 	    (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
2503 	    (r = sshbuf_get_u32(m, (uint32_t *)&kex->kex_strict)) != 0 ||
2504 	    (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
2505 	    (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
2506 	    (r = sshbuf_get_stringb(m, kex->client_version)) != 0 ||
2507 	    (r = sshbuf_get_stringb(m, kex->server_version)) != 0 ||
2508 	    (r = sshbuf_get_stringb(m, kex->session_id)) != 0 ||
2509 	    (r = sshbuf_get_u32(m, &kex->flags)) != 0)
2510 		goto out;
2511 	kex->server = 1;
2512 	kex->done = 1;
2513 	r = 0;
2514  out:
2515 	if (r != 0 || kexp == NULL) {
2516 		kex_free(kex);
2517 		if (kexp != NULL)
2518 			*kexp = NULL;
2519 	} else {
2520 		kex_free(*kexp);
2521 		*kexp = kex;
2522 	}
2523 	return r;
2524 }
2525 
2526 /*
2527  * Restore packet state from content of blob 'm' (de-serialization).
2528  * Note that 'm' will be partially consumed on parsing or any other errors.
2529  */
2530 int
2531 ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
2532 {
2533 	struct session_state *state = ssh->state;
2534 	const u_char *input, *output;
2535 	size_t ilen, olen;
2536 	int r;
2537 
2538 	if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
2539 	    (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
2540 	    (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
2541 	    (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
2542 	    (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
2543 	    (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
2544 	    (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
2545 	    (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
2546 	    (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
2547 	    (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
2548 	    (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
2549 	    (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
2550 	    (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
2551 		return r;
2552 	/*
2553 	 * We set the time here so that in post-auth privsep child we
2554 	 * count from the completion of the authentication.
2555 	 */
2556 	state->rekey_time = monotime();
2557 	/* XXX ssh_set_newkeys overrides p_read.packets? XXX */
2558 	if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
2559 	    (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
2560 		return r;
2561 
2562 	if ((r = ssh_packet_set_postauth(ssh)) != 0)
2563 		return r;
2564 
2565 	sshbuf_reset(state->input);
2566 	sshbuf_reset(state->output);
2567 	if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
2568 	    (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
2569 	    (r = sshbuf_put(state->input, input, ilen)) != 0 ||
2570 	    (r = sshbuf_put(state->output, output, olen)) != 0)
2571 		return r;
2572 
2573 	if (sshbuf_len(m))
2574 		return SSH_ERR_INVALID_FORMAT;
2575 	debug3_f("done");
2576 	return 0;
2577 }
2578 
2579 /* NEW API */
2580 
2581 /* put data to the outgoing packet */
2582 
2583 int
2584 sshpkt_put(struct ssh *ssh, const void *v, size_t len)
2585 {
2586 	return sshbuf_put(ssh->state->outgoing_packet, v, len);
2587 }
2588 
2589 int
2590 sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
2591 {
2592 	return sshbuf_putb(ssh->state->outgoing_packet, b);
2593 }
2594 
2595 int
2596 sshpkt_put_u8(struct ssh *ssh, u_char val)
2597 {
2598 	return sshbuf_put_u8(ssh->state->outgoing_packet, val);
2599 }
2600 
2601 int
2602 sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
2603 {
2604 	return sshbuf_put_u32(ssh->state->outgoing_packet, val);
2605 }
2606 
2607 int
2608 sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
2609 {
2610 	return sshbuf_put_u64(ssh->state->outgoing_packet, val);
2611 }
2612 
2613 int
2614 sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
2615 {
2616 	return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
2617 }
2618 
2619 int
2620 sshpkt_put_cstring(struct ssh *ssh, const void *v)
2621 {
2622 	return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
2623 }
2624 
2625 int
2626 sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
2627 {
2628 	return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
2629 }
2630 
2631 #ifdef WITH_OPENSSL
2632 int
2633 sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
2634 {
2635 	return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
2636 }
2637 
2638 int
2639 sshpkt_put_ec_pkey(struct ssh *ssh, EVP_PKEY *pkey)
2640 {
2641 	return sshbuf_put_ec_pkey(ssh->state->outgoing_packet, pkey);
2642 }
2643 
2644 int
2645 sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
2646 {
2647 	return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
2648 }
2649 #endif /* WITH_OPENSSL */
2650 
2651 /* fetch data from the incoming packet */
2652 
2653 int
2654 sshpkt_get(struct ssh *ssh, void *valp, size_t len)
2655 {
2656 	return sshbuf_get(ssh->state->incoming_packet, valp, len);
2657 }
2658 
2659 int
2660 sshpkt_get_u8(struct ssh *ssh, u_char *valp)
2661 {
2662 	return sshbuf_get_u8(ssh->state->incoming_packet, valp);
2663 }
2664 
2665 int
2666 sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
2667 {
2668 	return sshbuf_get_u32(ssh->state->incoming_packet, valp);
2669 }
2670 
2671 int
2672 sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
2673 {
2674 	return sshbuf_get_u64(ssh->state->incoming_packet, valp);
2675 }
2676 
2677 int
2678 sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
2679 {
2680 	return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
2681 }
2682 
2683 int
2684 sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2685 {
2686 	return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
2687 }
2688 
2689 int
2690 sshpkt_peek_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
2691 {
2692 	return sshbuf_peek_string_direct(ssh->state->incoming_packet, valp, lenp);
2693 }
2694 
2695 int
2696 sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
2697 {
2698 	return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
2699 }
2700 
2701 int
2702 sshpkt_getb_froms(struct ssh *ssh, struct sshbuf **valp)
2703 {
2704 	return sshbuf_froms(ssh->state->incoming_packet, valp);
2705 }
2706 
2707 #ifdef WITH_OPENSSL
2708 int
2709 sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
2710 {
2711 	return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
2712 }
2713 
2714 int
2715 sshpkt_get_bignum2(struct ssh *ssh, BIGNUM **valp)
2716 {
2717 	return sshbuf_get_bignum2(ssh->state->incoming_packet, valp);
2718 }
2719 #endif /* WITH_OPENSSL */
2720 
2721 int
2722 sshpkt_get_end(struct ssh *ssh)
2723 {
2724 	if (sshbuf_len(ssh->state->incoming_packet) > 0)
2725 		return SSH_ERR_UNEXPECTED_TRAILING_DATA;
2726 	return 0;
2727 }
2728 
2729 const u_char *
2730 sshpkt_ptr(struct ssh *ssh, size_t *lenp)
2731 {
2732 	if (lenp != NULL)
2733 		*lenp = sshbuf_len(ssh->state->incoming_packet);
2734 	return sshbuf_ptr(ssh->state->incoming_packet);
2735 }
2736 
2737 /* start a new packet */
2738 
2739 int
2740 sshpkt_start(struct ssh *ssh, u_char type)
2741 {
2742 	u_char buf[6]; /* u32 packet length, u8 pad len, u8 type */
2743 
2744 	DBG(debug("packet_start[%d]", type));
2745 	memset(buf, 0, sizeof(buf));
2746 	buf[sizeof(buf) - 1] = type;
2747 	sshbuf_reset(ssh->state->outgoing_packet);
2748 	return sshbuf_put(ssh->state->outgoing_packet, buf, sizeof(buf));
2749 }
2750 
2751 static int
2752 ssh_packet_send_mux(struct ssh *ssh)
2753 {
2754 	struct session_state *state = ssh->state;
2755 	u_char type, *cp;
2756 	size_t len;
2757 	int r;
2758 
2759 	if (ssh->kex)
2760 		return SSH_ERR_INTERNAL_ERROR;
2761 	len = sshbuf_len(state->outgoing_packet);
2762 	if (len < 6)
2763 		return SSH_ERR_INTERNAL_ERROR;
2764 	cp = sshbuf_mutable_ptr(state->outgoing_packet);
2765 	type = cp[5];
2766 	if (ssh_packet_log_type(type))
2767 		debug3_f("type %u", type);
2768 	/* drop everything, but the connection protocol */
2769 	if (type >= SSH2_MSG_CONNECTION_MIN &&
2770 	    type <= SSH2_MSG_CONNECTION_MAX) {
2771 		POKE_U32(cp, len - 4);
2772 		if ((r = sshbuf_putb(state->output,
2773 		    state->outgoing_packet)) != 0)
2774 			return r;
2775 		/* sshbuf_dump(state->output, stderr); */
2776 	}
2777 	sshbuf_reset(state->outgoing_packet);
2778 	return 0;
2779 }
2780 
2781 /*
2782  * 9.2.  Ignored Data Message
2783  *
2784  *   byte      SSH_MSG_IGNORE
2785  *   string    data
2786  *
2787  * All implementations MUST understand (and ignore) this message at any
2788  * time (after receiving the protocol version). No implementation is
2789  * required to send them. This message can be used as an additional
2790  * protection measure against advanced traffic analysis techniques.
2791  */
2792 int
2793 sshpkt_msg_ignore(struct ssh *ssh, u_int nbytes)
2794 {
2795 	u_int32_t rnd = 0;
2796 	int r;
2797 	u_int i;
2798 
2799 	if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2800 	    (r = sshpkt_put_u32(ssh, nbytes)) != 0)
2801 		return r;
2802 	for (i = 0; i < nbytes; i++) {
2803 		if (i % 4 == 0)
2804 			rnd = arc4random();
2805 		if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
2806 			return r;
2807 		rnd >>= 8;
2808 	}
2809 	return 0;
2810 }
2811 
2812 /* send it */
2813 
2814 int
2815 sshpkt_sendx(struct ssh *ssh)
2816 {
2817 	if (ssh->state && ssh->state->mux)
2818 		return ssh_packet_send_mux(ssh);
2819 	return ssh_packet_send2(ssh);
2820 }
2821 
2822 int
2823 sshpkt_send(struct ssh *ssh)
2824 {
2825 	int r = sshpkt_sendx(ssh);
2826 	return r < 0 ? r : 0;
2827 }
2828 
2829 int
2830 sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
2831 {
2832 	char buf[1024];
2833 	va_list args;
2834 	int r;
2835 
2836 	va_start(args, fmt);
2837 	vsnprintf(buf, sizeof(buf), fmt, args);
2838 	va_end(args);
2839 
2840 	debug2_f("sending SSH2_MSG_DISCONNECT: %s", buf);
2841 	if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
2842 	    (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
2843 	    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
2844 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2845 	    (r = sshpkt_send(ssh)) != 0)
2846 		return r;
2847 	return 0;
2848 }
2849 
2850 /* roundup current message to pad bytes */
2851 int
2852 sshpkt_add_padding(struct ssh *ssh, u_char pad)
2853 {
2854 	ssh->state->extra_pad = pad;
2855 	return 0;
2856 }
2857 
2858 int
2859 ssh_packet_authentication_state(struct ssh *ssh)
2860 {
2861 	return ssh->state->after_authentication;
2862 }
2863