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