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