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