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