1 /* $NetBSD: clientloop.c,v 1.29 2020/05/28 17:05:49 christos Exp $ */ 2 /* $OpenBSD: clientloop.c,v 1.344 2020/04/24 02:19:40 dtucker Exp $ */ 3 /* 4 * Author: Tatu Ylonen <ylo@cs.hut.fi> 5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 6 * All rights reserved 7 * The main loop for the interactive session (client 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 * Copyright (c) 1999 Theo de Raadt. All rights reserved. 17 * 18 * Redistribution and use in source and binary forms, with or without 19 * modification, are permitted provided that the following conditions 20 * are met: 21 * 1. Redistributions of source code must retain the above copyright 22 * notice, this list of conditions and the following disclaimer. 23 * 2. Redistributions in binary form must reproduce the above copyright 24 * notice, this list of conditions and the following disclaimer in the 25 * documentation and/or other materials provided with the distribution. 26 * 27 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 28 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 29 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 30 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 31 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 36 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 37 * 38 * 39 * SSH2 support added by Markus Friedl. 40 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved. 41 * 42 * Redistribution and use in source and binary forms, with or without 43 * modification, are permitted provided that the following conditions 44 * are met: 45 * 1. Redistributions of source code must retain the above copyright 46 * notice, this list of conditions and the following disclaimer. 47 * 2. Redistributions in binary form must reproduce the above copyright 48 * notice, this list of conditions and the following disclaimer in the 49 * documentation and/or other materials provided with the distribution. 50 * 51 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 52 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 53 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 54 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 55 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 56 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 57 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 58 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 59 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 60 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 61 */ 62 63 #include "includes.h" 64 __RCSID("$NetBSD: clientloop.c,v 1.29 2020/05/28 17:05:49 christos Exp $"); 65 66 #include <sys/types.h> 67 #include <sys/ioctl.h> 68 #include <sys/stat.h> 69 #include <sys/socket.h> 70 #include <sys/time.h> 71 #include <sys/queue.h> 72 73 #include <ctype.h> 74 #include <errno.h> 75 #include <paths.h> 76 #include <signal.h> 77 #include <stdio.h> 78 #include <stdlib.h> 79 #include <string.h> 80 #include <stdarg.h> 81 #include <termios.h> 82 #include <pwd.h> 83 #include <unistd.h> 84 #include <limits.h> 85 86 #include "xmalloc.h" 87 #include "ssh.h" 88 #include "ssh2.h" 89 #include "packet.h" 90 #include "sshbuf.h" 91 #include "compat.h" 92 #include "channels.h" 93 #include "dispatch.h" 94 #include "sshkey.h" 95 #include "cipher.h" 96 #include "kex.h" 97 #include "myproposal.h" 98 #include "log.h" 99 #include "misc.h" 100 #include "readconf.h" 101 #include "clientloop.h" 102 #include "sshconnect.h" 103 #include "authfd.h" 104 #include "atomicio.h" 105 #include "sshpty.h" 106 #include "match.h" 107 #include "msg.h" 108 #include "getpeereid.h" 109 #include "ssherr.h" 110 #include "hostfile.h" 111 112 /* import options */ 113 extern Options options; 114 115 /* Flag indicating that stdin should be redirected from /dev/null. */ 116 extern int stdin_null_flag; 117 118 /* Flag indicating that no shell has been requested */ 119 extern int no_shell_flag; 120 121 /* Flag indicating that ssh should daemonise after authentication is complete */ 122 extern int fork_after_authentication_flag; 123 124 /* Control socket */ 125 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */ 126 127 /* 128 * Name of the host we are connecting to. This is the name given on the 129 * command line, or the Hostname specified for the user-supplied name in a 130 * configuration file. 131 */ 132 extern char *host; 133 134 /* 135 * If this field is not NULL, the ForwardAgent socket is this path and different 136 * instead of SSH_AUTH_SOCK. 137 */ 138 extern char *forward_agent_sock_path; 139 140 /* 141 * Flag to indicate that we have received a window change signal which has 142 * not yet been processed. This will cause a message indicating the new 143 * window size to be sent to the server a little later. This is volatile 144 * because this is updated in a signal handler. 145 */ 146 static volatile sig_atomic_t received_window_change_signal = 0; 147 static volatile sig_atomic_t received_signal = 0; 148 149 /* Time when backgrounded control master using ControlPersist should exit */ 150 static time_t control_persist_exit_time = 0; 151 152 /* Common data for the client loop code. */ 153 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */ 154 static int last_was_cr; /* Last character was a newline. */ 155 static int exit_status; /* Used to store the command exit status. */ 156 static struct sshbuf *stderr_buffer; /* Used for final exit message. */ 157 static int connection_in; /* Connection to server (input). */ 158 static int connection_out; /* Connection to server (output). */ 159 static int need_rekeying; /* Set to non-zero if rekeying is requested. */ 160 static int session_closed; /* In SSH2: login session closed. */ 161 static u_int x11_refuse_time; /* If >0, refuse x11 opens after this time. */ 162 163 static void client_init_dispatch(struct ssh *ssh); 164 int session_ident = -1; 165 166 /* Track escape per proto2 channel */ 167 struct escape_filter_ctx { 168 int escape_pending; 169 int escape_char; 170 }; 171 172 /* Context for channel confirmation replies */ 173 struct channel_reply_ctx { 174 const char *request_type; 175 int id; 176 enum confirm_action action; 177 }; 178 179 /* Global request success/failure callbacks */ 180 /* XXX move to struct ssh? */ 181 struct global_confirm { 182 TAILQ_ENTRY(global_confirm) entry; 183 global_confirm_cb *cb; 184 void *ctx; 185 int ref_count; 186 }; 187 TAILQ_HEAD(global_confirms, global_confirm); 188 static struct global_confirms global_confirms = 189 TAILQ_HEAD_INITIALIZER(global_confirms); 190 191 void ssh_process_session2_setup(int, int, int, struct sshbuf *); 192 193 /* 194 * Signal handler for the window change signal (SIGWINCH). This just sets a 195 * flag indicating that the window has changed. 196 */ 197 /*ARGSUSED */ 198 static void 199 window_change_handler(int sig) 200 { 201 received_window_change_signal = 1; 202 } 203 204 /* 205 * Signal handler for signals that cause the program to terminate. These 206 * signals must be trapped to restore terminal modes. 207 */ 208 /*ARGSUSED */ 209 static void 210 signal_handler(int sig) 211 { 212 received_signal = sig; 213 quit_pending = 1; 214 } 215 216 /* 217 * Sets control_persist_exit_time to the absolute time when the 218 * backgrounded control master should exit due to expiry of the 219 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded 220 * control master process, or if there is no ControlPersist timeout. 221 */ 222 static void 223 set_control_persist_exit_time(struct ssh *ssh) 224 { 225 if (muxserver_sock == -1 || !options.control_persist 226 || options.control_persist_timeout == 0) { 227 /* not using a ControlPersist timeout */ 228 control_persist_exit_time = 0; 229 } else if (channel_still_open(ssh)) { 230 /* some client connections are still open */ 231 if (control_persist_exit_time > 0) 232 debug2("%s: cancel scheduled exit", __func__); 233 control_persist_exit_time = 0; 234 } else if (control_persist_exit_time <= 0) { 235 /* a client connection has recently closed */ 236 control_persist_exit_time = monotime() + 237 (time_t)options.control_persist_timeout; 238 debug2("%s: schedule exit in %d seconds", __func__, 239 options.control_persist_timeout); 240 } 241 /* else we are already counting down to the timeout */ 242 } 243 244 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_" 245 static int 246 client_x11_display_valid(const char *display) 247 { 248 size_t i, dlen; 249 250 if (display == NULL) 251 return 0; 252 253 dlen = strlen(display); 254 for (i = 0; i < dlen; i++) { 255 if (!isalnum((u_char)display[i]) && 256 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) { 257 debug("Invalid character '%c' in DISPLAY", display[i]); 258 return 0; 259 } 260 } 261 return 1; 262 } 263 264 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1" 265 #define X11_TIMEOUT_SLACK 60 266 int 267 client_x11_get_proto(struct ssh *ssh, const char *display, 268 const char *xauth_path, u_int trusted, u_int timeout, 269 char **_proto, char **_data) 270 { 271 char *cmd, line[512], xdisplay[512]; 272 char xauthfile[PATH_MAX], xauthdir[PATH_MAX]; 273 static char proto[512], data[512]; 274 FILE *f; 275 int got_data = 0, generated = 0, do_unlink = 0, r; 276 struct stat st; 277 u_int now, x11_timeout_real; 278 279 *_proto = proto; 280 *_data = data; 281 proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0'; 282 283 if (!client_x11_display_valid(display)) { 284 if (display != NULL) 285 logit("DISPLAY \"%s\" invalid; disabling X11 forwarding", 286 display); 287 return -1; 288 } 289 if (xauth_path != NULL && stat(xauth_path, &st) == -1) { 290 debug("No xauth program."); 291 xauth_path = NULL; 292 } 293 294 if (xauth_path != NULL) { 295 /* 296 * Handle FamilyLocal case where $DISPLAY does 297 * not match an authorization entry. For this we 298 * just try "xauth list unix:displaynum.screennum". 299 * XXX: "localhost" match to determine FamilyLocal 300 * is not perfect. 301 */ 302 if (strncmp(display, "localhost:", 10) == 0) { 303 if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s", 304 display + 10)) < 0 || 305 (size_t)r >= sizeof(xdisplay)) { 306 error("%s: display name too long", __func__); 307 return -1; 308 } 309 display = xdisplay; 310 } 311 if (trusted == 0) { 312 /* 313 * Generate an untrusted X11 auth cookie. 314 * 315 * The authentication cookie should briefly outlive 316 * ssh's willingness to forward X11 connections to 317 * avoid nasty fail-open behaviour in the X server. 318 */ 319 mktemp_proto(xauthdir, sizeof(xauthdir)); 320 if (mkdtemp(xauthdir) == NULL) { 321 error("%s: mkdtemp: %s", 322 __func__, strerror(errno)); 323 return -1; 324 } 325 do_unlink = 1; 326 if ((r = snprintf(xauthfile, sizeof(xauthfile), 327 "%s/xauthfile", xauthdir)) < 0 || 328 (size_t)r >= sizeof(xauthfile)) { 329 error("%s: xauthfile path too long", __func__); 330 rmdir(xauthdir); 331 return -1; 332 } 333 334 if (timeout == 0) { 335 /* auth doesn't time out */ 336 xasprintf(&cmd, "%s -f %s generate %s %s " 337 "untrusted 2>%s", 338 xauth_path, xauthfile, display, 339 SSH_X11_PROTO, _PATH_DEVNULL); 340 } else { 341 /* Add some slack to requested expiry */ 342 if (timeout < UINT_MAX - X11_TIMEOUT_SLACK) 343 x11_timeout_real = timeout + 344 X11_TIMEOUT_SLACK; 345 else { 346 /* Don't overflow on long timeouts */ 347 x11_timeout_real = UINT_MAX; 348 } 349 xasprintf(&cmd, "%s -f %s generate %s %s " 350 "untrusted timeout %u 2>%s", 351 xauth_path, xauthfile, display, 352 SSH_X11_PROTO, x11_timeout_real, 353 _PATH_DEVNULL); 354 } 355 debug2("%s: xauth command: %s", __func__, cmd); 356 357 if (timeout != 0 && x11_refuse_time == 0) { 358 now = monotime() + 1; 359 if (UINT_MAX - timeout < now) 360 x11_refuse_time = UINT_MAX; 361 else 362 x11_refuse_time = now + timeout; 363 channel_set_x11_refuse_time(ssh, 364 x11_refuse_time); 365 } 366 if (system(cmd) == 0) 367 generated = 1; 368 free(cmd); 369 } 370 371 /* 372 * When in untrusted mode, we read the cookie only if it was 373 * successfully generated as an untrusted one in the step 374 * above. 375 */ 376 if (trusted || generated) { 377 xasprintf(&cmd, 378 "%s %s%s list %s 2>" _PATH_DEVNULL, 379 xauth_path, 380 generated ? "-f " : "" , 381 generated ? xauthfile : "", 382 display); 383 debug2("x11_get_proto: %s", cmd); 384 f = popen(cmd, "r"); 385 if (f && fgets(line, sizeof(line), f) && 386 sscanf(line, "%*s %511s %511s", proto, data) == 2) 387 got_data = 1; 388 if (f) 389 pclose(f); 390 free(cmd); 391 } 392 } 393 394 if (do_unlink) { 395 unlink(xauthfile); 396 rmdir(xauthdir); 397 } 398 399 /* Don't fall back to fake X11 data for untrusted forwarding */ 400 if (!trusted && !got_data) { 401 error("Warning: untrusted X11 forwarding setup failed: " 402 "xauth key data not generated"); 403 return -1; 404 } 405 406 /* 407 * If we didn't get authentication data, just make up some 408 * data. The forwarding code will check the validity of the 409 * response anyway, and substitute this data. The X11 410 * server, however, will ignore this fake data and use 411 * whatever authentication mechanisms it was using otherwise 412 * for the local connection. 413 */ 414 if (!got_data) { 415 u_int8_t rnd[16]; 416 u_int i; 417 418 logit("Warning: No xauth data; " 419 "using fake authentication data for X11 forwarding."); 420 strlcpy(proto, SSH_X11_PROTO, sizeof proto); 421 arc4random_buf(rnd, sizeof(rnd)); 422 for (i = 0; i < sizeof(rnd); i++) { 423 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", 424 rnd[i]); 425 } 426 } 427 428 return 0; 429 } 430 431 /* 432 * Checks if the client window has changed, and sends a packet about it to 433 * the server if so. The actual change is detected elsewhere (by a software 434 * interrupt on Unix); this just checks the flag and sends a message if 435 * appropriate. 436 */ 437 438 static void 439 client_check_window_change(struct ssh *ssh) 440 { 441 if (!received_window_change_signal) 442 return; 443 received_window_change_signal = 0; 444 debug2("%s: changed", __func__); 445 channel_send_window_changes(ssh); 446 } 447 448 static int 449 client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh) 450 { 451 struct global_confirm *gc; 452 453 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL) 454 return 0; 455 if (gc->cb != NULL) 456 gc->cb(ssh, type, seq, gc->ctx); 457 if (--gc->ref_count <= 0) { 458 TAILQ_REMOVE(&global_confirms, gc, entry); 459 freezero(gc, sizeof(*gc)); 460 } 461 462 ssh_packet_set_alive_timeouts(ssh, 0); 463 return 0; 464 } 465 466 static void 467 server_alive_check(struct ssh *ssh) 468 { 469 int r; 470 471 if (ssh_packet_inc_alive_timeouts(ssh) > options.server_alive_count_max) { 472 logit("Timeout, server %s not responding.", host); 473 cleanup_exit(255); 474 } 475 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 476 (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) != 0 || 477 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* boolean: want reply */ 478 (r = sshpkt_send(ssh)) != 0) 479 fatal("%s: send packet: %s", __func__, ssh_err(r)); 480 /* Insert an empty placeholder to maintain ordering */ 481 client_register_global_confirm(NULL, NULL); 482 } 483 484 /* 485 * Waits until the client can do something (some data becomes available on 486 * one of the file descriptors). 487 */ 488 static void 489 client_wait_until_can_do_something(struct ssh *ssh, 490 fd_set **readsetp, fd_set **writesetp, 491 int *maxfdp, u_int *nallocp, int rekeying) 492 { 493 struct timeval tv, *tvp; 494 int timeout_secs; 495 time_t minwait_secs = 0, server_alive_time = 0, now = monotime(); 496 int r, ret; 497 498 /* Add any selections by the channel mechanism. */ 499 channel_prepare_select(ssh, readsetp, writesetp, maxfdp, 500 nallocp, &minwait_secs); 501 502 /* channel_prepare_select could have closed the last channel */ 503 if (session_closed && !channel_still_open(ssh) && 504 !ssh_packet_have_data_to_write(ssh)) { 505 /* clear mask since we did not call select() */ 506 memset(*readsetp, 0, *nallocp); 507 memset(*writesetp, 0, *nallocp); 508 return; 509 } 510 511 FD_SET(connection_in, *readsetp); 512 513 /* Select server connection if have data to write to the server. */ 514 if (ssh_packet_have_data_to_write(ssh)) 515 FD_SET(connection_out, *writesetp); 516 517 /* 518 * Wait for something to happen. This will suspend the process until 519 * some selected descriptor can be read, written, or has some other 520 * event pending, or a timeout expires. 521 */ 522 523 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */ 524 if (options.server_alive_interval > 0) { 525 timeout_secs = options.server_alive_interval; 526 server_alive_time = now + options.server_alive_interval; 527 } 528 if (options.rekey_interval > 0 && !rekeying) 529 timeout_secs = MINIMUM(timeout_secs, 530 ssh_packet_get_rekey_timeout(ssh)); 531 set_control_persist_exit_time(ssh); 532 if (control_persist_exit_time > 0) { 533 timeout_secs = MINIMUM(timeout_secs, 534 control_persist_exit_time - now); 535 if (timeout_secs < 0) 536 timeout_secs = 0; 537 } 538 if (minwait_secs != 0) 539 timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs); 540 if (timeout_secs == INT_MAX) 541 tvp = NULL; 542 else { 543 tv.tv_sec = timeout_secs; 544 tv.tv_usec = 0; 545 tvp = &tv; 546 } 547 548 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp); 549 if (ret == -1) { 550 /* 551 * We have to clear the select masks, because we return. 552 * We have to return, because the mainloop checks for the flags 553 * set by the signal handlers. 554 */ 555 memset(*readsetp, 0, *nallocp); 556 memset(*writesetp, 0, *nallocp); 557 558 if (errno == EINTR) 559 return; 560 /* Note: we might still have data in the buffers. */ 561 if ((r = sshbuf_putf(stderr_buffer, 562 "select: %s\r\n", strerror(errno))) != 0) 563 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 564 quit_pending = 1; 565 } else if (ret == 0) { 566 /* 567 * Timeout. Could have been either keepalive or rekeying. 568 * Keepalive we check here, rekeying is checked in clientloop. 569 */ 570 if (server_alive_time != 0 && server_alive_time <= monotime()) 571 server_alive_check(ssh); 572 } 573 574 } 575 576 static void 577 client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr) 578 { 579 /* Flush stdout and stderr buffers. */ 580 if (sshbuf_len(bout) > 0) 581 atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout), 582 sshbuf_len(bout)); 583 if (sshbuf_len(berr) > 0) 584 atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr), 585 sshbuf_len(berr)); 586 587 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 588 589 sshbuf_reset(bin); 590 sshbuf_reset(bout); 591 sshbuf_reset(berr); 592 593 /* Send the suspend signal to the program itself. */ 594 kill(getpid(), SIGTSTP); 595 596 /* Reset window sizes in case they have changed */ 597 received_window_change_signal = 1; 598 599 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 600 } 601 602 static void 603 client_process_net_input(struct ssh *ssh, fd_set *readset) 604 { 605 char buf[8192]; 606 int r, len; 607 608 /* 609 * Read input from the server, and add any such data to the buffer of 610 * the packet subsystem. 611 */ 612 if (FD_ISSET(connection_in, readset)) { 613 /* Read as much as possible. */ 614 len = read(connection_in, buf, sizeof(buf)); 615 if (len == 0) { 616 /* 617 * Received EOF. The remote host has closed the 618 * connection. 619 */ 620 if ((r = sshbuf_putf(stderr_buffer, 621 "Connection to %.300s closed by remote host.\r\n", 622 host)) != 0) 623 fatal("%s: buffer error: %s", 624 __func__, ssh_err(r)); 625 quit_pending = 1; 626 return; 627 } 628 /* 629 * There is a kernel bug on Solaris that causes select to 630 * sometimes wake up even though there is no data available. 631 */ 632 if (len == -1 && (errno == EAGAIN || errno == EINTR)) 633 len = 0; 634 635 if (len == -1) { 636 /* 637 * An error has encountered. Perhaps there is a 638 * network problem. 639 */ 640 if ((r = sshbuf_putf(stderr_buffer, 641 "Read from remote host %.300s: %.100s\r\n", 642 host, strerror(errno))) != 0) 643 fatal("%s: buffer error: %s", 644 __func__, ssh_err(r)); 645 quit_pending = 1; 646 return; 647 } 648 ssh_packet_process_incoming(ssh, buf, len); 649 } 650 } 651 652 static void 653 client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx) 654 { 655 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx; 656 char errmsg[256]; 657 int r, tochan; 658 659 /* 660 * If a TTY was explicitly requested, then a failure to allocate 661 * one is fatal. 662 */ 663 if (cr->action == CONFIRM_TTY && 664 (options.request_tty == REQUEST_TTY_FORCE || 665 options.request_tty == REQUEST_TTY_YES)) 666 cr->action = CONFIRM_CLOSE; 667 668 /* XXX suppress on mux _client_ quietmode */ 669 tochan = options.log_level >= SYSLOG_LEVEL_ERROR && 670 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE; 671 672 if (type == SSH2_MSG_CHANNEL_SUCCESS) { 673 debug2("%s request accepted on channel %d", 674 cr->request_type, c->self); 675 } else if (type == SSH2_MSG_CHANNEL_FAILURE) { 676 if (tochan) { 677 snprintf(errmsg, sizeof(errmsg), 678 "%s request failed\r\n", cr->request_type); 679 } else { 680 snprintf(errmsg, sizeof(errmsg), 681 "%s request failed on channel %d", 682 cr->request_type, c->self); 683 } 684 /* If error occurred on primary session channel, then exit */ 685 if (cr->action == CONFIRM_CLOSE && c->self == session_ident) 686 fatal("%s", errmsg); 687 /* 688 * If error occurred on mux client, append to 689 * their stderr. 690 */ 691 if (tochan) { 692 if ((r = sshbuf_put(c->extended, errmsg, 693 strlen(errmsg))) != 0) 694 fatal("%s: buffer error %s", __func__, 695 ssh_err(r)); 696 } else 697 error("%s", errmsg); 698 if (cr->action == CONFIRM_TTY) { 699 /* 700 * If a TTY allocation error occurred, then arrange 701 * for the correct TTY to leave raw mode. 702 */ 703 if (c->self == session_ident) 704 leave_raw_mode(0); 705 else 706 mux_tty_alloc_failed(ssh, c); 707 } else if (cr->action == CONFIRM_CLOSE) { 708 chan_read_failed(ssh, c); 709 chan_write_failed(ssh, c); 710 } 711 } 712 free(cr); 713 } 714 715 static void 716 client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx) 717 { 718 free(ctx); 719 } 720 721 void 722 client_expect_confirm(struct ssh *ssh, int id, const char *request, 723 enum confirm_action action) 724 { 725 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr)); 726 727 cr->request_type = request; 728 cr->action = action; 729 730 channel_register_status_confirm(ssh, id, client_status_confirm, 731 client_abandon_status_confirm, cr); 732 } 733 734 void 735 client_register_global_confirm(global_confirm_cb *cb, void *ctx) 736 { 737 struct global_confirm *gc, *last_gc; 738 739 /* Coalesce identical callbacks */ 740 last_gc = TAILQ_LAST(&global_confirms, global_confirms); 741 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) { 742 if (++last_gc->ref_count >= INT_MAX) 743 fatal("%s: last_gc->ref_count = %d", 744 __func__, last_gc->ref_count); 745 return; 746 } 747 748 gc = xcalloc(1, sizeof(*gc)); 749 gc->cb = cb; 750 gc->ctx = ctx; 751 gc->ref_count = 1; 752 TAILQ_INSERT_TAIL(&global_confirms, gc, entry); 753 } 754 755 static void 756 process_cmdline(struct ssh *ssh) 757 { 758 void (*handler)(int); 759 char *s, *cmd; 760 int ok, delete = 0, local = 0, remote = 0, dynamic = 0; 761 struct Forward fwd; 762 763 memset(&fwd, 0, sizeof(fwd)); 764 765 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 766 handler = ssh_signal(SIGINT, SIG_IGN); 767 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO); 768 if (s == NULL) 769 goto out; 770 while (isspace((u_char)*s)) 771 s++; 772 if (*s == '-') 773 s++; /* Skip cmdline '-', if any */ 774 if (*s == '\0') 775 goto out; 776 777 if (*s == 'h' || *s == 'H' || *s == '?') { 778 logit("Commands:"); 779 logit(" -L[bind_address:]port:host:hostport " 780 "Request local forward"); 781 logit(" -R[bind_address:]port:host:hostport " 782 "Request remote forward"); 783 logit(" -D[bind_address:]port " 784 "Request dynamic forward"); 785 logit(" -KL[bind_address:]port " 786 "Cancel local forward"); 787 logit(" -KR[bind_address:]port " 788 "Cancel remote forward"); 789 logit(" -KD[bind_address:]port " 790 "Cancel dynamic forward"); 791 if (!options.permit_local_command) 792 goto out; 793 logit(" !args " 794 "Execute local command"); 795 goto out; 796 } 797 798 if (*s == '!' && options.permit_local_command) { 799 s++; 800 ssh_local_cmd(s); 801 goto out; 802 } 803 804 if (*s == 'K') { 805 delete = 1; 806 s++; 807 } 808 if (*s == 'L') 809 local = 1; 810 else if (*s == 'R') 811 remote = 1; 812 else if (*s == 'D') 813 dynamic = 1; 814 else { 815 logit("Invalid command."); 816 goto out; 817 } 818 819 while (isspace((u_char)*++s)) 820 ; 821 822 /* XXX update list of forwards in options */ 823 if (delete) { 824 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */ 825 if (!parse_forward(&fwd, s, 1, 0)) { 826 logit("Bad forwarding close specification."); 827 goto out; 828 } 829 if (remote) 830 ok = channel_request_rforward_cancel(ssh, &fwd) == 0; 831 else if (dynamic) 832 ok = channel_cancel_lport_listener(ssh, &fwd, 833 0, &options.fwd_opts) > 0; 834 else 835 ok = channel_cancel_lport_listener(ssh, &fwd, 836 CHANNEL_CANCEL_PORT_STATIC, 837 &options.fwd_opts) > 0; 838 if (!ok) { 839 logit("Unknown port forwarding."); 840 goto out; 841 } 842 logit("Canceled forwarding."); 843 } else { 844 if (!parse_forward(&fwd, s, dynamic, remote)) { 845 logit("Bad forwarding specification."); 846 goto out; 847 } 848 if (local || dynamic) { 849 if (!channel_setup_local_fwd_listener(ssh, &fwd, 850 &options.fwd_opts)) { 851 logit("Port forwarding failed."); 852 goto out; 853 } 854 } else { 855 if (channel_request_remote_forwarding(ssh, &fwd) < 0) { 856 logit("Port forwarding failed."); 857 goto out; 858 } 859 } 860 logit("Forwarding port."); 861 } 862 863 out: 864 ssh_signal(SIGINT, handler); 865 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 866 free(cmd); 867 free(fwd.listen_host); 868 free(fwd.listen_path); 869 free(fwd.connect_host); 870 free(fwd.connect_path); 871 } 872 873 /* reasons to suppress output of an escape command in help output */ 874 #define SUPPRESS_NEVER 0 /* never suppress, always show */ 875 #define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */ 876 #define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */ 877 #define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */ 878 struct escape_help_text { 879 const char *cmd; 880 const char *text; 881 unsigned int flags; 882 }; 883 static struct escape_help_text esc_txt[] = { 884 {".", "terminate session", SUPPRESS_MUXMASTER}, 885 {".", "terminate connection (and any multiplexed sessions)", 886 SUPPRESS_MUXCLIENT}, 887 {"B", "send a BREAK to the remote system", SUPPRESS_NEVER}, 888 {"C", "open a command line", SUPPRESS_MUXCLIENT}, 889 {"R", "request rekey", SUPPRESS_NEVER}, 890 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT}, 891 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT}, 892 {"#", "list forwarded connections", SUPPRESS_NEVER}, 893 {"&", "background ssh (when waiting for connections to terminate)", 894 SUPPRESS_MUXCLIENT}, 895 {"?", "this message", SUPPRESS_NEVER}, 896 }; 897 898 static void 899 print_escape_help(struct sshbuf *b, int escape_char, int mux_client, 900 int using_stderr) 901 { 902 unsigned int i, suppress_flags; 903 int r; 904 905 if ((r = sshbuf_putf(b, 906 "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0) 907 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 908 909 suppress_flags = 910 (mux_client ? SUPPRESS_MUXCLIENT : 0) | 911 (mux_client ? 0 : SUPPRESS_MUXMASTER) | 912 (using_stderr ? 0 : SUPPRESS_SYSLOG); 913 914 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) { 915 if (esc_txt[i].flags & suppress_flags) 916 continue; 917 if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n", 918 escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0) 919 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 920 } 921 922 if ((r = sshbuf_putf(b, 923 " %c%c - send the escape character by typing it twice\r\n" 924 "(Note that escapes are only recognized immediately after " 925 "newline.)\r\n", escape_char, escape_char)) != 0) 926 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 927 } 928 929 /* 930 * Process the characters one by one. 931 */ 932 static int 933 process_escapes(struct ssh *ssh, Channel *c, 934 struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr, 935 const char *buf, int len) 936 { 937 pid_t pid; 938 int r, bytes = 0; 939 u_int i; 940 u_char ch; 941 char *s; 942 struct escape_filter_ctx *efc = c->filter_ctx == NULL ? 943 NULL : (struct escape_filter_ctx *)c->filter_ctx; 944 945 if (c->filter_ctx == NULL) 946 return 0; 947 948 if (len <= 0) 949 return (0); 950 951 for (i = 0; i < (u_int)len; i++) { 952 /* Get one character at a time. */ 953 ch = buf[i]; 954 955 if (efc->escape_pending) { 956 /* We have previously seen an escape character. */ 957 /* Clear the flag now. */ 958 efc->escape_pending = 0; 959 960 /* Process the escaped character. */ 961 switch (ch) { 962 case '.': 963 /* Terminate the connection. */ 964 if ((r = sshbuf_putf(berr, "%c.\r\n", 965 efc->escape_char)) != 0) 966 fatal("%s: buffer error: %s", 967 __func__, ssh_err(r)); 968 if (c && c->ctl_chan != -1) { 969 chan_read_failed(ssh, c); 970 chan_write_failed(ssh, c); 971 if (c->detach_user) { 972 c->detach_user(ssh, 973 c->self, NULL); 974 } 975 c->type = SSH_CHANNEL_ABANDONED; 976 sshbuf_reset(c->input); 977 chan_ibuf_empty(ssh, c); 978 return 0; 979 } else 980 quit_pending = 1; 981 return -1; 982 983 case 'Z' - 64: 984 /* XXX support this for mux clients */ 985 if (c && c->ctl_chan != -1) { 986 char b[16]; 987 noescape: 988 if (ch == 'Z' - 64) 989 snprintf(b, sizeof b, "^Z"); 990 else 991 snprintf(b, sizeof b, "%c", ch); 992 if ((r = sshbuf_putf(berr, 993 "%c%s escape not available to " 994 "multiplexed sessions\r\n", 995 efc->escape_char, b)) != 0) 996 fatal("%s: buffer error: %s", 997 __func__, ssh_err(r)); 998 continue; 999 } 1000 /* Suspend the program. Inform the user */ 1001 if ((r = sshbuf_putf(berr, 1002 "%c^Z [suspend ssh]\r\n", 1003 efc->escape_char)) != 0) 1004 fatal("%s: buffer error: %s", 1005 __func__, ssh_err(r)); 1006 1007 /* Restore terminal modes and suspend. */ 1008 client_suspend_self(bin, bout, berr); 1009 1010 /* We have been continued. */ 1011 continue; 1012 1013 case 'B': 1014 if ((r = sshbuf_putf(berr, 1015 "%cB\r\n", efc->escape_char)) != 0) 1016 fatal("%s: buffer error: %s", 1017 __func__, ssh_err(r)); 1018 channel_request_start(ssh, c->self, "break", 0); 1019 if ((r = sshpkt_put_u32(ssh, 1000)) != 0 || 1020 (r = sshpkt_send(ssh)) != 0) 1021 fatal("%s: send packet: %s", __func__, 1022 ssh_err(r)); 1023 continue; 1024 1025 case 'R': 1026 if (datafellows & SSH_BUG_NOREKEY) 1027 logit("Server does not " 1028 "support re-keying"); 1029 else 1030 need_rekeying = 1; 1031 continue; 1032 1033 case 'V': 1034 /* FALLTHROUGH */ 1035 case 'v': 1036 if (c && c->ctl_chan != -1) 1037 goto noescape; 1038 if (!log_is_on_stderr()) { 1039 if ((r = sshbuf_putf(berr, 1040 "%c%c [Logging to syslog]\r\n", 1041 efc->escape_char, ch)) != 0) 1042 fatal("%s: buffer error: %s", 1043 __func__, ssh_err(r)); 1044 continue; 1045 } 1046 if (ch == 'V' && options.log_level > 1047 SYSLOG_LEVEL_QUIET) 1048 log_change_level(--options.log_level); 1049 if (ch == 'v' && options.log_level < 1050 SYSLOG_LEVEL_DEBUG3) 1051 log_change_level(++options.log_level); 1052 if ((r = sshbuf_putf(berr, 1053 "%c%c [LogLevel %s]\r\n", 1054 efc->escape_char, ch, 1055 log_level_name(options.log_level))) != 0) 1056 fatal("%s: buffer error: %s", 1057 __func__, ssh_err(r)); 1058 continue; 1059 1060 case '&': 1061 if (c && c->ctl_chan != -1) 1062 goto noescape; 1063 /* 1064 * Detach the program (continue to serve 1065 * connections, but put in background and no 1066 * more new connections). 1067 */ 1068 /* Restore tty modes. */ 1069 leave_raw_mode( 1070 options.request_tty == REQUEST_TTY_FORCE); 1071 1072 /* Stop listening for new connections. */ 1073 channel_stop_listening(ssh); 1074 1075 if ((r = sshbuf_putf(berr, 1076 "%c& [backgrounded]\n", efc->escape_char)) 1077 != 0) 1078 fatal("%s: buffer error: %s", 1079 __func__, ssh_err(r)); 1080 1081 /* Fork into background. */ 1082 pid = fork(); 1083 if (pid == -1) { 1084 error("fork: %.100s", strerror(errno)); 1085 continue; 1086 } 1087 if (pid != 0) { /* This is the parent. */ 1088 /* The parent just exits. */ 1089 exit(0); 1090 } 1091 /* The child continues serving connections. */ 1092 /* fake EOF on stdin */ 1093 if ((r = sshbuf_put_u8(bin, 4)) != 0) 1094 fatal("%s: buffer error: %s", 1095 __func__, ssh_err(r)); 1096 return -1; 1097 case '?': 1098 print_escape_help(berr, efc->escape_char, 1099 (c && c->ctl_chan != -1), 1100 log_is_on_stderr()); 1101 continue; 1102 1103 case '#': 1104 if ((r = sshbuf_putf(berr, "%c#\r\n", 1105 efc->escape_char)) != 0) 1106 fatal("%s: buffer error: %s", 1107 __func__, ssh_err(r)); 1108 s = channel_open_message(ssh); 1109 if ((r = sshbuf_put(berr, s, strlen(s))) != 0) 1110 fatal("%s: buffer error: %s", 1111 __func__, ssh_err(r)); 1112 free(s); 1113 continue; 1114 1115 case 'C': 1116 if (c && c->ctl_chan != -1) 1117 goto noescape; 1118 process_cmdline(ssh); 1119 continue; 1120 1121 default: 1122 if (ch != efc->escape_char) { 1123 if ((r = sshbuf_put_u8(bin, 1124 efc->escape_char)) != 0) 1125 fatal("%s: buffer error: %s", 1126 __func__, ssh_err(r)); 1127 bytes++; 1128 } 1129 /* Escaped characters fall through here */ 1130 break; 1131 } 1132 } else { 1133 /* 1134 * The previous character was not an escape char. 1135 * Check if this is an escape. 1136 */ 1137 if (last_was_cr && ch == efc->escape_char) { 1138 /* 1139 * It is. Set the flag and continue to 1140 * next character. 1141 */ 1142 efc->escape_pending = 1; 1143 continue; 1144 } 1145 } 1146 1147 /* 1148 * Normal character. Record whether it was a newline, 1149 * and append it to the buffer. 1150 */ 1151 last_was_cr = (ch == '\r' || ch == '\n'); 1152 if ((r = sshbuf_put_u8(bin, ch)) != 0) 1153 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 1154 bytes++; 1155 } 1156 return bytes; 1157 } 1158 1159 /* 1160 * Get packets from the connection input buffer, and process them as long as 1161 * there are packets available. 1162 * 1163 * Any unknown packets received during the actual 1164 * session cause the session to terminate. This is 1165 * intended to make debugging easier since no 1166 * confirmations are sent. Any compatible protocol 1167 * extensions must be negotiated during the 1168 * preparatory phase. 1169 */ 1170 1171 static void 1172 client_process_buffered_input_packets(struct ssh *ssh) 1173 { 1174 ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, &quit_pending); 1175 } 1176 1177 /* scan buf[] for '~' before sending data to the peer */ 1178 1179 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */ 1180 void * 1181 client_new_escape_filter_ctx(int escape_char) 1182 { 1183 struct escape_filter_ctx *ret; 1184 1185 ret = xcalloc(1, sizeof(*ret)); 1186 ret->escape_pending = 0; 1187 ret->escape_char = escape_char; 1188 return (void *)ret; 1189 } 1190 1191 /* Free the escape filter context on channel free */ 1192 void 1193 client_filter_cleanup(struct ssh *ssh, int cid, void *ctx) 1194 { 1195 free(ctx); 1196 } 1197 1198 int 1199 client_simple_escape_filter(struct ssh *ssh, Channel *c, const char *buf, 1200 int len) 1201 { 1202 if (c->extended_usage != CHAN_EXTENDED_WRITE) 1203 return 0; 1204 1205 return process_escapes(ssh, c, c->input, c->output, c->extended, 1206 buf, len); 1207 } 1208 1209 static void 1210 client_channel_closed(struct ssh *ssh, int id, void *arg) 1211 { 1212 channel_cancel_cleanup(ssh, id); 1213 session_closed = 1; 1214 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1215 } 1216 1217 /* 1218 * Implements the interactive session with the server. This is called after 1219 * the user has been authenticated, and a command has been started on the 1220 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character 1221 * used as an escape character for terminating or suspending the session. 1222 */ 1223 int 1224 client_loop(struct ssh *ssh, int have_pty, int escape_char_arg, 1225 int ssh2_chan_id) 1226 { 1227 fd_set *readset = NULL, *writeset = NULL; 1228 double start_time, total_time; 1229 int r, max_fd = 0, max_fd2 = 0, len; 1230 u_int64_t ibytes, obytes; 1231 u_int nalloc = 0; 1232 char buf[100]; 1233 1234 debug("Entering interactive session."); 1235 1236 #ifdef __OpenBSD__ 1237 if (options.control_master && 1238 !option_clear_or_none(options.control_path)) { 1239 debug("pledge: id"); 1240 if (pledge("stdio rpath wpath cpath unix inet dns recvfd sendfd proc exec id tty", 1241 NULL) == -1) 1242 fatal("%s pledge(): %s", __func__, strerror(errno)); 1243 1244 } else if (options.forward_x11 || options.permit_local_command) { 1245 debug("pledge: exec"); 1246 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty", 1247 NULL) == -1) 1248 fatal("%s pledge(): %s", __func__, strerror(errno)); 1249 1250 } else if (options.update_hostkeys) { 1251 debug("pledge: filesystem full"); 1252 if (pledge("stdio rpath wpath cpath unix inet dns proc tty", 1253 NULL) == -1) 1254 fatal("%s pledge(): %s", __func__, strerror(errno)); 1255 1256 } else if (!option_clear_or_none(options.proxy_command) || 1257 fork_after_authentication_flag) { 1258 debug("pledge: proc"); 1259 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1) 1260 fatal("%s pledge(): %s", __func__, strerror(errno)); 1261 1262 } else { 1263 debug("pledge: network"); 1264 if (pledge("stdio unix inet dns proc tty", NULL) == -1) 1265 fatal("%s pledge(): %s", __func__, strerror(errno)); 1266 } 1267 #endif 1268 1269 start_time = monotime_double(); 1270 1271 /* Initialize variables. */ 1272 last_was_cr = 1; 1273 exit_status = -1; 1274 connection_in = ssh_packet_get_connection_in(ssh); 1275 connection_out = ssh_packet_get_connection_out(ssh); 1276 max_fd = MAXIMUM(connection_in, connection_out); 1277 1278 quit_pending = 0; 1279 1280 /* Initialize buffer. */ 1281 if ((stderr_buffer = sshbuf_new()) == NULL) 1282 fatal("%s: sshbuf_new failed", __func__); 1283 1284 client_init_dispatch(ssh); 1285 1286 /* 1287 * Set signal handlers, (e.g. to restore non-blocking mode) 1288 * but don't overwrite SIG_IGN, matches behaviour from rsh(1) 1289 */ 1290 if (ssh_signal(SIGHUP, SIG_IGN) != SIG_IGN) 1291 ssh_signal(SIGHUP, signal_handler); 1292 if (ssh_signal(SIGINT, SIG_IGN) != SIG_IGN) 1293 ssh_signal(SIGINT, signal_handler); 1294 if (ssh_signal(SIGQUIT, SIG_IGN) != SIG_IGN) 1295 ssh_signal(SIGQUIT, signal_handler); 1296 if (ssh_signal(SIGTERM, SIG_IGN) != SIG_IGN) 1297 ssh_signal(SIGTERM, signal_handler); 1298 ssh_signal(SIGWINCH, window_change_handler); 1299 1300 if (have_pty) 1301 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1302 1303 session_ident = ssh2_chan_id; 1304 if (session_ident != -1) { 1305 if (escape_char_arg != SSH_ESCAPECHAR_NONE) { 1306 channel_register_filter(ssh, session_ident, 1307 client_simple_escape_filter, NULL, 1308 client_filter_cleanup, 1309 client_new_escape_filter_ctx( 1310 escape_char_arg)); 1311 } 1312 channel_register_cleanup(ssh, session_ident, 1313 client_channel_closed, 0); 1314 } 1315 1316 /* Main loop of the client for the interactive session mode. */ 1317 while (!quit_pending) { 1318 1319 /* Process buffered packets sent by the server. */ 1320 client_process_buffered_input_packets(ssh); 1321 1322 if (session_closed && !channel_still_open(ssh)) 1323 break; 1324 1325 if (ssh_packet_is_rekeying(ssh)) { 1326 debug("rekeying in progress"); 1327 } else if (need_rekeying) { 1328 /* manual rekey request */ 1329 debug("need rekeying"); 1330 if ((r = kex_start_rekex(ssh)) != 0) 1331 fatal("%s: kex_start_rekex: %s", __func__, 1332 ssh_err(r)); 1333 need_rekeying = 0; 1334 } else { 1335 /* 1336 * Make packets from buffered channel data, and 1337 * enqueue them for sending to the server. 1338 */ 1339 if (ssh_packet_not_very_much_data_to_write(ssh)) 1340 channel_output_poll(ssh); 1341 1342 /* 1343 * Check if the window size has changed, and buffer a 1344 * message about it to the server if so. 1345 */ 1346 client_check_window_change(ssh); 1347 1348 if (quit_pending) 1349 break; 1350 } 1351 /* 1352 * Wait until we have something to do (something becomes 1353 * available on one of the descriptors). 1354 */ 1355 max_fd2 = max_fd; 1356 client_wait_until_can_do_something(ssh, &readset, &writeset, 1357 &max_fd2, &nalloc, ssh_packet_is_rekeying(ssh)); 1358 1359 if (quit_pending) 1360 break; 1361 1362 /* Do channel operations unless rekeying in progress. */ 1363 if (!ssh_packet_is_rekeying(ssh)) 1364 channel_after_select(ssh, readset, writeset); 1365 1366 /* Buffer input from the connection. */ 1367 client_process_net_input(ssh, readset); 1368 1369 if (quit_pending) 1370 break; 1371 1372 /* 1373 * Send as much buffered packet data as possible to the 1374 * sender. 1375 */ 1376 if (FD_ISSET(connection_out, writeset)) { 1377 if ((r = ssh_packet_write_poll(ssh)) < 0) { 1378 sshpkt_fatal(ssh, r, 1379 "%s: ssh_packet_write_poll", __func__); 1380 } 1381 } 1382 1383 /* 1384 * If we are a backgrounded control master, and the 1385 * timeout has expired without any active client 1386 * connections, then quit. 1387 */ 1388 if (control_persist_exit_time > 0) { 1389 if (monotime() >= control_persist_exit_time) { 1390 debug("ControlPersist timeout expired"); 1391 break; 1392 } 1393 } 1394 } 1395 free(readset); 1396 free(writeset); 1397 1398 /* Terminate the session. */ 1399 1400 /* Stop watching for window change. */ 1401 ssh_signal(SIGWINCH, SIG_DFL); 1402 1403 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 || 1404 (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_BY_APPLICATION)) != 0 || 1405 (r = sshpkt_put_cstring(ssh, "disconnected by user")) != 0 || 1406 (r = sshpkt_put_cstring(ssh, "")) != 0 || /* language tag */ 1407 (r = sshpkt_send(ssh)) != 0 || 1408 (r = ssh_packet_write_wait(ssh)) < 0) 1409 fatal("%s: send disconnect: %s", __func__, ssh_err(r)); 1410 1411 channel_free_all(ssh); 1412 1413 if (have_pty) 1414 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1415 1416 /* restore blocking io */ 1417 if (!isatty(fileno(stdin))) 1418 unset_nonblock(fileno(stdin)); 1419 if (!isatty(fileno(stdout))) 1420 unset_nonblock(fileno(stdout)); 1421 if (!isatty(fileno(stderr))) 1422 unset_nonblock(fileno(stderr)); 1423 1424 /* 1425 * If there was no shell or command requested, there will be no remote 1426 * exit status to be returned. In that case, clear error code if the 1427 * connection was deliberately terminated at this end. 1428 */ 1429 if (no_shell_flag && received_signal == SIGTERM) { 1430 received_signal = 0; 1431 exit_status = 0; 1432 } 1433 1434 if (received_signal) { 1435 verbose("Killed by signal %d.", (int) received_signal); 1436 cleanup_exit(0); 1437 } 1438 1439 /* 1440 * In interactive mode (with pseudo tty) display a message indicating 1441 * that the connection has been closed. 1442 */ 1443 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) { 1444 if ((r = sshbuf_putf(stderr_buffer, 1445 "Connection to %.64s closed.\r\n", host)) != 0) 1446 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 1447 } 1448 1449 /* Output any buffered data for stderr. */ 1450 if (sshbuf_len(stderr_buffer) > 0) { 1451 len = atomicio(vwrite, fileno(stderr), 1452 sshbuf_mutable_ptr(stderr_buffer), 1453 sshbuf_len(stderr_buffer)); 1454 if (len < 0 || (u_int)len != sshbuf_len(stderr_buffer)) 1455 error("Write failed flushing stderr buffer."); 1456 else if ((r = sshbuf_consume(stderr_buffer, len)) != 0) 1457 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 1458 } 1459 1460 /* Clear and free any buffers. */ 1461 explicit_bzero(buf, sizeof(buf)); 1462 sshbuf_free(stderr_buffer); 1463 1464 /* Report bytes transferred, and transfer rates. */ 1465 total_time = monotime_double() - start_time; 1466 ssh_packet_get_bytes(ssh, &ibytes, &obytes); 1467 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds", 1468 (unsigned long long)obytes, (unsigned long long)ibytes, total_time); 1469 if (total_time > 0) 1470 verbose("Bytes per second: sent %.1f, received %.1f", 1471 obytes / total_time, ibytes / total_time); 1472 /* Return the exit status of the program. */ 1473 debug("Exit status %d", exit_status); 1474 return exit_status; 1475 } 1476 1477 /*********/ 1478 1479 static Channel * 1480 client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type, 1481 int rchan, u_int rwindow, u_int rmaxpack) 1482 { 1483 Channel *c = NULL; 1484 struct sshbuf *b = NULL; 1485 char *listen_address, *originator_address; 1486 u_int listen_port, originator_port; 1487 int r; 1488 1489 /* Get rest of the packet */ 1490 if ((r = sshpkt_get_cstring(ssh, &listen_address, NULL)) != 0 || 1491 (r = sshpkt_get_u32(ssh, &listen_port)) != 0 || 1492 (r = sshpkt_get_cstring(ssh, &originator_address, NULL)) != 0 || 1493 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 || 1494 (r = sshpkt_get_end(ssh)) != 0) 1495 fatal("%s: parse packet: %s", __func__, ssh_err(r)); 1496 1497 debug("%s: listen %s port %d, originator %s port %d", __func__, 1498 listen_address, listen_port, originator_address, originator_port); 1499 1500 if (listen_port > 0xffff) 1501 error("%s: invalid listen port", __func__); 1502 else if (originator_port > 0xffff) 1503 error("%s: invalid originator port", __func__); 1504 else { 1505 c = channel_connect_by_listen_address(ssh, 1506 listen_address, listen_port, "forwarded-tcpip", 1507 originator_address); 1508 } 1509 1510 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) { 1511 if ((b = sshbuf_new()) == NULL) { 1512 error("%s: alloc reply", __func__); 1513 goto out; 1514 } 1515 /* reconstruct and send to muxclient */ 1516 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */ 1517 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 || 1518 (r = sshbuf_put_cstring(b, request_type)) != 0 || 1519 (r = sshbuf_put_u32(b, rchan)) != 0 || 1520 (r = sshbuf_put_u32(b, rwindow)) != 0 || 1521 (r = sshbuf_put_u32(b, rmaxpack)) != 0 || 1522 (r = sshbuf_put_cstring(b, listen_address)) != 0 || 1523 (r = sshbuf_put_u32(b, listen_port)) != 0 || 1524 (r = sshbuf_put_cstring(b, originator_address)) != 0 || 1525 (r = sshbuf_put_u32(b, originator_port)) != 0 || 1526 (r = sshbuf_put_stringb(c->output, b)) != 0) { 1527 error("%s: compose for muxclient %s", __func__, 1528 ssh_err(r)); 1529 goto out; 1530 } 1531 } 1532 1533 out: 1534 sshbuf_free(b); 1535 free(originator_address); 1536 free(listen_address); 1537 return c; 1538 } 1539 1540 static Channel * 1541 client_request_forwarded_streamlocal(struct ssh *ssh, 1542 const char *request_type, int rchan) 1543 { 1544 Channel *c = NULL; 1545 char *listen_path; 1546 int r; 1547 1548 /* Get the remote path. */ 1549 if ((r = sshpkt_get_cstring(ssh, &listen_path, NULL)) != 0 || 1550 (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 || /* reserved */ 1551 (r = sshpkt_get_end(ssh)) != 0) 1552 fatal("%s: parse packet: %s", __func__, ssh_err(r)); 1553 1554 debug("%s: request: %s", __func__, listen_path); 1555 1556 c = channel_connect_by_listen_path(ssh, listen_path, 1557 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal"); 1558 free(listen_path); 1559 return c; 1560 } 1561 1562 static Channel * 1563 client_request_x11(struct ssh *ssh, const char *request_type, int rchan) 1564 { 1565 Channel *c = NULL; 1566 char *originator; 1567 u_int originator_port; 1568 int r, sock; 1569 1570 if (!options.forward_x11) { 1571 error("Warning: ssh server tried X11 forwarding."); 1572 error("Warning: this is probably a break-in attempt by a " 1573 "malicious server."); 1574 return NULL; 1575 } 1576 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) { 1577 verbose("Rejected X11 connection after ForwardX11Timeout " 1578 "expired"); 1579 return NULL; 1580 } 1581 if ((r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 || 1582 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 || 1583 (r = sshpkt_get_end(ssh)) != 0) 1584 fatal("%s: parse packet: %s", __func__, ssh_err(r)); 1585 /* XXX check permission */ 1586 /* XXX range check originator port? */ 1587 debug("client_request_x11: request from %s %u", originator, 1588 originator_port); 1589 free(originator); 1590 sock = x11_connect_display(ssh); 1591 if (sock < 0) 1592 return NULL; 1593 /* again is this really necessary for X11? */ 1594 if (options.hpn_disabled) 1595 c = channel_new(ssh, "x11", 1596 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 1597 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1); 1598 else 1599 c = channel_new(ssh, "x11", 1600 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 1601 options.hpn_buffer_size, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1); 1602 c->force_drain = 1; 1603 return c; 1604 } 1605 1606 static Channel * 1607 client_request_agent(struct ssh *ssh, const char *request_type, int rchan) 1608 { 1609 Channel *c = NULL; 1610 int r, sock; 1611 1612 if (!options.forward_agent) { 1613 error("Warning: ssh server tried agent forwarding."); 1614 error("Warning: this is probably a break-in attempt by a " 1615 "malicious server."); 1616 return NULL; 1617 } 1618 if (forward_agent_sock_path == NULL) { 1619 r = ssh_get_authentication_socket(&sock); 1620 } else { 1621 r = ssh_get_authentication_socket_path(forward_agent_sock_path, &sock); 1622 } 1623 if (r != 0) { 1624 if (r != SSH_ERR_AGENT_NOT_PRESENT) 1625 debug("%s: ssh_get_authentication_socket: %s", 1626 __func__, ssh_err(r)); 1627 return NULL; 1628 } 1629 if (options.hpn_disabled) 1630 c = channel_new(ssh, "authentication agent connection", 1631 SSH_CHANNEL_OPEN, sock, sock, -1, 1632 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, 1633 "authentication agent connection", 1); 1634 else 1635 c = channel_new(ssh, "authentication agent connection", 1636 SSH_CHANNEL_OPEN, sock, sock, -1, 1637 options.hpn_buffer_size, options.hpn_buffer_size, 0, 1638 "authentication agent connection", 1); 1639 c->force_drain = 1; 1640 return c; 1641 } 1642 1643 char * 1644 client_request_tun_fwd(struct ssh *ssh, int tun_mode, 1645 int local_tun, int remote_tun, channel_open_fn *cb, void *cbctx) 1646 { 1647 Channel *c; 1648 int r, fd; 1649 char *ifname = NULL; 1650 1651 if (tun_mode == SSH_TUNMODE_NO) 1652 return 0; 1653 1654 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode); 1655 1656 /* Open local tunnel device */ 1657 if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) { 1658 error("Tunnel device open failed."); 1659 return NULL; 1660 } 1661 debug("Tunnel forwarding using interface %s", ifname); 1662 1663 if(options.hpn_disabled) 1664 c = channel_new(ssh, "tun", SSH_CHANNEL_OPENING, fd, fd, -1, 1665 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1); 1666 else 1667 c = channel_new(ssh, "tun", SSH_CHANNEL_OPENING, fd, fd, -1, 1668 options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1); 1669 c->datagram = 1; 1670 1671 if (cb != NULL) 1672 channel_register_open_confirm(ssh, c->self, cb, cbctx); 1673 1674 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 || 1675 (r = sshpkt_put_cstring(ssh, "tun@openssh.com")) != 0 || 1676 (r = sshpkt_put_u32(ssh, c->self)) != 0 || 1677 (r = sshpkt_put_u32(ssh, c->local_window_max)) != 0 || 1678 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 || 1679 (r = sshpkt_put_u32(ssh, tun_mode)) != 0 || 1680 (r = sshpkt_put_u32(ssh, remote_tun)) != 0 || 1681 (r = sshpkt_send(ssh)) != 0) 1682 sshpkt_fatal(ssh, r, "%s: send reply", __func__); 1683 1684 return ifname; 1685 } 1686 1687 /* XXXX move to generic input handler */ 1688 static int 1689 client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh) 1690 { 1691 Channel *c = NULL; 1692 char *ctype = NULL; 1693 int r; 1694 u_int rchan; 1695 size_t len; 1696 u_int rmaxpack, rwindow; 1697 1698 if ((r = sshpkt_get_cstring(ssh, &ctype, &len)) != 0 || 1699 (r = sshpkt_get_u32(ssh, &rchan)) != 0 || 1700 (r = sshpkt_get_u32(ssh, &rwindow)) != 0 || 1701 (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0) 1702 goto out; 1703 1704 debug("client_input_channel_open: ctype %s rchan %d win %d max %d", 1705 ctype, rchan, rwindow, rmaxpack); 1706 1707 if (strcmp(ctype, "forwarded-tcpip") == 0) { 1708 c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow, 1709 rmaxpack); 1710 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) { 1711 c = client_request_forwarded_streamlocal(ssh, ctype, rchan); 1712 } else if (strcmp(ctype, "x11") == 0) { 1713 c = client_request_x11(ssh, ctype, rchan); 1714 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) { 1715 c = client_request_agent(ssh, ctype, rchan); 1716 } 1717 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) { 1718 debug3("proxied to downstream: %s", ctype); 1719 } else if (c != NULL) { 1720 debug("confirm %s", ctype); 1721 c->remote_id = rchan; 1722 c->have_remote_id = 1; 1723 c->remote_window = rwindow; 1724 c->remote_maxpacket = rmaxpack; 1725 if (c->type != SSH_CHANNEL_CONNECTING) { 1726 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 || 1727 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 || 1728 (r = sshpkt_put_u32(ssh, c->self)) != 0 || 1729 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 || 1730 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 || 1731 (r = sshpkt_send(ssh)) != 0) 1732 sshpkt_fatal(ssh, r, "%s: send reply", __func__); 1733 } 1734 } else { 1735 debug("failure %s", ctype); 1736 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 || 1737 (r = sshpkt_put_u32(ssh, rchan)) != 0 || 1738 (r = sshpkt_put_u32(ssh, SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) != 0 || 1739 (r = sshpkt_put_cstring(ssh, "open failed")) != 0 || 1740 (r = sshpkt_put_cstring(ssh, "")) != 0 || 1741 (r = sshpkt_send(ssh)) != 0) 1742 sshpkt_fatal(ssh, r, "%s: send failure", __func__); 1743 } 1744 r = 0; 1745 out: 1746 free(ctype); 1747 return r; 1748 } 1749 1750 static int 1751 client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh) 1752 { 1753 Channel *c = NULL; 1754 char *rtype = NULL; 1755 u_char reply; 1756 u_int id, exitval; 1757 int r, success = 0; 1758 1759 if ((r = sshpkt_get_u32(ssh, &id)) != 0) 1760 return r; 1761 if (id <= INT_MAX) 1762 c = channel_lookup(ssh, id); 1763 if (channel_proxy_upstream(c, type, seq, ssh)) 1764 return 0; 1765 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 || 1766 (r = sshpkt_get_u8(ssh, &reply)) != 0) 1767 goto out; 1768 1769 debug("client_input_channel_req: channel %u rtype %s reply %d", 1770 id, rtype, reply); 1771 1772 if (c == NULL) { 1773 error("client_input_channel_req: channel %d: " 1774 "unknown channel", id); 1775 } else if (strcmp(rtype, "eow@openssh.com") == 0) { 1776 if ((r = sshpkt_get_end(ssh)) != 0) 1777 goto out; 1778 chan_rcvd_eow(ssh, c); 1779 } else if (strcmp(rtype, "exit-status") == 0) { 1780 if ((r = sshpkt_get_u32(ssh, &exitval)) != 0) 1781 goto out; 1782 if (c->ctl_chan != -1) { 1783 mux_exit_message(ssh, c, exitval); 1784 success = 1; 1785 } else if ((int)id == session_ident) { 1786 /* Record exit value of local session */ 1787 success = 1; 1788 exit_status = exitval; 1789 } else { 1790 /* Probably for a mux channel that has already closed */ 1791 debug("%s: no sink for exit-status on channel %d", 1792 __func__, id); 1793 } 1794 if ((r = sshpkt_get_end(ssh)) != 0) 1795 goto out; 1796 } 1797 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) { 1798 if (!c->have_remote_id) 1799 fatal("%s: channel %d: no remote_id", 1800 __func__, c->self); 1801 if ((r = sshpkt_start(ssh, success ? 1802 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 || 1803 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 || 1804 (r = sshpkt_send(ssh)) != 0) 1805 sshpkt_fatal(ssh, r, "%s: send failure", __func__); 1806 } 1807 r = 0; 1808 out: 1809 free(rtype); 1810 return r; 1811 } 1812 1813 struct hostkeys_update_ctx { 1814 /* The hostname and (optionally) IP address string for the server */ 1815 char *host_str, *ip_str; 1816 1817 /* 1818 * Keys received from the server and a flag for each indicating 1819 * whether they already exist in known_hosts. 1820 * keys_seen is filled in by hostkeys_find() and later (for new 1821 * keys) by client_global_hostkeys_private_confirm(). 1822 */ 1823 struct sshkey **keys; 1824 int *keys_seen; 1825 size_t nkeys, nnew; 1826 1827 /* 1828 * Keys that are in known_hosts, but were not present in the update 1829 * from the server (i.e. scheduled to be deleted). 1830 * Filled in by hostkeys_find(). 1831 */ 1832 struct sshkey **old_keys; 1833 size_t nold; 1834 }; 1835 1836 static void 1837 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx) 1838 { 1839 size_t i; 1840 1841 if (ctx == NULL) 1842 return; 1843 for (i = 0; i < ctx->nkeys; i++) 1844 sshkey_free(ctx->keys[i]); 1845 free(ctx->keys); 1846 free(ctx->keys_seen); 1847 for (i = 0; i < ctx->nold; i++) 1848 sshkey_free(ctx->old_keys[i]); 1849 free(ctx->old_keys); 1850 free(ctx->host_str); 1851 free(ctx->ip_str); 1852 free(ctx); 1853 } 1854 1855 static int 1856 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx) 1857 { 1858 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx; 1859 size_t i; 1860 struct sshkey **tmp; 1861 1862 if (l->status != HKF_STATUS_MATCHED || l->key == NULL) 1863 return 0; 1864 1865 /* Mark off keys we've already seen for this host */ 1866 for (i = 0; i < ctx->nkeys; i++) { 1867 if (sshkey_equal(l->key, ctx->keys[i])) { 1868 debug3("%s: found %s key at %s:%ld", __func__, 1869 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum); 1870 ctx->keys_seen[i] = 1; 1871 return 0; 1872 } 1873 } 1874 /* This line contained a key that not offered by the server */ 1875 debug3("%s: deprecated %s key at %s:%ld", __func__, 1876 sshkey_ssh_name(l->key), l->path, l->linenum); 1877 if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1, 1878 sizeof(*ctx->old_keys))) == NULL) 1879 fatal("%s: recallocarray failed nold = %zu", 1880 __func__, ctx->nold); 1881 ctx->old_keys = tmp; 1882 ctx->old_keys[ctx->nold++] = l->key; 1883 l->key = NULL; 1884 1885 return 0; 1886 } 1887 1888 static void 1889 hostkey_change_preamble(LogLevel loglevel) 1890 { 1891 do_log2(loglevel, "The server has updated its host keys."); 1892 do_log2(loglevel, "These changes were verified by the server's " 1893 "existing trusted key."); 1894 } 1895 1896 static void 1897 update_known_hosts(struct hostkeys_update_ctx *ctx) 1898 { 1899 int r, was_raw = 0, first = 1; 1900 int asking = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK; 1901 LogLevel loglevel = asking ? SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE; 1902 char *fp, *response; 1903 size_t i; 1904 struct stat sb; 1905 1906 for (i = 0; i < ctx->nkeys; i++) { 1907 if (ctx->keys_seen[i] != 2) 1908 continue; 1909 if ((fp = sshkey_fingerprint(ctx->keys[i], 1910 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) 1911 fatal("%s: sshkey_fingerprint failed", __func__); 1912 if (first && asking) 1913 hostkey_change_preamble(loglevel); 1914 do_log2(loglevel, "Learned new hostkey: %s %s", 1915 sshkey_type(ctx->keys[i]), fp); 1916 first = 0; 1917 free(fp); 1918 } 1919 for (i = 0; i < ctx->nold; i++) { 1920 if ((fp = sshkey_fingerprint(ctx->old_keys[i], 1921 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) 1922 fatal("%s: sshkey_fingerprint failed", __func__); 1923 if (first && asking) 1924 hostkey_change_preamble(loglevel); 1925 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s", 1926 sshkey_type(ctx->old_keys[i]), fp); 1927 first = 0; 1928 free(fp); 1929 } 1930 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) { 1931 if (get_saved_tio() != NULL) { 1932 leave_raw_mode(1); 1933 was_raw = 1; 1934 } 1935 response = NULL; 1936 for (i = 0; !quit_pending && i < 3; i++) { 1937 free(response); 1938 response = read_passphrase("Accept updated hostkeys? " 1939 "(yes/no): ", RP_ECHO); 1940 if (strcasecmp(response, "yes") == 0) 1941 break; 1942 else if (quit_pending || response == NULL || 1943 strcasecmp(response, "no") == 0) { 1944 options.update_hostkeys = 0; 1945 break; 1946 } else { 1947 do_log2(loglevel, "Please enter " 1948 "\"yes\" or \"no\""); 1949 } 1950 } 1951 if (quit_pending || i >= 3 || response == NULL) 1952 options.update_hostkeys = 0; 1953 free(response); 1954 if (was_raw) 1955 enter_raw_mode(1); 1956 } 1957 if (options.update_hostkeys == 0) 1958 return; 1959 /* 1960 * Now that all the keys are verified, we can go ahead and replace 1961 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't 1962 * cancel the operation). 1963 */ 1964 for (i = 0; i < options.num_user_hostfiles; i++) { 1965 /* 1966 * NB. keys are only added to hostfiles[0], for the rest we 1967 * just delete the hostname entries. 1968 */ 1969 if (stat(options.user_hostfiles[i], &sb) != 0) { 1970 if (errno == ENOENT) { 1971 debug("%s: known hosts file %s does not exist", 1972 __func__, strerror(errno)); 1973 } else { 1974 error("%s: known hosts file %s inaccessible", 1975 __func__, strerror(errno)); 1976 } 1977 continue; 1978 } 1979 if ((r = hostfile_replace_entries(options.user_hostfiles[i], 1980 ctx->host_str, ctx->ip_str, 1981 i == 0 ? ctx->keys : NULL, i == 0 ? ctx->nkeys : 0, 1982 options.hash_known_hosts, 0, 1983 options.fingerprint_hash)) != 0) { 1984 error("%s: hostfile_replace_entries failed for %s: %s", 1985 __func__, options.user_hostfiles[i], ssh_err(r)); 1986 } 1987 } 1988 } 1989 1990 static void 1991 client_global_hostkeys_private_confirm(struct ssh *ssh, int type, 1992 u_int32_t seq, void *_ctx) 1993 { 1994 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx; 1995 size_t i, ndone; 1996 struct sshbuf *signdata; 1997 int r, kexsigtype, use_kexsigtype; 1998 const u_char *sig; 1999 size_t siglen; 2000 2001 if (ctx->nnew == 0) 2002 fatal("%s: ctx->nnew == 0", __func__); /* sanity */ 2003 if (type != SSH2_MSG_REQUEST_SUCCESS) { 2004 error("Server failed to confirm ownership of " 2005 "private host keys"); 2006 hostkeys_update_ctx_free(ctx); 2007 return; 2008 } 2009 kexsigtype = sshkey_type_plain( 2010 sshkey_type_from_name(ssh->kex->hostkey_alg)); 2011 2012 if ((signdata = sshbuf_new()) == NULL) 2013 fatal("%s: sshbuf_new failed", __func__); 2014 /* Don't want to accidentally accept an unbound signature */ 2015 if (ssh->kex->session_id_len == 0) 2016 fatal("%s: ssh->kex->session_id_len == 0", __func__); 2017 /* 2018 * Expect a signature for each of the ctx->nnew private keys we 2019 * haven't seen before. They will be in the same order as the 2020 * ctx->keys where the corresponding ctx->keys_seen[i] == 0. 2021 */ 2022 for (ndone = i = 0; i < ctx->nkeys; i++) { 2023 if (ctx->keys_seen[i]) 2024 continue; 2025 /* Prepare data to be signed: session ID, unique string, key */ 2026 sshbuf_reset(signdata); 2027 if ( (r = sshbuf_put_cstring(signdata, 2028 "hostkeys-prove-00@openssh.com")) != 0 || 2029 (r = sshbuf_put_string(signdata, ssh->kex->session_id, 2030 ssh->kex->session_id_len)) != 0 || 2031 (r = sshkey_puts(ctx->keys[i], signdata)) != 0) 2032 fatal("%s: failed to prepare signature: %s", 2033 __func__, ssh_err(r)); 2034 /* Extract and verify signature */ 2035 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) { 2036 error("%s: couldn't parse message: %s", 2037 __func__, ssh_err(r)); 2038 goto out; 2039 } 2040 /* 2041 * For RSA keys, prefer to use the signature type negotiated 2042 * during KEX to the default (SHA1). 2043 */ 2044 use_kexsigtype = kexsigtype == KEY_RSA && 2045 sshkey_type_plain(ctx->keys[i]->type) == KEY_RSA; 2046 if ((r = sshkey_verify(ctx->keys[i], sig, siglen, 2047 sshbuf_ptr(signdata), sshbuf_len(signdata), 2048 use_kexsigtype ? ssh->kex->hostkey_alg : NULL, 0, 2049 NULL)) != 0) { 2050 error("%s: server gave bad signature for %s key %zu", 2051 __func__, sshkey_type(ctx->keys[i]), i); 2052 goto out; 2053 } 2054 /* Key is good. Mark it as 'seen' */ 2055 ctx->keys_seen[i] = 2; 2056 ndone++; 2057 } 2058 if (ndone != ctx->nnew) 2059 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__, 2060 ndone, ctx->nnew); /* Shouldn't happen */ 2061 if ((r = sshpkt_get_end(ssh)) != 0) { 2062 error("%s: protocol error", __func__); 2063 goto out; 2064 } 2065 2066 /* Make the edits to known_hosts */ 2067 update_known_hosts(ctx); 2068 out: 2069 hostkeys_update_ctx_free(ctx); 2070 } 2071 2072 /* 2073 * Returns non-zero if the key is accepted by HostkeyAlgorithms. 2074 * Made slightly less trivial by the multiple RSA signature algorithm names. 2075 */ 2076 static int 2077 key_accepted_by_hostkeyalgs(const struct sshkey *key) 2078 { 2079 const char *ktype = sshkey_ssh_name(key); 2080 const char *hostkeyalgs = options.hostkeyalgorithms; 2081 2082 if (key == NULL || key->type == KEY_UNSPEC) 2083 return 0; 2084 if (key->type == KEY_RSA && 2085 (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 || 2086 match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1)) 2087 return 1; 2088 return match_pattern_list(ktype, hostkeyalgs, 0) == 1; 2089 } 2090 2091 /* 2092 * Handle hostkeys-00@openssh.com global request to inform the client of all 2093 * the server's hostkeys. The keys are checked against the user's 2094 * HostkeyAlgorithms preference before they are accepted. 2095 */ 2096 static int 2097 client_input_hostkeys(struct ssh *ssh) 2098 { 2099 const u_char *blob = NULL; 2100 size_t i, len = 0; 2101 struct sshbuf *buf = NULL; 2102 struct sshkey *key = NULL, **tmp; 2103 int r; 2104 char *fp; 2105 static int hostkeys_seen = 0; /* XXX use struct ssh */ 2106 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */ 2107 struct hostkeys_update_ctx *ctx = NULL; 2108 2109 if (hostkeys_seen) 2110 fatal("%s: server already sent hostkeys", __func__); 2111 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK && 2112 options.batch_mode) 2113 return 1; /* won't ask in batchmode, so don't even try */ 2114 if (!options.update_hostkeys || options.num_user_hostfiles <= 0) 2115 return 1; 2116 2117 ctx = xcalloc(1, sizeof(*ctx)); 2118 while (ssh_packet_remaining(ssh) > 0) { 2119 sshkey_free(key); 2120 key = NULL; 2121 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) { 2122 error("%s: couldn't parse message: %s", 2123 __func__, ssh_err(r)); 2124 goto out; 2125 } 2126 if ((r = sshkey_from_blob(blob, len, &key)) != 0) { 2127 do_log2(r == SSH_ERR_KEY_TYPE_UNKNOWN ? 2128 SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_ERROR, 2129 "%s: parse key: %s", __func__, ssh_err(r)); 2130 continue; 2131 } 2132 fp = sshkey_fingerprint(key, options.fingerprint_hash, 2133 SSH_FP_DEFAULT); 2134 debug3("%s: received %s key %s", __func__, 2135 sshkey_type(key), fp); 2136 free(fp); 2137 2138 if (!key_accepted_by_hostkeyalgs(key)) { 2139 debug3("%s: %s key not permitted by HostkeyAlgorithms", 2140 __func__, sshkey_ssh_name(key)); 2141 continue; 2142 } 2143 /* Skip certs */ 2144 if (sshkey_is_cert(key)) { 2145 debug3("%s: %s key is a certificate; skipping", 2146 __func__, sshkey_ssh_name(key)); 2147 continue; 2148 } 2149 /* Ensure keys are unique */ 2150 for (i = 0; i < ctx->nkeys; i++) { 2151 if (sshkey_equal(key, ctx->keys[i])) { 2152 error("%s: received duplicated %s host key", 2153 __func__, sshkey_ssh_name(key)); 2154 goto out; 2155 } 2156 } 2157 /* Key is good, record it */ 2158 if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1, 2159 sizeof(*ctx->keys))) == NULL) 2160 fatal("%s: recallocarray failed nkeys = %zu", 2161 __func__, ctx->nkeys); 2162 ctx->keys = tmp; 2163 ctx->keys[ctx->nkeys++] = key; 2164 key = NULL; 2165 } 2166 2167 if (ctx->nkeys == 0) { 2168 debug("%s: server sent no hostkeys", __func__); 2169 goto out; 2170 } 2171 2172 if ((ctx->keys_seen = calloc(ctx->nkeys, 2173 sizeof(*ctx->keys_seen))) == NULL) 2174 fatal("%s: calloc failed", __func__); 2175 2176 get_hostfile_hostname_ipaddr(host, 2177 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL, 2178 options.port, &ctx->host_str, 2179 options.check_host_ip ? &ctx->ip_str : NULL); 2180 2181 /* Find which keys we already know about. */ 2182 for (i = 0; i < options.num_user_hostfiles; i++) { 2183 debug("%s: searching %s for %s / %s", __func__, 2184 options.user_hostfiles[i], ctx->host_str, 2185 ctx->ip_str ? ctx->ip_str : "(none)"); 2186 if ((r = hostkeys_foreach(options.user_hostfiles[i], 2187 hostkeys_find, ctx, ctx->host_str, ctx->ip_str, 2188 HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) { 2189 if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) { 2190 debug("%s: hostkeys file %s does not exist", 2191 __func__, options.user_hostfiles[i]); 2192 continue; 2193 } 2194 error("%s: hostkeys_foreach failed for %s: %s", 2195 __func__, options.user_hostfiles[i], ssh_err(r)); 2196 goto out; 2197 } 2198 } 2199 2200 /* Figure out if we have any new keys to add */ 2201 ctx->nnew = 0; 2202 for (i = 0; i < ctx->nkeys; i++) { 2203 if (!ctx->keys_seen[i]) 2204 ctx->nnew++; 2205 } 2206 2207 debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove", 2208 __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold); 2209 2210 if (ctx->nnew == 0 && ctx->nold != 0) { 2211 /* We have some keys to remove. Just do it. */ 2212 update_known_hosts(ctx); 2213 } else if (ctx->nnew != 0) { 2214 /* 2215 * We have received hitherto-unseen keys from the server. 2216 * Ask the server to confirm ownership of the private halves. 2217 */ 2218 debug3("%s: asking server to prove ownership for %zu keys", 2219 __func__, ctx->nnew); 2220 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 2221 (r = sshpkt_put_cstring(ssh, 2222 "hostkeys-prove-00@openssh.com")) != 0 || 2223 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */ 2224 fatal("%s: cannot prepare packet: %s", 2225 __func__, ssh_err(r)); 2226 if ((buf = sshbuf_new()) == NULL) 2227 fatal("%s: sshbuf_new", __func__); 2228 for (i = 0; i < ctx->nkeys; i++) { 2229 if (ctx->keys_seen[i]) 2230 continue; 2231 sshbuf_reset(buf); 2232 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0) 2233 fatal("%s: sshkey_putb: %s", 2234 __func__, ssh_err(r)); 2235 if ((r = sshpkt_put_stringb(ssh, buf)) != 0) 2236 fatal("%s: sshpkt_put_string: %s", 2237 __func__, ssh_err(r)); 2238 } 2239 if ((r = sshpkt_send(ssh)) != 0) 2240 fatal("%s: sshpkt_send: %s", __func__, ssh_err(r)); 2241 client_register_global_confirm( 2242 client_global_hostkeys_private_confirm, ctx); 2243 ctx = NULL; /* will be freed in callback */ 2244 } 2245 2246 /* Success */ 2247 out: 2248 hostkeys_update_ctx_free(ctx); 2249 sshkey_free(key); 2250 sshbuf_free(buf); 2251 /* 2252 * NB. Return success for all cases. The server doesn't need to know 2253 * what the client does with its hosts file. 2254 */ 2255 return 1; 2256 } 2257 2258 static int 2259 client_input_global_request(int type, u_int32_t seq, struct ssh *ssh) 2260 { 2261 char *rtype; 2262 u_char want_reply; 2263 int r, success = 0; 2264 2265 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 || 2266 (r = sshpkt_get_u8(ssh, &want_reply)) != 0) 2267 goto out; 2268 debug("client_input_global_request: rtype %s want_reply %d", 2269 rtype, want_reply); 2270 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0) 2271 success = client_input_hostkeys(ssh); 2272 if (want_reply) { 2273 if ((r = sshpkt_start(ssh, success ? SSH2_MSG_REQUEST_SUCCESS : 2274 SSH2_MSG_REQUEST_FAILURE)) != 0 || 2275 (r = sshpkt_send(ssh)) != 0 || 2276 (r = ssh_packet_write_wait(ssh)) != 0) 2277 goto out; 2278 } 2279 r = 0; 2280 out: 2281 free(rtype); 2282 return r; 2283 } 2284 2285 void 2286 client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem, 2287 const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd, 2288 char **env) 2289 { 2290 int i, j, matched, len, r; 2291 char *name, *val; 2292 Channel *c = NULL; 2293 2294 debug2("%s: id %d", __func__, id); 2295 2296 if ((c = channel_lookup(ssh, id)) == NULL) 2297 fatal("%s: channel %d: unknown channel", __func__, id); 2298 2299 ssh_packet_set_interactive(ssh, want_tty, 2300 options.ip_qos_interactive, options.ip_qos_bulk); 2301 2302 if (want_tty) { 2303 struct winsize ws; 2304 2305 /* Store window size in the packet. */ 2306 if (ioctl(in_fd, TIOCGWINSZ, &ws) == -1) 2307 memset(&ws, 0, sizeof(ws)); 2308 2309 channel_request_start(ssh, id, "pty-req", 1); 2310 client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY); 2311 if ((r = sshpkt_put_cstring(ssh, term != NULL ? term : "")) 2312 != 0 || 2313 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 || 2314 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 || 2315 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 || 2316 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0) 2317 fatal("%s: build packet: %s", __func__, ssh_err(r)); 2318 if (tiop == NULL) 2319 tiop = get_saved_tio(); 2320 ssh_tty_make_modes(ssh, -1, tiop); 2321 if ((r = sshpkt_send(ssh)) != 0) 2322 fatal("%s: send packet: %s", __func__, ssh_err(r)); 2323 /* XXX wait for reply */ 2324 c->client_tty = 1; 2325 } 2326 2327 /* Transfer any environment variables from client to server */ 2328 if (options.num_send_env != 0 && env != NULL) { 2329 debug("Sending environment."); 2330 for (i = 0; env[i] != NULL; i++) { 2331 /* Split */ 2332 name = xstrdup(env[i]); 2333 if ((val = strchr(name, '=')) == NULL) { 2334 free(name); 2335 continue; 2336 } 2337 *val++ = '\0'; 2338 2339 matched = 0; 2340 for (j = 0; j < options.num_send_env; j++) { 2341 if (match_pattern(name, options.send_env[j])) { 2342 matched = 1; 2343 break; 2344 } 2345 } 2346 if (!matched) { 2347 debug3("Ignored env %s", name); 2348 free(name); 2349 continue; 2350 } 2351 2352 debug("Sending env %s = %s", name, val); 2353 channel_request_start(ssh, id, "env", 0); 2354 if ((r = sshpkt_put_cstring(ssh, name)) != 0 || 2355 (r = sshpkt_put_cstring(ssh, val)) != 0 || 2356 (r = sshpkt_send(ssh)) != 0) { 2357 fatal("%s: send packet: %s", 2358 __func__, ssh_err(r)); 2359 } 2360 free(name); 2361 } 2362 } 2363 for (i = 0; i < options.num_setenv; i++) { 2364 /* Split */ 2365 name = xstrdup(options.setenv[i]); 2366 if ((val = strchr(name, '=')) == NULL) { 2367 free(name); 2368 continue; 2369 } 2370 *val++ = '\0'; 2371 2372 debug("Setting env %s = %s", name, val); 2373 channel_request_start(ssh, id, "env", 0); 2374 if ((r = sshpkt_put_cstring(ssh, name)) != 0 || 2375 (r = sshpkt_put_cstring(ssh, val)) != 0 || 2376 (r = sshpkt_send(ssh)) != 0) 2377 fatal("%s: send packet: %s", __func__, ssh_err(r)); 2378 free(name); 2379 } 2380 2381 len = sshbuf_len(cmd); 2382 if (len > 0) { 2383 if (len > 900) 2384 len = 900; 2385 if (want_subsystem) { 2386 debug("Sending subsystem: %.*s", 2387 len, (const u_char*)sshbuf_ptr(cmd)); 2388 channel_request_start(ssh, id, "subsystem", 1); 2389 client_expect_confirm(ssh, id, "subsystem", 2390 CONFIRM_CLOSE); 2391 } else { 2392 debug("Sending command: %.*s", 2393 len, (const u_char*)sshbuf_ptr(cmd)); 2394 channel_request_start(ssh, id, "exec", 1); 2395 client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE); 2396 } 2397 if ((r = sshpkt_put_stringb(ssh, cmd)) != 0 || 2398 (r = sshpkt_send(ssh)) != 0) 2399 fatal("%s: send command: %s", __func__, ssh_err(r)); 2400 } else { 2401 channel_request_start(ssh, id, "shell", 1); 2402 client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE); 2403 if ((r = sshpkt_send(ssh)) != 0) { 2404 fatal("%s: send shell request: %s", 2405 __func__, ssh_err(r)); 2406 } 2407 } 2408 } 2409 2410 static void 2411 client_init_dispatch(struct ssh *ssh) 2412 { 2413 ssh_dispatch_init(ssh, &dispatch_protocol_error); 2414 2415 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose); 2416 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data); 2417 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof); 2418 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data); 2419 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open); 2420 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation); 2421 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure); 2422 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req); 2423 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust); 2424 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm); 2425 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm); 2426 ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request); 2427 2428 /* rekeying */ 2429 ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit); 2430 2431 /* global request reply messages */ 2432 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply); 2433 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply); 2434 } 2435 2436 void 2437 client_stop_mux(void) 2438 { 2439 if (options.control_path != NULL && muxserver_sock != -1) 2440 unlink(options.control_path); 2441 /* 2442 * If we are in persist mode, or don't have a shell, signal that we 2443 * should close when all active channels are closed. 2444 */ 2445 if (options.control_persist || no_shell_flag) { 2446 session_closed = 1; 2447 setproctitle("[stopped mux]"); 2448 } 2449 } 2450 2451 /* client specific fatal cleanup */ 2452 void 2453 cleanup_exit(int i) 2454 { 2455 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 2456 if (options.control_path != NULL && muxserver_sock != -1) 2457 unlink(options.control_path); 2458 ssh_kill_proxy_command(); 2459 _exit(i); 2460 } 2461