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