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