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