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