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