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