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