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