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