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