1 /* $OpenBSD: packet.c,v 1.199 2014/10/24 02:01:20 lteo 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 <sys/param.h> 45 46 #include <netinet/in.h> 47 #include <netinet/ip.h> 48 49 #include <errno.h> 50 #include <stdarg.h> 51 #include <stdio.h> 52 #include <stdlib.h> 53 #include <string.h> 54 #include <unistd.h> 55 #include <signal.h> 56 #include <time.h> 57 58 #include "xmalloc.h" 59 #include "buffer.h" 60 #include "packet.h" 61 #include "crc32.h" 62 #include "compress.h" 63 #include "deattack.h" 64 #include "compat.h" 65 #include "ssh1.h" 66 #include "ssh2.h" 67 #include "cipher.h" 68 #include "key.h" 69 #include "kex.h" 70 #include "mac.h" 71 #include "log.h" 72 #include "canohost.h" 73 #include "misc.h" 74 #include "channels.h" 75 #include "ssh.h" 76 #include "ssherr.h" 77 #include "roaming.h" 78 79 #ifdef PACKET_DEBUG 80 #define DBG(x) x 81 #else 82 #define DBG(x) 83 #endif 84 85 #define PACKET_MAX_SIZE (256 * 1024) 86 87 struct packet_state { 88 u_int32_t seqnr; 89 u_int32_t packets; 90 u_int64_t blocks; 91 u_int64_t bytes; 92 }; 93 94 struct packet { 95 TAILQ_ENTRY(packet) next; 96 u_char type; 97 Buffer payload; 98 }; 99 100 struct session_state { 101 /* 102 * This variable contains the file descriptors used for 103 * communicating with the other side. connection_in is used for 104 * reading; connection_out for writing. These can be the same 105 * descriptor, in which case it is assumed to be a socket. 106 */ 107 int connection_in; 108 int connection_out; 109 110 /* Protocol flags for the remote side. */ 111 u_int remote_protocol_flags; 112 113 /* Encryption context for receiving data. Only used for decryption. */ 114 CipherContext receive_context; 115 116 /* Encryption context for sending data. Only used for encryption. */ 117 CipherContext send_context; 118 119 /* Buffer for raw input data from the socket. */ 120 Buffer input; 121 122 /* Buffer for raw output data going to the socket. */ 123 Buffer output; 124 125 /* Buffer for the partial outgoing packet being constructed. */ 126 Buffer outgoing_packet; 127 128 /* Buffer for the incoming packet currently being processed. */ 129 Buffer incoming_packet; 130 131 /* Scratch buffer for packet compression/decompression. */ 132 Buffer compression_buffer; 133 int compression_buffer_ready; 134 135 /* 136 * Flag indicating whether packet compression/decompression is 137 * enabled. 138 */ 139 int packet_compression; 140 141 /* default maximum packet size */ 142 u_int max_packet_size; 143 144 /* Flag indicating whether this module has been initialized. */ 145 int initialized; 146 147 /* Set to true if the connection is interactive. */ 148 int interactive_mode; 149 150 /* Set to true if we are the server side. */ 151 int server_side; 152 153 /* Set to true if we are authenticated. */ 154 int after_authentication; 155 156 int keep_alive_timeouts; 157 158 /* The maximum time that we will wait to send or receive a packet */ 159 int packet_timeout_ms; 160 161 /* Session key information for Encryption and MAC */ 162 Newkeys *newkeys[MODE_MAX]; 163 struct packet_state p_read, p_send; 164 165 /* Volume-based rekeying */ 166 u_int64_t max_blocks_in, max_blocks_out; 167 u_int32_t rekey_limit; 168 169 /* Time-based rekeying */ 170 time_t rekey_interval; /* how often in seconds */ 171 time_t rekey_time; /* time of last rekeying */ 172 173 /* Session key for protocol v1 */ 174 u_char ssh1_key[SSH_SESSION_KEY_LENGTH]; 175 u_int ssh1_keylen; 176 177 /* roundup current message to extra_pad bytes */ 178 u_char extra_pad; 179 180 /* XXX discard incoming data after MAC error */ 181 u_int packet_discard; 182 Mac *packet_discard_mac; 183 184 /* Used in packet_read_poll2() */ 185 u_int packlen; 186 187 /* Used in packet_send2 */ 188 int rekeying; 189 190 /* Used in packet_set_interactive */ 191 int set_interactive_called; 192 193 /* Used in packet_set_maxsize */ 194 int set_maxsize_called; 195 196 TAILQ_HEAD(, packet) outgoing; 197 }; 198 199 static struct session_state *active_state, *backup_state; 200 201 static struct session_state * 202 alloc_session_state(void) 203 { 204 struct session_state *s = xcalloc(1, sizeof(*s)); 205 206 s->connection_in = -1; 207 s->connection_out = -1; 208 s->max_packet_size = 32768; 209 s->packet_timeout_ms = -1; 210 return s; 211 } 212 213 /* 214 * Sets the descriptors used for communication. Disables encryption until 215 * packet_set_encryption_key is called. 216 */ 217 void 218 packet_set_connection(int fd_in, int fd_out) 219 { 220 const Cipher *none = cipher_by_name("none"); 221 int r; 222 223 if (none == NULL) 224 fatal("packet_set_connection: cannot load cipher 'none'"); 225 if (active_state == NULL) 226 active_state = alloc_session_state(); 227 active_state->connection_in = fd_in; 228 active_state->connection_out = fd_out; 229 if ((r = cipher_init(&active_state->send_context, none, 230 (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 || 231 (r = cipher_init(&active_state->receive_context, none, 232 (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) 233 fatal("%s: cipher_init: %s", __func__, ssh_err(r)); 234 active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL; 235 if (!active_state->initialized) { 236 active_state->initialized = 1; 237 buffer_init(&active_state->input); 238 buffer_init(&active_state->output); 239 buffer_init(&active_state->outgoing_packet); 240 buffer_init(&active_state->incoming_packet); 241 TAILQ_INIT(&active_state->outgoing); 242 active_state->p_send.packets = active_state->p_read.packets = 0; 243 } 244 } 245 246 void 247 packet_set_timeout(int timeout, int count) 248 { 249 if (timeout <= 0 || count <= 0) { 250 active_state->packet_timeout_ms = -1; 251 return; 252 } 253 if ((INT_MAX / 1000) / count < timeout) 254 active_state->packet_timeout_ms = INT_MAX; 255 else 256 active_state->packet_timeout_ms = timeout * count * 1000; 257 } 258 259 static void 260 packet_stop_discard(void) 261 { 262 if (active_state->packet_discard_mac) { 263 char buf[1024]; 264 265 memset(buf, 'a', sizeof(buf)); 266 while (buffer_len(&active_state->incoming_packet) < 267 PACKET_MAX_SIZE) 268 buffer_append(&active_state->incoming_packet, buf, 269 sizeof(buf)); 270 (void) mac_compute(active_state->packet_discard_mac, 271 active_state->p_read.seqnr, 272 buffer_ptr(&active_state->incoming_packet), 273 PACKET_MAX_SIZE); 274 } 275 logit("Finished discarding for %.200s", get_remote_ipaddr()); 276 cleanup_exit(255); 277 } 278 279 static void 280 packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard) 281 { 282 if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) 283 packet_disconnect("Packet corrupt"); 284 if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled) 285 active_state->packet_discard_mac = mac; 286 if (buffer_len(&active_state->input) >= discard) 287 packet_stop_discard(); 288 active_state->packet_discard = discard - 289 buffer_len(&active_state->input); 290 } 291 292 /* Returns 1 if remote host is connected via socket, 0 if not. */ 293 294 int 295 packet_connection_is_on_socket(void) 296 { 297 struct sockaddr_storage from, to; 298 socklen_t fromlen, tolen; 299 300 /* filedescriptors in and out are the same, so it's a socket */ 301 if (active_state->connection_in == active_state->connection_out) 302 return 1; 303 fromlen = sizeof(from); 304 memset(&from, 0, sizeof(from)); 305 if (getpeername(active_state->connection_in, (struct sockaddr *)&from, 306 &fromlen) < 0) 307 return 0; 308 tolen = sizeof(to); 309 memset(&to, 0, sizeof(to)); 310 if (getpeername(active_state->connection_out, (struct sockaddr *)&to, 311 &tolen) < 0) 312 return 0; 313 if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0) 314 return 0; 315 if (from.ss_family != AF_INET && from.ss_family != AF_INET6) 316 return 0; 317 return 1; 318 } 319 320 /* 321 * Exports an IV from the CipherContext required to export the key 322 * state back from the unprivileged child to the privileged parent 323 * process. 324 */ 325 326 void 327 packet_get_keyiv(int mode, u_char *iv, u_int len) 328 { 329 CipherContext *cc; 330 int r; 331 332 if (mode == MODE_OUT) 333 cc = &active_state->send_context; 334 else 335 cc = &active_state->receive_context; 336 337 if ((r = cipher_get_keyiv(cc, iv, len)) != 0) 338 fatal("%s: cipher_get_keyiv: %s", __func__, ssh_err(r)); 339 } 340 341 int 342 packet_get_keycontext(int mode, u_char *dat) 343 { 344 CipherContext *cc; 345 346 if (mode == MODE_OUT) 347 cc = &active_state->send_context; 348 else 349 cc = &active_state->receive_context; 350 351 return (cipher_get_keycontext(cc, dat)); 352 } 353 354 void 355 packet_set_keycontext(int mode, u_char *dat) 356 { 357 CipherContext *cc; 358 359 if (mode == MODE_OUT) 360 cc = &active_state->send_context; 361 else 362 cc = &active_state->receive_context; 363 364 cipher_set_keycontext(cc, dat); 365 } 366 367 int 368 packet_get_keyiv_len(int mode) 369 { 370 CipherContext *cc; 371 372 if (mode == MODE_OUT) 373 cc = &active_state->send_context; 374 else 375 cc = &active_state->receive_context; 376 377 return (cipher_get_keyiv_len(cc)); 378 } 379 380 void 381 packet_set_iv(int mode, u_char *dat) 382 { 383 CipherContext *cc; 384 int r; 385 386 if (mode == MODE_OUT) 387 cc = &active_state->send_context; 388 else 389 cc = &active_state->receive_context; 390 391 if ((r = cipher_set_keyiv(cc, dat)) != 0) 392 fatal("%s: cipher_set_keyiv: %s", __func__, ssh_err(r)); 393 } 394 395 int 396 packet_get_ssh1_cipher(void) 397 { 398 return (cipher_get_number(active_state->receive_context.cipher)); 399 } 400 401 void 402 packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, 403 u_int32_t *packets, u_int64_t *bytes) 404 { 405 struct packet_state *state; 406 407 state = (mode == MODE_IN) ? 408 &active_state->p_read : &active_state->p_send; 409 if (seqnr) 410 *seqnr = state->seqnr; 411 if (blocks) 412 *blocks = state->blocks; 413 if (packets) 414 *packets = state->packets; 415 if (bytes) 416 *bytes = state->bytes; 417 } 418 419 void 420 packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets, 421 u_int64_t bytes) 422 { 423 struct packet_state *state; 424 425 state = (mode == MODE_IN) ? 426 &active_state->p_read : &active_state->p_send; 427 state->seqnr = seqnr; 428 state->blocks = blocks; 429 state->packets = packets; 430 state->bytes = bytes; 431 } 432 433 static int 434 packet_connection_af(void) 435 { 436 struct sockaddr_storage to; 437 socklen_t tolen = sizeof(to); 438 439 memset(&to, 0, sizeof(to)); 440 if (getsockname(active_state->connection_out, (struct sockaddr *)&to, 441 &tolen) < 0) 442 return 0; 443 return to.ss_family; 444 } 445 446 /* Sets the connection into non-blocking mode. */ 447 448 void 449 packet_set_nonblocking(void) 450 { 451 /* Set the socket into non-blocking mode. */ 452 set_nonblock(active_state->connection_in); 453 454 if (active_state->connection_out != active_state->connection_in) 455 set_nonblock(active_state->connection_out); 456 } 457 458 /* Returns the socket used for reading. */ 459 460 int 461 packet_get_connection_in(void) 462 { 463 return active_state->connection_in; 464 } 465 466 /* Returns the descriptor used for writing. */ 467 468 int 469 packet_get_connection_out(void) 470 { 471 return active_state->connection_out; 472 } 473 474 /* Closes the connection and clears and frees internal data structures. */ 475 476 void 477 packet_close(void) 478 { 479 if (!active_state->initialized) 480 return; 481 active_state->initialized = 0; 482 if (active_state->connection_in == active_state->connection_out) { 483 shutdown(active_state->connection_out, SHUT_RDWR); 484 close(active_state->connection_out); 485 } else { 486 close(active_state->connection_in); 487 close(active_state->connection_out); 488 } 489 buffer_free(&active_state->input); 490 buffer_free(&active_state->output); 491 buffer_free(&active_state->outgoing_packet); 492 buffer_free(&active_state->incoming_packet); 493 if (active_state->compression_buffer_ready) { 494 buffer_free(&active_state->compression_buffer); 495 buffer_compress_uninit(); 496 } 497 cipher_cleanup(&active_state->send_context); 498 cipher_cleanup(&active_state->receive_context); 499 } 500 501 /* Sets remote side protocol flags. */ 502 503 void 504 packet_set_protocol_flags(u_int protocol_flags) 505 { 506 active_state->remote_protocol_flags = protocol_flags; 507 } 508 509 /* Returns the remote protocol flags set earlier by the above function. */ 510 511 u_int 512 packet_get_protocol_flags(void) 513 { 514 return active_state->remote_protocol_flags; 515 } 516 517 /* 518 * Starts packet compression from the next packet on in both directions. 519 * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip. 520 */ 521 522 static void 523 packet_init_compression(void) 524 { 525 if (active_state->compression_buffer_ready == 1) 526 return; 527 active_state->compression_buffer_ready = 1; 528 buffer_init(&active_state->compression_buffer); 529 } 530 531 void 532 packet_start_compression(int level) 533 { 534 if (active_state->packet_compression && !compat20) 535 fatal("Compression already enabled."); 536 active_state->packet_compression = 1; 537 packet_init_compression(); 538 buffer_compress_init_send(level); 539 buffer_compress_init_recv(); 540 } 541 542 /* 543 * Causes any further packets to be encrypted using the given key. The same 544 * key is used for both sending and reception. However, both directions are 545 * encrypted independently of each other. 546 */ 547 548 void 549 packet_set_encryption_key(const u_char *key, u_int keylen, int number) 550 { 551 const Cipher *cipher = cipher_by_number(number); 552 int r; 553 554 if (cipher == NULL) 555 fatal("packet_set_encryption_key: unknown cipher number %d", number); 556 if (keylen < 20) 557 fatal("packet_set_encryption_key: keylen too small: %d", keylen); 558 if (keylen > SSH_SESSION_KEY_LENGTH) 559 fatal("packet_set_encryption_key: keylen too big: %d", keylen); 560 memcpy(active_state->ssh1_key, key, keylen); 561 active_state->ssh1_keylen = keylen; 562 if ((r = cipher_init(&active_state->send_context, cipher, 563 key, keylen, NULL, 0, CIPHER_ENCRYPT)) != 0 || 564 (r = cipher_init(&active_state->receive_context, cipher, 565 key, keylen, NULL, 0, CIPHER_DECRYPT)) != 0) 566 fatal("%s: cipher_init: %s", __func__, ssh_err(r)); 567 } 568 569 u_int 570 packet_get_encryption_key(u_char *key) 571 { 572 if (key == NULL) 573 return (active_state->ssh1_keylen); 574 memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen); 575 return (active_state->ssh1_keylen); 576 } 577 578 /* Start constructing a packet to send. */ 579 void 580 packet_start(u_char type) 581 { 582 u_char buf[9]; 583 int len; 584 585 DBG(debug("packet_start[%d]", type)); 586 len = compat20 ? 6 : 9; 587 memset(buf, 0, len - 1); 588 buf[len - 1] = type; 589 buffer_clear(&active_state->outgoing_packet); 590 buffer_append(&active_state->outgoing_packet, buf, len); 591 } 592 593 /* Append payload. */ 594 void 595 packet_put_char(int value) 596 { 597 char ch = value; 598 599 buffer_append(&active_state->outgoing_packet, &ch, 1); 600 } 601 602 void 603 packet_put_int(u_int value) 604 { 605 buffer_put_int(&active_state->outgoing_packet, value); 606 } 607 608 void 609 packet_put_int64(u_int64_t value) 610 { 611 buffer_put_int64(&active_state->outgoing_packet, value); 612 } 613 614 void 615 packet_put_string(const void *buf, u_int len) 616 { 617 buffer_put_string(&active_state->outgoing_packet, buf, len); 618 } 619 620 void 621 packet_put_cstring(const char *str) 622 { 623 buffer_put_cstring(&active_state->outgoing_packet, str); 624 } 625 626 void 627 packet_put_raw(const void *buf, u_int len) 628 { 629 buffer_append(&active_state->outgoing_packet, buf, len); 630 } 631 632 #ifdef WITH_OPENSSL 633 void 634 packet_put_bignum(BIGNUM * value) 635 { 636 buffer_put_bignum(&active_state->outgoing_packet, value); 637 } 638 639 void 640 packet_put_bignum2(BIGNUM * value) 641 { 642 buffer_put_bignum2(&active_state->outgoing_packet, value); 643 } 644 645 void 646 packet_put_ecpoint(const EC_GROUP *curve, const EC_POINT *point) 647 { 648 buffer_put_ecpoint(&active_state->outgoing_packet, curve, point); 649 } 650 #endif 651 652 /* 653 * Finalizes and sends the packet. If the encryption key has been set, 654 * encrypts the packet before sending. 655 */ 656 657 static void 658 packet_send1(void) 659 { 660 u_char buf[8], *cp; 661 int i, padding, len; 662 u_int checksum; 663 u_int32_t rnd = 0; 664 665 /* 666 * If using packet compression, compress the payload of the outgoing 667 * packet. 668 */ 669 if (active_state->packet_compression) { 670 buffer_clear(&active_state->compression_buffer); 671 /* Skip padding. */ 672 buffer_consume(&active_state->outgoing_packet, 8); 673 /* padding */ 674 buffer_append(&active_state->compression_buffer, 675 "\0\0\0\0\0\0\0\0", 8); 676 buffer_compress(&active_state->outgoing_packet, 677 &active_state->compression_buffer); 678 buffer_clear(&active_state->outgoing_packet); 679 buffer_append(&active_state->outgoing_packet, 680 buffer_ptr(&active_state->compression_buffer), 681 buffer_len(&active_state->compression_buffer)); 682 } 683 /* Compute packet length without padding (add checksum, remove padding). */ 684 len = buffer_len(&active_state->outgoing_packet) + 4 - 8; 685 686 /* Insert padding. Initialized to zero in packet_start1() */ 687 padding = 8 - len % 8; 688 if (!active_state->send_context.plaintext) { 689 cp = buffer_ptr(&active_state->outgoing_packet); 690 for (i = 0; i < padding; i++) { 691 if (i % 4 == 0) 692 rnd = arc4random(); 693 cp[7 - i] = rnd & 0xff; 694 rnd >>= 8; 695 } 696 } 697 buffer_consume(&active_state->outgoing_packet, 8 - padding); 698 699 /* Add check bytes. */ 700 checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet), 701 buffer_len(&active_state->outgoing_packet)); 702 put_u32(buf, checksum); 703 buffer_append(&active_state->outgoing_packet, buf, 4); 704 705 #ifdef PACKET_DEBUG 706 fprintf(stderr, "packet_send plain: "); 707 buffer_dump(&active_state->outgoing_packet); 708 #endif 709 710 /* Append to output. */ 711 put_u32(buf, len); 712 buffer_append(&active_state->output, buf, 4); 713 cp = buffer_append_space(&active_state->output, 714 buffer_len(&active_state->outgoing_packet)); 715 if (cipher_crypt(&active_state->send_context, 0, cp, 716 buffer_ptr(&active_state->outgoing_packet), 717 buffer_len(&active_state->outgoing_packet), 0, 0) != 0) 718 fatal("%s: cipher_crypt failed", __func__); 719 720 #ifdef PACKET_DEBUG 721 fprintf(stderr, "encrypted: "); 722 buffer_dump(&active_state->output); 723 #endif 724 active_state->p_send.packets++; 725 active_state->p_send.bytes += len + 726 buffer_len(&active_state->outgoing_packet); 727 buffer_clear(&active_state->outgoing_packet); 728 729 /* 730 * Note that the packet is now only buffered in output. It won't be 731 * actually sent until packet_write_wait or packet_write_poll is 732 * called. 733 */ 734 } 735 736 void 737 set_newkeys(int mode) 738 { 739 Enc *enc; 740 Mac *mac; 741 Comp *comp; 742 CipherContext *cc; 743 u_int64_t *max_blocks; 744 int r, crypt_type; 745 746 debug2("set_newkeys: mode %d", mode); 747 748 if (mode == MODE_OUT) { 749 cc = &active_state->send_context; 750 crypt_type = CIPHER_ENCRYPT; 751 active_state->p_send.packets = active_state->p_send.blocks = 0; 752 max_blocks = &active_state->max_blocks_out; 753 } else { 754 cc = &active_state->receive_context; 755 crypt_type = CIPHER_DECRYPT; 756 active_state->p_read.packets = active_state->p_read.blocks = 0; 757 max_blocks = &active_state->max_blocks_in; 758 } 759 if (active_state->newkeys[mode] != NULL) { 760 debug("set_newkeys: rekeying"); 761 cipher_cleanup(cc); 762 enc = &active_state->newkeys[mode]->enc; 763 mac = &active_state->newkeys[mode]->mac; 764 comp = &active_state->newkeys[mode]->comp; 765 mac_clear(mac); 766 explicit_bzero(enc->iv, enc->iv_len); 767 explicit_bzero(enc->key, enc->key_len); 768 explicit_bzero(mac->key, mac->key_len); 769 free(enc->name); 770 free(enc->iv); 771 free(enc->key); 772 free(mac->name); 773 free(mac->key); 774 free(comp->name); 775 free(active_state->newkeys[mode]); 776 } 777 active_state->newkeys[mode] = kex_get_newkeys(mode); 778 if (active_state->newkeys[mode] == NULL) 779 fatal("newkeys: no keys for mode %d", mode); 780 enc = &active_state->newkeys[mode]->enc; 781 mac = &active_state->newkeys[mode]->mac; 782 comp = &active_state->newkeys[mode]->comp; 783 if (cipher_authlen(enc->cipher) == 0 && mac_init(mac) == 0) 784 mac->enabled = 1; 785 DBG(debug("cipher_init_context: %d", mode)); 786 if ((r = cipher_init(cc, enc->cipher, enc->key, enc->key_len, 787 enc->iv, enc->iv_len, crypt_type)) != 0) 788 fatal("%s: cipher_init: %s", __func__, ssh_err(r)); 789 /* Deleting the keys does not gain extra security */ 790 /* explicit_bzero(enc->iv, enc->block_size); 791 explicit_bzero(enc->key, enc->key_len); 792 explicit_bzero(mac->key, mac->key_len); */ 793 if ((comp->type == COMP_ZLIB || 794 (comp->type == COMP_DELAYED && 795 active_state->after_authentication)) && comp->enabled == 0) { 796 packet_init_compression(); 797 if (mode == MODE_OUT) 798 buffer_compress_init_send(6); 799 else 800 buffer_compress_init_recv(); 801 comp->enabled = 1; 802 } 803 /* 804 * The 2^(blocksize*2) limit is too expensive for 3DES, 805 * blowfish, etc, so enforce a 1GB limit for small blocksizes. 806 */ 807 if (enc->block_size >= 16) 808 *max_blocks = (u_int64_t)1 << (enc->block_size*2); 809 else 810 *max_blocks = ((u_int64_t)1 << 30) / enc->block_size; 811 if (active_state->rekey_limit) 812 *max_blocks = MIN(*max_blocks, 813 active_state->rekey_limit / enc->block_size); 814 } 815 816 /* 817 * Delayed compression for SSH2 is enabled after authentication: 818 * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent, 819 * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received. 820 */ 821 static void 822 packet_enable_delayed_compress(void) 823 { 824 Comp *comp = NULL; 825 int mode; 826 827 /* 828 * Remember that we are past the authentication step, so rekeying 829 * with COMP_DELAYED will turn on compression immediately. 830 */ 831 active_state->after_authentication = 1; 832 for (mode = 0; mode < MODE_MAX; mode++) { 833 /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */ 834 if (active_state->newkeys[mode] == NULL) 835 continue; 836 comp = &active_state->newkeys[mode]->comp; 837 if (comp && !comp->enabled && comp->type == COMP_DELAYED) { 838 packet_init_compression(); 839 if (mode == MODE_OUT) 840 buffer_compress_init_send(6); 841 else 842 buffer_compress_init_recv(); 843 comp->enabled = 1; 844 } 845 } 846 } 847 848 /* 849 * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue) 850 */ 851 static void 852 packet_send2_wrapped(void) 853 { 854 u_char type, *cp, *macbuf = NULL; 855 u_char padlen, pad = 0; 856 u_int i, len, authlen = 0, aadlen = 0; 857 u_int32_t rnd = 0; 858 Enc *enc = NULL; 859 Mac *mac = NULL; 860 Comp *comp = NULL; 861 int block_size; 862 863 if (active_state->newkeys[MODE_OUT] != NULL) { 864 enc = &active_state->newkeys[MODE_OUT]->enc; 865 mac = &active_state->newkeys[MODE_OUT]->mac; 866 comp = &active_state->newkeys[MODE_OUT]->comp; 867 /* disable mac for authenticated encryption */ 868 if ((authlen = cipher_authlen(enc->cipher)) != 0) 869 mac = NULL; 870 } 871 block_size = enc ? enc->block_size : 8; 872 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0; 873 874 cp = buffer_ptr(&active_state->outgoing_packet); 875 type = cp[5]; 876 877 #ifdef PACKET_DEBUG 878 fprintf(stderr, "plain: "); 879 buffer_dump(&active_state->outgoing_packet); 880 #endif 881 882 if (comp && comp->enabled) { 883 len = buffer_len(&active_state->outgoing_packet); 884 /* skip header, compress only payload */ 885 buffer_consume(&active_state->outgoing_packet, 5); 886 buffer_clear(&active_state->compression_buffer); 887 buffer_compress(&active_state->outgoing_packet, 888 &active_state->compression_buffer); 889 buffer_clear(&active_state->outgoing_packet); 890 buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5); 891 buffer_append(&active_state->outgoing_packet, 892 buffer_ptr(&active_state->compression_buffer), 893 buffer_len(&active_state->compression_buffer)); 894 DBG(debug("compression: raw %d compressed %d", len, 895 buffer_len(&active_state->outgoing_packet))); 896 } 897 898 /* sizeof (packet_len + pad_len + payload) */ 899 len = buffer_len(&active_state->outgoing_packet); 900 901 /* 902 * calc size of padding, alloc space, get random data, 903 * minimum padding is 4 bytes 904 */ 905 len -= aadlen; /* packet length is not encrypted for EtM modes */ 906 padlen = block_size - (len % block_size); 907 if (padlen < 4) 908 padlen += block_size; 909 if (active_state->extra_pad) { 910 /* will wrap if extra_pad+padlen > 255 */ 911 active_state->extra_pad = 912 roundup(active_state->extra_pad, block_size); 913 pad = active_state->extra_pad - 914 ((len + padlen) % active_state->extra_pad); 915 DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)", 916 __func__, pad, len, padlen, active_state->extra_pad)); 917 padlen += pad; 918 active_state->extra_pad = 0; 919 } 920 cp = buffer_append_space(&active_state->outgoing_packet, padlen); 921 if (enc && !active_state->send_context.plaintext) { 922 /* random padding */ 923 for (i = 0; i < padlen; i++) { 924 if (i % 4 == 0) 925 rnd = arc4random(); 926 cp[i] = rnd & 0xff; 927 rnd >>= 8; 928 } 929 } else { 930 /* clear padding */ 931 explicit_bzero(cp, padlen); 932 } 933 /* sizeof (packet_len + pad_len + payload + padding) */ 934 len = buffer_len(&active_state->outgoing_packet); 935 cp = buffer_ptr(&active_state->outgoing_packet); 936 /* packet_length includes payload, padding and padding length field */ 937 put_u32(cp, len - 4); 938 cp[4] = padlen; 939 DBG(debug("send: len %d (includes padlen %d, aadlen %d)", 940 len, padlen, aadlen)); 941 942 /* compute MAC over seqnr and packet(length fields, payload, padding) */ 943 if (mac && mac->enabled && !mac->etm) { 944 macbuf = mac_compute(mac, active_state->p_send.seqnr, 945 buffer_ptr(&active_state->outgoing_packet), len); 946 DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr)); 947 } 948 /* encrypt packet and append to output buffer. */ 949 cp = buffer_append_space(&active_state->output, len + authlen); 950 if (cipher_crypt(&active_state->send_context, active_state->p_send.seqnr, 951 cp, buffer_ptr(&active_state->outgoing_packet), 952 len - aadlen, aadlen, authlen) != 0) 953 fatal("%s: cipher_crypt failed", __func__); 954 /* append unencrypted MAC */ 955 if (mac && mac->enabled) { 956 if (mac->etm) { 957 /* EtM: compute mac over aadlen + cipher text */ 958 macbuf = mac_compute(mac, 959 active_state->p_send.seqnr, cp, len); 960 DBG(debug("done calc MAC(EtM) out #%d", 961 active_state->p_send.seqnr)); 962 } 963 buffer_append(&active_state->output, macbuf, mac->mac_len); 964 } 965 #ifdef PACKET_DEBUG 966 fprintf(stderr, "encrypted: "); 967 buffer_dump(&active_state->output); 968 #endif 969 /* increment sequence number for outgoing packets */ 970 if (++active_state->p_send.seqnr == 0) 971 logit("outgoing seqnr wraps around"); 972 if (++active_state->p_send.packets == 0) 973 if (!(datafellows & SSH_BUG_NOREKEY)) 974 fatal("XXX too many packets with same key"); 975 active_state->p_send.blocks += len / block_size; 976 active_state->p_send.bytes += len; 977 buffer_clear(&active_state->outgoing_packet); 978 979 if (type == SSH2_MSG_NEWKEYS) 980 set_newkeys(MODE_OUT); 981 else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side) 982 packet_enable_delayed_compress(); 983 } 984 985 static void 986 packet_send2(void) 987 { 988 struct packet *p; 989 u_char type, *cp; 990 991 cp = buffer_ptr(&active_state->outgoing_packet); 992 type = cp[5]; 993 994 /* during rekeying we can only send key exchange messages */ 995 if (active_state->rekeying) { 996 if ((type < SSH2_MSG_TRANSPORT_MIN) || 997 (type > SSH2_MSG_TRANSPORT_MAX) || 998 (type == SSH2_MSG_SERVICE_REQUEST) || 999 (type == SSH2_MSG_SERVICE_ACCEPT)) { 1000 debug("enqueue packet: %u", type); 1001 p = xcalloc(1, sizeof(*p)); 1002 p->type = type; 1003 memcpy(&p->payload, &active_state->outgoing_packet, 1004 sizeof(Buffer)); 1005 buffer_init(&active_state->outgoing_packet); 1006 TAILQ_INSERT_TAIL(&active_state->outgoing, p, next); 1007 return; 1008 } 1009 } 1010 1011 /* rekeying starts with sending KEXINIT */ 1012 if (type == SSH2_MSG_KEXINIT) 1013 active_state->rekeying = 1; 1014 1015 packet_send2_wrapped(); 1016 1017 /* after a NEWKEYS message we can send the complete queue */ 1018 if (type == SSH2_MSG_NEWKEYS) { 1019 active_state->rekeying = 0; 1020 active_state->rekey_time = monotime(); 1021 while ((p = TAILQ_FIRST(&active_state->outgoing))) { 1022 type = p->type; 1023 debug("dequeue packet: %u", type); 1024 buffer_free(&active_state->outgoing_packet); 1025 memcpy(&active_state->outgoing_packet, &p->payload, 1026 sizeof(Buffer)); 1027 TAILQ_REMOVE(&active_state->outgoing, p, next); 1028 free(p); 1029 packet_send2_wrapped(); 1030 } 1031 } 1032 } 1033 1034 void 1035 packet_send(void) 1036 { 1037 if (compat20) 1038 packet_send2(); 1039 else 1040 packet_send1(); 1041 DBG(debug("packet_send done")); 1042 } 1043 1044 /* 1045 * Waits until a packet has been received, and returns its type. Note that 1046 * no other data is processed until this returns, so this function should not 1047 * be used during the interactive session. 1048 */ 1049 1050 int 1051 packet_read_seqnr(u_int32_t *seqnr_p) 1052 { 1053 int type, len, ret, cont, ms_remain = 0; 1054 fd_set *setp; 1055 char buf[8192]; 1056 struct timeval timeout, start, *timeoutp = NULL; 1057 1058 DBG(debug("packet_read()")); 1059 1060 setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1, 1061 NFDBITS), sizeof(fd_mask)); 1062 1063 /* Since we are blocking, ensure that all written packets have been sent. */ 1064 packet_write_wait(); 1065 1066 /* Stay in the loop until we have received a complete packet. */ 1067 for (;;) { 1068 /* Try to read a packet from the buffer. */ 1069 type = packet_read_poll_seqnr(seqnr_p); 1070 if (!compat20 && ( 1071 type == SSH_SMSG_SUCCESS 1072 || type == SSH_SMSG_FAILURE 1073 || type == SSH_CMSG_EOF 1074 || type == SSH_CMSG_EXIT_CONFIRMATION)) 1075 packet_check_eom(); 1076 /* If we got a packet, return it. */ 1077 if (type != SSH_MSG_NONE) { 1078 free(setp); 1079 return type; 1080 } 1081 /* 1082 * Otherwise, wait for some data to arrive, add it to the 1083 * buffer, and try again. 1084 */ 1085 memset(setp, 0, howmany(active_state->connection_in + 1, 1086 NFDBITS) * sizeof(fd_mask)); 1087 FD_SET(active_state->connection_in, setp); 1088 1089 if (active_state->packet_timeout_ms > 0) { 1090 ms_remain = active_state->packet_timeout_ms; 1091 timeoutp = &timeout; 1092 } 1093 /* Wait for some data to arrive. */ 1094 for (;;) { 1095 if (active_state->packet_timeout_ms != -1) { 1096 ms_to_timeval(&timeout, ms_remain); 1097 gettimeofday(&start, NULL); 1098 } 1099 if ((ret = select(active_state->connection_in + 1, setp, 1100 NULL, NULL, timeoutp)) >= 0) 1101 break; 1102 if (errno != EAGAIN && errno != EINTR) 1103 break; 1104 if (active_state->packet_timeout_ms == -1) 1105 continue; 1106 ms_subtract_diff(&start, &ms_remain); 1107 if (ms_remain <= 0) { 1108 ret = 0; 1109 break; 1110 } 1111 } 1112 if (ret == 0) { 1113 logit("Connection to %.200s timed out while " 1114 "waiting to read", get_remote_ipaddr()); 1115 cleanup_exit(255); 1116 } 1117 /* Read data from the socket. */ 1118 do { 1119 cont = 0; 1120 len = roaming_read(active_state->connection_in, buf, 1121 sizeof(buf), &cont); 1122 } while (len == 0 && cont); 1123 if (len == 0) { 1124 logit("Connection closed by %.200s", get_remote_ipaddr()); 1125 cleanup_exit(255); 1126 } 1127 if (len < 0) 1128 fatal("Read from socket failed: %.100s", strerror(errno)); 1129 /* Append it to the buffer. */ 1130 packet_process_incoming(buf, len); 1131 } 1132 /* NOTREACHED */ 1133 } 1134 1135 int 1136 packet_read(void) 1137 { 1138 return packet_read_seqnr(NULL); 1139 } 1140 1141 /* 1142 * Waits until a packet has been received, verifies that its type matches 1143 * that given, and gives a fatal error and exits if there is a mismatch. 1144 */ 1145 1146 void 1147 packet_read_expect(int expected_type) 1148 { 1149 int type; 1150 1151 type = packet_read(); 1152 if (type != expected_type) 1153 packet_disconnect("Protocol error: expected packet type %d, got %d", 1154 expected_type, type); 1155 } 1156 1157 /* Checks if a full packet is available in the data received so far via 1158 * packet_process_incoming. If so, reads the packet; otherwise returns 1159 * SSH_MSG_NONE. This does not wait for data from the connection. 1160 * 1161 * SSH_MSG_DISCONNECT is handled specially here. Also, 1162 * SSH_MSG_IGNORE messages are skipped by this function and are never returned 1163 * to higher levels. 1164 */ 1165 1166 static int 1167 packet_read_poll1(void) 1168 { 1169 u_int len, padded_len; 1170 u_char *cp, type; 1171 u_int checksum, stored_checksum; 1172 1173 /* Check if input size is less than minimum packet size. */ 1174 if (buffer_len(&active_state->input) < 4 + 8) 1175 return SSH_MSG_NONE; 1176 /* Get length of incoming packet. */ 1177 cp = buffer_ptr(&active_state->input); 1178 len = get_u32(cp); 1179 if (len < 1 + 2 + 2 || len > 256 * 1024) 1180 packet_disconnect("Bad packet length %u.", len); 1181 padded_len = (len + 8) & ~7; 1182 1183 /* Check if the packet has been entirely received. */ 1184 if (buffer_len(&active_state->input) < 4 + padded_len) 1185 return SSH_MSG_NONE; 1186 1187 /* The entire packet is in buffer. */ 1188 1189 /* Consume packet length. */ 1190 buffer_consume(&active_state->input, 4); 1191 1192 /* 1193 * Cryptographic attack detector for ssh 1194 * (C)1998 CORE-SDI, Buenos Aires Argentina 1195 * Ariel Futoransky(futo@core-sdi.com) 1196 */ 1197 if (!active_state->receive_context.plaintext) { 1198 switch (detect_attack(buffer_ptr(&active_state->input), 1199 padded_len)) { 1200 case DEATTACK_DETECTED: 1201 packet_disconnect("crc32 compensation attack: " 1202 "network attack detected"); 1203 case DEATTACK_DOS_DETECTED: 1204 packet_disconnect("deattack denial of " 1205 "service detected"); 1206 } 1207 } 1208 1209 /* Decrypt data to incoming_packet. */ 1210 buffer_clear(&active_state->incoming_packet); 1211 cp = buffer_append_space(&active_state->incoming_packet, padded_len); 1212 if (cipher_crypt(&active_state->receive_context, 0, cp, 1213 buffer_ptr(&active_state->input), padded_len, 0, 0) != 0) 1214 fatal("%s: cipher_crypt failed", __func__); 1215 1216 buffer_consume(&active_state->input, padded_len); 1217 1218 #ifdef PACKET_DEBUG 1219 fprintf(stderr, "read_poll plain: "); 1220 buffer_dump(&active_state->incoming_packet); 1221 #endif 1222 1223 /* Compute packet checksum. */ 1224 checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet), 1225 buffer_len(&active_state->incoming_packet) - 4); 1226 1227 /* Skip padding. */ 1228 buffer_consume(&active_state->incoming_packet, 8 - len % 8); 1229 1230 /* Test check bytes. */ 1231 if (len != buffer_len(&active_state->incoming_packet)) 1232 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.", 1233 len, buffer_len(&active_state->incoming_packet)); 1234 1235 cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4; 1236 stored_checksum = get_u32(cp); 1237 if (checksum != stored_checksum) 1238 packet_disconnect("Corrupted check bytes on input."); 1239 buffer_consume_end(&active_state->incoming_packet, 4); 1240 1241 if (active_state->packet_compression) { 1242 buffer_clear(&active_state->compression_buffer); 1243 buffer_uncompress(&active_state->incoming_packet, 1244 &active_state->compression_buffer); 1245 buffer_clear(&active_state->incoming_packet); 1246 buffer_append(&active_state->incoming_packet, 1247 buffer_ptr(&active_state->compression_buffer), 1248 buffer_len(&active_state->compression_buffer)); 1249 } 1250 active_state->p_read.packets++; 1251 active_state->p_read.bytes += padded_len + 4; 1252 type = buffer_get_char(&active_state->incoming_packet); 1253 if (type < SSH_MSG_MIN || type > SSH_MSG_MAX) 1254 packet_disconnect("Invalid ssh1 packet type: %d", type); 1255 return type; 1256 } 1257 1258 static int 1259 packet_read_poll2(u_int32_t *seqnr_p) 1260 { 1261 u_int padlen, need; 1262 u_char *macbuf = NULL, *cp, type; 1263 u_int maclen, authlen = 0, aadlen = 0, block_size; 1264 Enc *enc = NULL; 1265 Mac *mac = NULL; 1266 Comp *comp = NULL; 1267 1268 if (active_state->packet_discard) 1269 return SSH_MSG_NONE; 1270 1271 if (active_state->newkeys[MODE_IN] != NULL) { 1272 enc = &active_state->newkeys[MODE_IN]->enc; 1273 mac = &active_state->newkeys[MODE_IN]->mac; 1274 comp = &active_state->newkeys[MODE_IN]->comp; 1275 /* disable mac for authenticated encryption */ 1276 if ((authlen = cipher_authlen(enc->cipher)) != 0) 1277 mac = NULL; 1278 } 1279 maclen = mac && mac->enabled ? mac->mac_len : 0; 1280 block_size = enc ? enc->block_size : 8; 1281 aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0; 1282 1283 if (aadlen && active_state->packlen == 0) { 1284 if (cipher_get_length(&active_state->receive_context, 1285 &active_state->packlen, 1286 active_state->p_read.seqnr, 1287 buffer_ptr(&active_state->input), 1288 buffer_len(&active_state->input)) != 0) 1289 return SSH_MSG_NONE; 1290 if (active_state->packlen < 1 + 4 || 1291 active_state->packlen > PACKET_MAX_SIZE) { 1292 #ifdef PACKET_DEBUG 1293 buffer_dump(&active_state->input); 1294 #endif 1295 logit("Bad packet length %u.", active_state->packlen); 1296 packet_disconnect("Packet corrupt"); 1297 } 1298 buffer_clear(&active_state->incoming_packet); 1299 } else if (active_state->packlen == 0) { 1300 /* 1301 * check if input size is less than the cipher block size, 1302 * decrypt first block and extract length of incoming packet 1303 */ 1304 if (buffer_len(&active_state->input) < block_size) 1305 return SSH_MSG_NONE; 1306 buffer_clear(&active_state->incoming_packet); 1307 cp = buffer_append_space(&active_state->incoming_packet, 1308 block_size); 1309 if (cipher_crypt(&active_state->receive_context, 1310 active_state->p_read.seqnr, cp, 1311 buffer_ptr(&active_state->input), block_size, 0, 0) != 0) 1312 fatal("Decryption integrity check failed"); 1313 cp = buffer_ptr(&active_state->incoming_packet); 1314 active_state->packlen = get_u32(cp); 1315 if (active_state->packlen < 1 + 4 || 1316 active_state->packlen > PACKET_MAX_SIZE) { 1317 #ifdef PACKET_DEBUG 1318 buffer_dump(&active_state->incoming_packet); 1319 #endif 1320 logit("Bad packet length %u.", active_state->packlen); 1321 packet_start_discard(enc, mac, active_state->packlen, 1322 PACKET_MAX_SIZE); 1323 return SSH_MSG_NONE; 1324 } 1325 buffer_consume(&active_state->input, block_size); 1326 } 1327 DBG(debug("input: packet len %u", active_state->packlen+4)); 1328 if (aadlen) { 1329 /* only the payload is encrypted */ 1330 need = active_state->packlen; 1331 } else { 1332 /* 1333 * the payload size and the payload are encrypted, but we 1334 * have a partial packet of block_size bytes 1335 */ 1336 need = 4 + active_state->packlen - block_size; 1337 } 1338 DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d," 1339 " aadlen %d", block_size, need, maclen, authlen, aadlen)); 1340 if (need % block_size != 0) { 1341 logit("padding error: need %d block %d mod %d", 1342 need, block_size, need % block_size); 1343 packet_start_discard(enc, mac, active_state->packlen, 1344 PACKET_MAX_SIZE - block_size); 1345 return SSH_MSG_NONE; 1346 } 1347 /* 1348 * check if the entire packet has been received and 1349 * decrypt into incoming_packet: 1350 * 'aadlen' bytes are unencrypted, but authenticated. 1351 * 'need' bytes are encrypted, followed by either 1352 * 'authlen' bytes of authentication tag or 1353 * 'maclen' bytes of message authentication code. 1354 */ 1355 if (buffer_len(&active_state->input) < aadlen + need + authlen + maclen) 1356 return SSH_MSG_NONE; 1357 #ifdef PACKET_DEBUG 1358 fprintf(stderr, "read_poll enc/full: "); 1359 buffer_dump(&active_state->input); 1360 #endif 1361 /* EtM: compute mac over encrypted input */ 1362 if (mac && mac->enabled && mac->etm) 1363 macbuf = mac_compute(mac, active_state->p_read.seqnr, 1364 buffer_ptr(&active_state->input), aadlen + need); 1365 cp = buffer_append_space(&active_state->incoming_packet, aadlen + need); 1366 if (cipher_crypt(&active_state->receive_context, 1367 active_state->p_read.seqnr, cp, 1368 buffer_ptr(&active_state->input), need, aadlen, authlen) != 0) 1369 fatal("Decryption integrity check failed"); 1370 buffer_consume(&active_state->input, aadlen + need + authlen); 1371 /* 1372 * compute MAC over seqnr and packet, 1373 * increment sequence number for incoming packet 1374 */ 1375 if (mac && mac->enabled) { 1376 if (!mac->etm) 1377 macbuf = mac_compute(mac, active_state->p_read.seqnr, 1378 buffer_ptr(&active_state->incoming_packet), 1379 buffer_len(&active_state->incoming_packet)); 1380 if (timingsafe_bcmp(macbuf, buffer_ptr(&active_state->input), 1381 mac->mac_len) != 0) { 1382 logit("Corrupted MAC on input."); 1383 if (need > PACKET_MAX_SIZE) 1384 fatal("internal error need %d", need); 1385 packet_start_discard(enc, mac, active_state->packlen, 1386 PACKET_MAX_SIZE - need); 1387 return SSH_MSG_NONE; 1388 } 1389 1390 DBG(debug("MAC #%d ok", active_state->p_read.seqnr)); 1391 buffer_consume(&active_state->input, mac->mac_len); 1392 } 1393 /* XXX now it's safe to use fatal/packet_disconnect */ 1394 if (seqnr_p != NULL) 1395 *seqnr_p = active_state->p_read.seqnr; 1396 if (++active_state->p_read.seqnr == 0) 1397 logit("incoming seqnr wraps around"); 1398 if (++active_state->p_read.packets == 0) 1399 if (!(datafellows & SSH_BUG_NOREKEY)) 1400 fatal("XXX too many packets with same key"); 1401 active_state->p_read.blocks += (active_state->packlen + 4) / block_size; 1402 active_state->p_read.bytes += active_state->packlen + 4; 1403 1404 /* get padlen */ 1405 cp = buffer_ptr(&active_state->incoming_packet); 1406 padlen = cp[4]; 1407 DBG(debug("input: padlen %d", padlen)); 1408 if (padlen < 4) 1409 packet_disconnect("Corrupted padlen %d on input.", padlen); 1410 1411 /* skip packet size + padlen, discard padding */ 1412 buffer_consume(&active_state->incoming_packet, 4 + 1); 1413 buffer_consume_end(&active_state->incoming_packet, padlen); 1414 1415 DBG(debug("input: len before de-compress %d", 1416 buffer_len(&active_state->incoming_packet))); 1417 if (comp && comp->enabled) { 1418 buffer_clear(&active_state->compression_buffer); 1419 buffer_uncompress(&active_state->incoming_packet, 1420 &active_state->compression_buffer); 1421 buffer_clear(&active_state->incoming_packet); 1422 buffer_append(&active_state->incoming_packet, 1423 buffer_ptr(&active_state->compression_buffer), 1424 buffer_len(&active_state->compression_buffer)); 1425 DBG(debug("input: len after de-compress %d", 1426 buffer_len(&active_state->incoming_packet))); 1427 } 1428 /* 1429 * get packet type, implies consume. 1430 * return length of payload (without type field) 1431 */ 1432 type = buffer_get_char(&active_state->incoming_packet); 1433 if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN) 1434 packet_disconnect("Invalid ssh2 packet type: %d", type); 1435 if (type == SSH2_MSG_NEWKEYS) 1436 set_newkeys(MODE_IN); 1437 else if (type == SSH2_MSG_USERAUTH_SUCCESS && 1438 !active_state->server_side) 1439 packet_enable_delayed_compress(); 1440 #ifdef PACKET_DEBUG 1441 fprintf(stderr, "read/plain[%d]:\r\n", type); 1442 buffer_dump(&active_state->incoming_packet); 1443 #endif 1444 /* reset for next packet */ 1445 active_state->packlen = 0; 1446 return type; 1447 } 1448 1449 int 1450 packet_read_poll_seqnr(u_int32_t *seqnr_p) 1451 { 1452 u_int reason, seqnr; 1453 u_char type; 1454 char *msg; 1455 1456 for (;;) { 1457 if (compat20) { 1458 type = packet_read_poll2(seqnr_p); 1459 if (type) { 1460 active_state->keep_alive_timeouts = 0; 1461 DBG(debug("received packet type %d", type)); 1462 } 1463 switch (type) { 1464 case SSH2_MSG_IGNORE: 1465 debug3("Received SSH2_MSG_IGNORE"); 1466 break; 1467 case SSH2_MSG_DEBUG: 1468 packet_get_char(); 1469 msg = packet_get_string(NULL); 1470 debug("Remote: %.900s", msg); 1471 free(msg); 1472 msg = packet_get_string(NULL); 1473 free(msg); 1474 break; 1475 case SSH2_MSG_DISCONNECT: 1476 reason = packet_get_int(); 1477 msg = packet_get_string(NULL); 1478 /* Ignore normal client exit notifications */ 1479 do_log2(active_state->server_side && 1480 reason == SSH2_DISCONNECT_BY_APPLICATION ? 1481 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR, 1482 "Received disconnect from %s: %u: %.400s", 1483 get_remote_ipaddr(), reason, msg); 1484 free(msg); 1485 cleanup_exit(255); 1486 break; 1487 case SSH2_MSG_UNIMPLEMENTED: 1488 seqnr = packet_get_int(); 1489 debug("Received SSH2_MSG_UNIMPLEMENTED for %u", 1490 seqnr); 1491 break; 1492 default: 1493 return type; 1494 } 1495 } else { 1496 type = packet_read_poll1(); 1497 switch (type) { 1498 case SSH_MSG_NONE: 1499 return SSH_MSG_NONE; 1500 case SSH_MSG_IGNORE: 1501 break; 1502 case SSH_MSG_DEBUG: 1503 msg = packet_get_string(NULL); 1504 debug("Remote: %.900s", msg); 1505 free(msg); 1506 break; 1507 case SSH_MSG_DISCONNECT: 1508 msg = packet_get_string(NULL); 1509 error("Received disconnect from %s: %.400s", 1510 get_remote_ipaddr(), msg); 1511 cleanup_exit(255); 1512 break; 1513 default: 1514 DBG(debug("received packet type %d", type)); 1515 return type; 1516 } 1517 } 1518 } 1519 } 1520 1521 /* 1522 * Buffers the given amount of input characters. This is intended to be used 1523 * together with packet_read_poll. 1524 */ 1525 1526 void 1527 packet_process_incoming(const char *buf, u_int len) 1528 { 1529 if (active_state->packet_discard) { 1530 active_state->keep_alive_timeouts = 0; /* ?? */ 1531 if (len >= active_state->packet_discard) 1532 packet_stop_discard(); 1533 active_state->packet_discard -= len; 1534 return; 1535 } 1536 buffer_append(&active_state->input, buf, len); 1537 } 1538 1539 /* Returns a character from the packet. */ 1540 1541 u_int 1542 packet_get_char(void) 1543 { 1544 char ch; 1545 1546 buffer_get(&active_state->incoming_packet, &ch, 1); 1547 return (u_char) ch; 1548 } 1549 1550 /* Returns an integer from the packet data. */ 1551 1552 u_int 1553 packet_get_int(void) 1554 { 1555 return buffer_get_int(&active_state->incoming_packet); 1556 } 1557 1558 /* Returns an 64 bit integer from the packet data. */ 1559 1560 u_int64_t 1561 packet_get_int64(void) 1562 { 1563 return buffer_get_int64(&active_state->incoming_packet); 1564 } 1565 1566 /* 1567 * Returns an arbitrary precision integer from the packet data. The integer 1568 * must have been initialized before this call. 1569 */ 1570 1571 #ifdef WITH_OPENSSL 1572 void 1573 packet_get_bignum(BIGNUM * value) 1574 { 1575 buffer_get_bignum(&active_state->incoming_packet, value); 1576 } 1577 1578 void 1579 packet_get_bignum2(BIGNUM * value) 1580 { 1581 buffer_get_bignum2(&active_state->incoming_packet, value); 1582 } 1583 1584 void 1585 packet_get_ecpoint(const EC_GROUP *curve, EC_POINT *point) 1586 { 1587 buffer_get_ecpoint(&active_state->incoming_packet, curve, point); 1588 } 1589 #endif 1590 1591 void * 1592 packet_get_raw(u_int *length_ptr) 1593 { 1594 u_int bytes = buffer_len(&active_state->incoming_packet); 1595 1596 if (length_ptr != NULL) 1597 *length_ptr = bytes; 1598 return buffer_ptr(&active_state->incoming_packet); 1599 } 1600 1601 int 1602 packet_remaining(void) 1603 { 1604 return buffer_len(&active_state->incoming_packet); 1605 } 1606 1607 /* 1608 * Returns a string from the packet data. The string is allocated using 1609 * xmalloc; it is the responsibility of the calling program to free it when 1610 * no longer needed. The length_ptr argument may be NULL, or point to an 1611 * integer into which the length of the string is stored. 1612 */ 1613 1614 void * 1615 packet_get_string(u_int *length_ptr) 1616 { 1617 return buffer_get_string(&active_state->incoming_packet, length_ptr); 1618 } 1619 1620 const void * 1621 packet_get_string_ptr(u_int *length_ptr) 1622 { 1623 return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr); 1624 } 1625 1626 /* Ensures the returned string has no embedded \0 characters in it. */ 1627 char * 1628 packet_get_cstring(u_int *length_ptr) 1629 { 1630 return buffer_get_cstring(&active_state->incoming_packet, length_ptr); 1631 } 1632 1633 /* 1634 * Sends a diagnostic message from the server to the client. This message 1635 * can be sent at any time (but not while constructing another message). The 1636 * message is printed immediately, but only if the client is being executed 1637 * in verbose mode. These messages are primarily intended to ease debugging 1638 * authentication problems. The length of the formatted message must not 1639 * exceed 1024 bytes. This will automatically call packet_write_wait. 1640 */ 1641 1642 void 1643 packet_send_debug(const char *fmt,...) 1644 { 1645 char buf[1024]; 1646 va_list args; 1647 1648 if (compat20 && (datafellows & SSH_BUG_DEBUG)) 1649 return; 1650 1651 va_start(args, fmt); 1652 vsnprintf(buf, sizeof(buf), fmt, args); 1653 va_end(args); 1654 1655 if (compat20) { 1656 packet_start(SSH2_MSG_DEBUG); 1657 packet_put_char(0); /* bool: always display */ 1658 packet_put_cstring(buf); 1659 packet_put_cstring(""); 1660 } else { 1661 packet_start(SSH_MSG_DEBUG); 1662 packet_put_cstring(buf); 1663 } 1664 packet_send(); 1665 packet_write_wait(); 1666 } 1667 1668 /* 1669 * Logs the error plus constructs and sends a disconnect packet, closes the 1670 * connection, and exits. This function never returns. The error message 1671 * should not contain a newline. The length of the formatted message must 1672 * not exceed 1024 bytes. 1673 */ 1674 1675 void 1676 packet_disconnect(const char *fmt,...) 1677 { 1678 char buf[1024]; 1679 va_list args; 1680 static int disconnecting = 0; 1681 1682 if (disconnecting) /* Guard against recursive invocations. */ 1683 fatal("packet_disconnect called recursively."); 1684 disconnecting = 1; 1685 1686 /* 1687 * Format the message. Note that the caller must make sure the 1688 * message is of limited size. 1689 */ 1690 va_start(args, fmt); 1691 vsnprintf(buf, sizeof(buf), fmt, args); 1692 va_end(args); 1693 1694 /* Display the error locally */ 1695 logit("Disconnecting: %.100s", buf); 1696 1697 /* Send the disconnect message to the other side, and wait for it to get sent. */ 1698 if (compat20) { 1699 packet_start(SSH2_MSG_DISCONNECT); 1700 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR); 1701 packet_put_cstring(buf); 1702 packet_put_cstring(""); 1703 } else { 1704 packet_start(SSH_MSG_DISCONNECT); 1705 packet_put_cstring(buf); 1706 } 1707 packet_send(); 1708 packet_write_wait(); 1709 1710 /* Stop listening for connections. */ 1711 channel_close_all(); 1712 1713 /* Close the connection. */ 1714 packet_close(); 1715 cleanup_exit(255); 1716 } 1717 1718 /* Checks if there is any buffered output, and tries to write some of the output. */ 1719 1720 void 1721 packet_write_poll(void) 1722 { 1723 int len = buffer_len(&active_state->output); 1724 int cont; 1725 1726 if (len > 0) { 1727 cont = 0; 1728 len = roaming_write(active_state->connection_out, 1729 buffer_ptr(&active_state->output), len, &cont); 1730 if (len == -1) { 1731 if (errno == EINTR || errno == EAGAIN) 1732 return; 1733 fatal("Write failed: %.100s", strerror(errno)); 1734 } 1735 if (len == 0 && !cont) 1736 fatal("Write connection closed"); 1737 buffer_consume(&active_state->output, len); 1738 } 1739 } 1740 1741 /* 1742 * Calls packet_write_poll repeatedly until all pending output data has been 1743 * written. 1744 */ 1745 1746 void 1747 packet_write_wait(void) 1748 { 1749 fd_set *setp; 1750 int ret, ms_remain = 0; 1751 struct timeval start, timeout, *timeoutp = NULL; 1752 1753 setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1, 1754 NFDBITS), sizeof(fd_mask)); 1755 packet_write_poll(); 1756 while (packet_have_data_to_write()) { 1757 memset(setp, 0, howmany(active_state->connection_out + 1, 1758 NFDBITS) * sizeof(fd_mask)); 1759 FD_SET(active_state->connection_out, setp); 1760 1761 if (active_state->packet_timeout_ms > 0) { 1762 ms_remain = active_state->packet_timeout_ms; 1763 timeoutp = &timeout; 1764 } 1765 for (;;) { 1766 if (active_state->packet_timeout_ms != -1) { 1767 ms_to_timeval(&timeout, ms_remain); 1768 gettimeofday(&start, NULL); 1769 } 1770 if ((ret = select(active_state->connection_out + 1, 1771 NULL, setp, NULL, timeoutp)) >= 0) 1772 break; 1773 if (errno != EAGAIN && errno != EINTR) 1774 break; 1775 if (active_state->packet_timeout_ms == -1) 1776 continue; 1777 ms_subtract_diff(&start, &ms_remain); 1778 if (ms_remain <= 0) { 1779 ret = 0; 1780 break; 1781 } 1782 } 1783 if (ret == 0) { 1784 logit("Connection to %.200s timed out while " 1785 "waiting to write", get_remote_ipaddr()); 1786 cleanup_exit(255); 1787 } 1788 packet_write_poll(); 1789 } 1790 free(setp); 1791 } 1792 1793 /* Returns true if there is buffered data to write to the connection. */ 1794 1795 int 1796 packet_have_data_to_write(void) 1797 { 1798 return buffer_len(&active_state->output) != 0; 1799 } 1800 1801 /* Returns true if there is not too much data to write to the connection. */ 1802 1803 int 1804 packet_not_very_much_data_to_write(void) 1805 { 1806 if (active_state->interactive_mode) 1807 return buffer_len(&active_state->output) < 16384; 1808 else 1809 return buffer_len(&active_state->output) < 128 * 1024; 1810 } 1811 1812 static void 1813 packet_set_tos(int tos) 1814 { 1815 if (!packet_connection_is_on_socket()) 1816 return; 1817 switch (packet_connection_af()) { 1818 case AF_INET: 1819 debug3("%s: set IP_TOS 0x%02x", __func__, tos); 1820 if (setsockopt(active_state->connection_in, 1821 IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0) 1822 error("setsockopt IP_TOS %d: %.100s:", 1823 tos, strerror(errno)); 1824 break; 1825 case AF_INET6: 1826 debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos); 1827 if (setsockopt(active_state->connection_in, 1828 IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0) 1829 error("setsockopt IPV6_TCLASS %d: %.100s:", 1830 tos, strerror(errno)); 1831 break; 1832 } 1833 } 1834 1835 /* Informs that the current session is interactive. Sets IP flags for that. */ 1836 1837 void 1838 packet_set_interactive(int interactive, int qos_interactive, int qos_bulk) 1839 { 1840 if (active_state->set_interactive_called) 1841 return; 1842 active_state->set_interactive_called = 1; 1843 1844 /* Record that we are in interactive mode. */ 1845 active_state->interactive_mode = interactive; 1846 1847 /* Only set socket options if using a socket. */ 1848 if (!packet_connection_is_on_socket()) 1849 return; 1850 set_nodelay(active_state->connection_in); 1851 packet_set_tos(interactive ? qos_interactive : qos_bulk); 1852 } 1853 1854 /* Returns true if the current connection is interactive. */ 1855 1856 int 1857 packet_is_interactive(void) 1858 { 1859 return active_state->interactive_mode; 1860 } 1861 1862 int 1863 packet_set_maxsize(u_int s) 1864 { 1865 if (active_state->set_maxsize_called) { 1866 logit("packet_set_maxsize: called twice: old %d new %d", 1867 active_state->max_packet_size, s); 1868 return -1; 1869 } 1870 if (s < 4 * 1024 || s > 1024 * 1024) { 1871 logit("packet_set_maxsize: bad size %d", s); 1872 return -1; 1873 } 1874 active_state->set_maxsize_called = 1; 1875 debug("packet_set_maxsize: setting to %d", s); 1876 active_state->max_packet_size = s; 1877 return s; 1878 } 1879 1880 int 1881 packet_inc_alive_timeouts(void) 1882 { 1883 return ++active_state->keep_alive_timeouts; 1884 } 1885 1886 void 1887 packet_set_alive_timeouts(int ka) 1888 { 1889 active_state->keep_alive_timeouts = ka; 1890 } 1891 1892 u_int 1893 packet_get_maxsize(void) 1894 { 1895 return active_state->max_packet_size; 1896 } 1897 1898 /* roundup current message to pad bytes */ 1899 void 1900 packet_add_padding(u_char pad) 1901 { 1902 active_state->extra_pad = pad; 1903 } 1904 1905 /* 1906 * 9.2. Ignored Data Message 1907 * 1908 * byte SSH_MSG_IGNORE 1909 * string data 1910 * 1911 * All implementations MUST understand (and ignore) this message at any 1912 * time (after receiving the protocol version). No implementation is 1913 * required to send them. This message can be used as an additional 1914 * protection measure against advanced traffic analysis techniques. 1915 */ 1916 void 1917 packet_send_ignore(int nbytes) 1918 { 1919 u_int32_t rnd = 0; 1920 int i; 1921 1922 packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE); 1923 packet_put_int(nbytes); 1924 for (i = 0; i < nbytes; i++) { 1925 if (i % 4 == 0) 1926 rnd = arc4random(); 1927 packet_put_char((u_char)rnd & 0xff); 1928 rnd >>= 8; 1929 } 1930 } 1931 1932 #define MAX_PACKETS (1U<<31) 1933 int 1934 packet_need_rekeying(void) 1935 { 1936 if (datafellows & SSH_BUG_NOREKEY) 1937 return 0; 1938 return 1939 (active_state->p_send.packets > MAX_PACKETS) || 1940 (active_state->p_read.packets > MAX_PACKETS) || 1941 (active_state->max_blocks_out && 1942 (active_state->p_send.blocks > active_state->max_blocks_out)) || 1943 (active_state->max_blocks_in && 1944 (active_state->p_read.blocks > active_state->max_blocks_in)) || 1945 (active_state->rekey_interval != 0 && active_state->rekey_time + 1946 active_state->rekey_interval <= monotime()); 1947 } 1948 1949 void 1950 packet_set_rekey_limits(u_int32_t bytes, time_t seconds) 1951 { 1952 debug3("rekey after %lld bytes, %d seconds", (long long)bytes, 1953 (int)seconds); 1954 active_state->rekey_limit = bytes; 1955 active_state->rekey_interval = seconds; 1956 /* 1957 * We set the time here so that in post-auth privsep slave we count 1958 * from the completion of the authentication. 1959 */ 1960 active_state->rekey_time = monotime(); 1961 } 1962 1963 time_t 1964 packet_get_rekey_timeout(void) 1965 { 1966 time_t seconds; 1967 1968 seconds = active_state->rekey_time + active_state->rekey_interval - 1969 monotime(); 1970 return (seconds <= 0 ? 1 : seconds); 1971 } 1972 1973 void 1974 packet_set_server(void) 1975 { 1976 active_state->server_side = 1; 1977 } 1978 1979 void 1980 packet_set_authenticated(void) 1981 { 1982 active_state->after_authentication = 1; 1983 } 1984 1985 void * 1986 packet_get_input(void) 1987 { 1988 return (void *)&active_state->input; 1989 } 1990 1991 void * 1992 packet_get_output(void) 1993 { 1994 return (void *)&active_state->output; 1995 } 1996 1997 void * 1998 packet_get_newkeys(int mode) 1999 { 2000 return (void *)active_state->newkeys[mode]; 2001 } 2002 2003 /* 2004 * Save the state for the real connection, and use a separate state when 2005 * resuming a suspended connection. 2006 */ 2007 void 2008 packet_backup_state(void) 2009 { 2010 struct session_state *tmp; 2011 2012 close(active_state->connection_in); 2013 active_state->connection_in = -1; 2014 close(active_state->connection_out); 2015 active_state->connection_out = -1; 2016 if (backup_state) 2017 tmp = backup_state; 2018 else 2019 tmp = alloc_session_state(); 2020 backup_state = active_state; 2021 active_state = tmp; 2022 } 2023 2024 /* 2025 * Swap in the old state when resuming a connecion. 2026 */ 2027 void 2028 packet_restore_state(void) 2029 { 2030 struct session_state *tmp; 2031 void *buf; 2032 u_int len; 2033 2034 tmp = backup_state; 2035 backup_state = active_state; 2036 active_state = tmp; 2037 active_state->connection_in = backup_state->connection_in; 2038 backup_state->connection_in = -1; 2039 active_state->connection_out = backup_state->connection_out; 2040 backup_state->connection_out = -1; 2041 len = buffer_len(&backup_state->input); 2042 if (len > 0) { 2043 buf = buffer_ptr(&backup_state->input); 2044 buffer_append(&active_state->input, buf, len); 2045 buffer_clear(&backup_state->input); 2046 add_recv_bytes(len); 2047 } 2048 } 2049 2050 /* Reset after_authentication and reset compression in post-auth privsep */ 2051 void 2052 packet_set_postauth(void) 2053 { 2054 Comp *comp; 2055 int mode; 2056 2057 debug("%s: called", __func__); 2058 /* This was set in net child, but is not visible in user child */ 2059 active_state->after_authentication = 1; 2060 active_state->rekeying = 0; 2061 for (mode = 0; mode < MODE_MAX; mode++) { 2062 if (active_state->newkeys[mode] == NULL) 2063 continue; 2064 comp = &active_state->newkeys[mode]->comp; 2065 if (comp && comp->enabled) 2066 packet_init_compression(); 2067 } 2068 } 2069