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