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