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