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