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