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