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