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