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