1 /* $NetBSD: serverloop.c,v 1.19 2018/04/06 18:59:00 christos Exp $ */ 2 /* $OpenBSD: serverloop.c,v 1.205 2018/03/03 03:15:51 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 * Server main loop for handling the interactive session. 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 * SSH2 support by Markus Friedl. 16 * Copyright (c) 2000, 2001 Markus Friedl. 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 #include "includes.h" 40 __RCSID("$NetBSD: serverloop.c,v 1.19 2018/04/06 18:59:00 christos Exp $"); 41 42 #include <sys/param.h> /* MIN MAX */ 43 #include <sys/types.h> 44 #include <sys/wait.h> 45 #include <sys/socket.h> 46 #include <sys/time.h> 47 #include <sys/queue.h> 48 49 #include <netinet/in.h> 50 51 #include <errno.h> 52 #include <fcntl.h> 53 #include <pwd.h> 54 #include <signal.h> 55 #include <string.h> 56 #include <termios.h> 57 #include <unistd.h> 58 #include <stdarg.h> 59 60 #include "xmalloc.h" 61 #include "packet.h" 62 #include "buffer.h" 63 #include "log.h" 64 #include "misc.h" 65 #include "servconf.h" 66 #include "canohost.h" 67 #include "sshpty.h" 68 #include "channels.h" 69 #include "compat.h" 70 #include "ssh2.h" 71 #include "key.h" 72 #include "cipher.h" 73 #include "kex.h" 74 #include "hostfile.h" 75 #include "auth.h" 76 #include "session.h" 77 #include "dispatch.h" 78 #include "auth-options.h" 79 #include "serverloop.h" 80 #include "ssherr.h" 81 82 static u_long stdin_bytes = 0; /* Number of bytes written to stdin. */ 83 static u_long fdout_bytes = 0; /* Number of stdout bytes read from program. */ 84 85 extern ServerOptions options; 86 87 /* XXX */ 88 extern Authctxt *the_authctxt; 89 extern struct sshauthopt *auth_opts; 90 extern int use_privsep; 91 92 static int no_more_sessions = 0; /* Disallow further sessions. */ 93 94 /* 95 * This SIGCHLD kludge is used to detect when the child exits. The server 96 * will exit after that, as soon as forwarded connections have terminated. 97 */ 98 99 static volatile sig_atomic_t child_terminated = 0; /* The child has terminated. */ 100 101 /* Cleanup on signals (!use_privsep case only) */ 102 static volatile sig_atomic_t received_sigterm = 0; 103 104 /* prototypes */ 105 static void server_init_dispatch(void); 106 107 /* requested tunnel forwarding interface(s), shared with session.c */ 108 char *tun_fwd_ifnames = NULL; 109 110 /* 111 * Returns current time in seconds from Jan 1, 1970 with the maximum 112 * available resolution. 113 */ 114 115 static double 116 get_current_time(void) 117 { 118 struct timeval tv; 119 gettimeofday(&tv, NULL); 120 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0; 121 } 122 123 /* 124 * we write to this pipe if a SIGCHLD is caught in order to avoid 125 * the race between select() and child_terminated 126 */ 127 static int notify_pipe[2]; 128 static void 129 notify_setup(void) 130 { 131 if (pipe(notify_pipe) < 0) { 132 error("pipe(notify_pipe) failed %s", strerror(errno)); 133 } else if ((fcntl(notify_pipe[0], F_SETFD, FD_CLOEXEC) == -1) || 134 (fcntl(notify_pipe[1], F_SETFD, FD_CLOEXEC) == -1)) { 135 error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno)); 136 close(notify_pipe[0]); 137 close(notify_pipe[1]); 138 } else { 139 set_nonblock(notify_pipe[0]); 140 set_nonblock(notify_pipe[1]); 141 return; 142 } 143 notify_pipe[0] = -1; /* read end */ 144 notify_pipe[1] = -1; /* write end */ 145 } 146 static void 147 notify_parent(void) 148 { 149 if (notify_pipe[1] != -1) 150 (void)write(notify_pipe[1], "", 1); 151 } 152 static void 153 notify_prepare(fd_set *readset) 154 { 155 if (notify_pipe[0] != -1) 156 FD_SET(notify_pipe[0], readset); 157 } 158 static void 159 notify_done(fd_set *readset) 160 { 161 char c; 162 163 if (notify_pipe[0] != -1 && FD_ISSET(notify_pipe[0], readset)) 164 while (read(notify_pipe[0], &c, 1) != -1) 165 debug2("notify_done: reading"); 166 } 167 168 /*ARGSUSED*/ 169 static void 170 sigchld_handler(int sig) 171 { 172 int save_errno = errno; 173 child_terminated = 1; 174 notify_parent(); 175 errno = save_errno; 176 } 177 178 /*ARGSUSED*/ 179 static void 180 sigterm_handler(int sig) 181 { 182 received_sigterm = sig; 183 } 184 185 static void 186 client_alive_check(struct ssh *ssh) 187 { 188 int channel_id; 189 char remote_id[512]; 190 191 /* timeout, check to see how many we have had */ 192 if (packet_inc_alive_timeouts() > options.client_alive_count_max) { 193 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id)); 194 logit("Timeout, client not responding from %s", remote_id); 195 cleanup_exit(255); 196 } 197 198 /* 199 * send a bogus global/channel request with "wantreply", 200 * we should get back a failure 201 */ 202 if ((channel_id = channel_find_open(ssh)) == -1) { 203 packet_start(SSH2_MSG_GLOBAL_REQUEST); 204 packet_put_cstring("keepalive@openssh.com"); 205 packet_put_char(1); /* boolean: want reply */ 206 } else { 207 channel_request_start(ssh, channel_id, 208 "keepalive@openssh.com", 1); 209 } 210 packet_send(); 211 } 212 213 /* 214 * Sleep in select() until we can do something. This will initialize the 215 * select masks. Upon return, the masks will indicate which descriptors 216 * have data or can accept data. Optionally, a maximum time can be specified 217 * for the duration of the wait (0 = infinite). 218 */ 219 static void 220 wait_until_can_do_something(struct ssh *ssh, 221 int connection_in, int connection_out, 222 fd_set **readsetp, fd_set **writesetp, int *maxfdp, 223 u_int *nallocp, u_int64_t max_time_ms) 224 { 225 struct timeval tv, *tvp; 226 int ret; 227 time_t minwait_secs = 0; 228 int client_alive_scheduled = 0; 229 static time_t last_client_time; 230 231 /* Allocate and update select() masks for channel descriptors. */ 232 channel_prepare_select(ssh, readsetp, writesetp, maxfdp, 233 nallocp, &minwait_secs); 234 235 /* XXX need proper deadline system for rekey/client alive */ 236 if (minwait_secs != 0) 237 max_time_ms = MINIMUM(max_time_ms, (u_int)minwait_secs * 1000); 238 239 /* 240 * if using client_alive, set the max timeout accordingly, 241 * and indicate that this particular timeout was for client 242 * alive by setting the client_alive_scheduled flag. 243 * 244 * this could be randomized somewhat to make traffic 245 * analysis more difficult, but we're not doing it yet. 246 */ 247 if (options.client_alive_interval) { 248 uint64_t keepalive_ms = 249 (uint64_t)options.client_alive_interval * 1000; 250 251 client_alive_scheduled = 1; 252 if (max_time_ms == 0 || max_time_ms > keepalive_ms) 253 max_time_ms = keepalive_ms; 254 } 255 256 #if 0 257 /* wrong: bad condition XXX */ 258 if (channel_not_very_much_buffered_data()) 259 #endif 260 FD_SET(connection_in, *readsetp); 261 notify_prepare(*readsetp); 262 263 /* 264 * If we have buffered packet data going to the client, mark that 265 * descriptor. 266 */ 267 if (packet_have_data_to_write()) 268 FD_SET(connection_out, *writesetp); 269 270 /* 271 * If child has terminated and there is enough buffer space to read 272 * from it, then read as much as is available and exit. 273 */ 274 if (child_terminated && packet_not_very_much_data_to_write()) 275 if (max_time_ms == 0 || client_alive_scheduled) 276 max_time_ms = 100; 277 278 if (max_time_ms == 0) 279 tvp = NULL; 280 else { 281 tv.tv_sec = max_time_ms / 1000; 282 tv.tv_usec = 1000 * (max_time_ms % 1000); 283 tvp = &tv; 284 } 285 286 /* Wait for something to happen, or the timeout to expire. */ 287 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp); 288 289 if (ret == -1) { 290 memset(*readsetp, 0, *nallocp); 291 memset(*writesetp, 0, *nallocp); 292 if (errno != EINTR) 293 error("select: %.100s", strerror(errno)); 294 } else if (client_alive_scheduled) { 295 time_t now = monotime(); 296 297 if (ret == 0) { /* timeout */ 298 client_alive_check(ssh); 299 } else if (FD_ISSET(connection_in, *readsetp)) { 300 last_client_time = now; 301 } else if (last_client_time != 0 && last_client_time + 302 options.client_alive_interval <= now) { 303 client_alive_check(ssh); 304 last_client_time = now; 305 } 306 } 307 308 notify_done(*readsetp); 309 } 310 311 /* 312 * Processes input from the client and the program. Input data is stored 313 * in buffers and processed later. 314 */ 315 static int 316 process_input(struct ssh *ssh, fd_set *readset, int connection_in) 317 { 318 int len; 319 char buf[16384]; 320 321 /* Read and buffer any input data from the client. */ 322 if (FD_ISSET(connection_in, readset)) { 323 len = read(connection_in, buf, sizeof(buf)); 324 if (len == 0) { 325 verbose("Connection closed by %.100s port %d", 326 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 327 return -1; 328 } else if (len < 0) { 329 if (errno != EINTR && errno != EAGAIN) { 330 verbose("Read error from remote host " 331 "%.100s port %d: %.100s", 332 ssh_remote_ipaddr(ssh), 333 ssh_remote_port(ssh), strerror(errno)); 334 cleanup_exit(255); 335 } 336 } else { 337 /* Buffer any received data. */ 338 packet_process_incoming(buf, len); 339 fdout_bytes += len; 340 } 341 } 342 return 0; 343 } 344 345 /* 346 * Sends data from internal buffers to client program stdin. 347 */ 348 static void 349 process_output(fd_set *writeset, int connection_out) 350 { 351 /* Send any buffered packet data to the client. */ 352 if (FD_ISSET(connection_out, writeset)) 353 stdin_bytes += packet_write_poll(); 354 } 355 356 static void 357 process_buffered_input_packets(struct ssh *ssh) 358 { 359 ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, NULL); 360 } 361 362 static void 363 collect_children(struct ssh *ssh) 364 { 365 pid_t pid; 366 sigset_t oset, nset; 367 int status; 368 369 /* block SIGCHLD while we check for dead children */ 370 sigemptyset(&nset); 371 sigaddset(&nset, SIGCHLD); 372 sigprocmask(SIG_BLOCK, &nset, &oset); 373 if (child_terminated) { 374 debug("Received SIGCHLD."); 375 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 376 (pid < 0 && errno == EINTR)) 377 if (pid > 0) 378 session_close_by_pid(ssh, pid, status); 379 child_terminated = 0; 380 } 381 sigprocmask(SIG_SETMASK, &oset, NULL); 382 } 383 384 void 385 server_loop2(struct ssh *ssh, Authctxt *authctxt) 386 { 387 fd_set *readset = NULL, *writeset = NULL; 388 int max_fd; 389 u_int nalloc = 0, connection_in, connection_out; 390 u_int64_t rekey_timeout_ms = 0; 391 double start_time, total_time; 392 393 debug("Entering interactive session for SSH2."); 394 start_time = get_current_time(); 395 396 signal(SIGCHLD, sigchld_handler); 397 child_terminated = 0; 398 connection_in = packet_get_connection_in(); 399 connection_out = packet_get_connection_out(); 400 401 if (!use_privsep) { 402 signal(SIGTERM, sigterm_handler); 403 signal(SIGINT, sigterm_handler); 404 signal(SIGQUIT, sigterm_handler); 405 } 406 407 notify_setup(); 408 409 max_fd = MAXIMUM(connection_in, connection_out); 410 max_fd = MAXIMUM(max_fd, notify_pipe[0]); 411 412 server_init_dispatch(); 413 414 for (;;) { 415 process_buffered_input_packets(ssh); 416 417 if (!ssh_packet_is_rekeying(ssh) && 418 packet_not_very_much_data_to_write()) 419 channel_output_poll(ssh); 420 if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) 421 rekey_timeout_ms = packet_get_rekey_timeout() * 1000; 422 else 423 rekey_timeout_ms = 0; 424 425 wait_until_can_do_something(ssh, connection_in, connection_out, 426 &readset, &writeset, &max_fd, &nalloc, rekey_timeout_ms); 427 428 if (received_sigterm) { 429 logit("Exiting on signal %d", (int)received_sigterm); 430 /* Clean up sessions, utmp, etc. */ 431 cleanup_exit(255); 432 } 433 434 collect_children(ssh); 435 if (!ssh_packet_is_rekeying(ssh)) 436 channel_after_select(ssh, readset, writeset); 437 if (process_input(ssh, readset, connection_in) < 0) 438 break; 439 process_output(writeset, connection_out); 440 } 441 collect_children(ssh); 442 443 free(readset); 444 free(writeset); 445 446 /* free all channels, no more reads and writes */ 447 channel_free_all(ssh); 448 449 /* free remaining sessions, e.g. remove wtmp entries */ 450 session_destroy_all(ssh, NULL); 451 total_time = get_current_time() - start_time; 452 logit("SSH: Server;LType: Throughput;Remote: %s-%d;IN: %lu;OUT: %lu;Duration: %.1f;tPut_in: %.1f;tPut_out: %.1f", 453 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), 454 stdin_bytes, fdout_bytes, total_time, stdin_bytes / total_time, 455 fdout_bytes / total_time); 456 } 457 458 static int 459 server_input_keep_alive(int type, u_int32_t seq, struct ssh *ssh) 460 { 461 debug("Got %d/%u for keepalive", type, seq); 462 /* 463 * reset timeout, since we got a sane answer from the client. 464 * even if this was generated by something other than 465 * the bogus CHANNEL_REQUEST we send for keepalives. 466 */ 467 packet_set_alive_timeouts(0); 468 return 0; 469 } 470 471 static Channel * 472 server_request_direct_tcpip(struct ssh *ssh, int *reason, const char **errmsg) 473 { 474 Channel *c = NULL; 475 char *target, *originator; 476 u_short target_port, originator_port; 477 478 target = packet_get_string(NULL); 479 target_port = packet_get_int(); 480 originator = packet_get_string(NULL); 481 originator_port = packet_get_int(); 482 packet_check_eom(); 483 484 debug("%s: originator %s port %d, target %s port %d", __func__, 485 originator, originator_port, target, target_port); 486 487 /* XXX fine grained permissions */ 488 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 && 489 auth_opts->permit_port_forwarding_flag && 490 !options.disable_forwarding) { 491 c = channel_connect_to_port(ssh, target, target_port, 492 "direct-tcpip", "direct-tcpip", reason, errmsg); 493 } else { 494 logit("refused local port forward: " 495 "originator %s port %d, target %s port %d", 496 originator, originator_port, target, target_port); 497 if (reason != NULL) 498 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED; 499 } 500 501 free(originator); 502 free(target); 503 504 return c; 505 } 506 507 static Channel * 508 server_request_direct_streamlocal(struct ssh *ssh) 509 { 510 Channel *c = NULL; 511 char *target, *originator; 512 u_short originator_port; 513 struct passwd *pw = the_authctxt->pw; 514 515 if (pw == NULL || !the_authctxt->valid) 516 fatal("%s: no/invalid user", __func__); 517 518 target = packet_get_string(NULL); 519 originator = packet_get_string(NULL); 520 originator_port = packet_get_int(); 521 packet_check_eom(); 522 523 debug("%s: originator %s port %d, target %s", __func__, 524 originator, originator_port, target); 525 526 /* XXX fine grained permissions */ 527 if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 && 528 auth_opts->permit_port_forwarding_flag && 529 !options.disable_forwarding && (pw->pw_uid == 0 || use_privsep)) { 530 c = channel_connect_to_path(ssh, target, 531 "direct-streamlocal@openssh.com", "direct-streamlocal"); 532 } else { 533 logit("refused streamlocal port forward: " 534 "originator %s port %d, target %s", 535 originator, originator_port, target); 536 } 537 538 free(originator); 539 free(target); 540 541 return c; 542 } 543 544 static Channel * 545 server_request_tun(struct ssh *ssh) 546 { 547 Channel *c = NULL; 548 int mode, tun, sock; 549 char *tmp, *ifname = NULL; 550 551 mode = packet_get_int(); 552 switch (mode) { 553 case SSH_TUNMODE_POINTOPOINT: 554 case SSH_TUNMODE_ETHERNET: 555 break; 556 default: 557 packet_send_debug("Unsupported tunnel device mode."); 558 return NULL; 559 } 560 if ((options.permit_tun & mode) == 0) { 561 packet_send_debug("Server has rejected tunnel device " 562 "forwarding"); 563 return NULL; 564 } 565 566 tun = packet_get_int(); 567 if (auth_opts->force_tun_device != -1) { 568 if (tun != SSH_TUNID_ANY && auth_opts->force_tun_device != tun) 569 goto done; 570 tun = auth_opts->force_tun_device; 571 } 572 sock = tun_open(tun, mode, &ifname); 573 if (sock < 0) 574 goto done; 575 debug("Tunnel forwarding using interface %s", ifname); 576 577 if (options.hpn_disabled) 578 c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1, 579 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1); 580 else 581 c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1, 582 options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1); 583 c->datagram = 1; 584 585 /* 586 * Update the list of names exposed to the session 587 * XXX remove these if the tunnels are closed (won't matter 588 * much if they are already in the environment though) 589 */ 590 tmp = tun_fwd_ifnames; 591 xasprintf(&tun_fwd_ifnames, "%s%s%s", 592 tun_fwd_ifnames == NULL ? "" : tun_fwd_ifnames, 593 tun_fwd_ifnames == NULL ? "" : ",", 594 ifname); 595 free(tmp); 596 free(ifname); 597 598 done: 599 if (c == NULL) 600 packet_send_debug("Failed to open the tunnel device."); 601 return c; 602 } 603 604 static Channel * 605 server_request_session(struct ssh *ssh) 606 { 607 Channel *c; 608 609 debug("input_session_request"); 610 packet_check_eom(); 611 612 if (no_more_sessions) { 613 packet_disconnect("Possible attack: attempt to open a session " 614 "after additional sessions disabled"); 615 } 616 617 /* 618 * A server session has no fd to read or write until a 619 * CHANNEL_REQUEST for a shell is made, so we set the type to 620 * SSH_CHANNEL_LARVAL. Additionally, a callback for handling all 621 * CHANNEL_REQUEST messages is registered. 622 */ 623 c = channel_new(ssh, "session", SSH_CHANNEL_LARVAL, 624 -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT, 625 0, "server-session", 1); 626 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) 627 c->dynamic_window = 1; 628 if (session_open(the_authctxt, c->self) != 1) { 629 debug("session open failed, free channel %d", c->self); 630 channel_free(ssh, c); 631 return NULL; 632 } 633 channel_register_cleanup(ssh, c->self, session_close_by_channel, 0); 634 return c; 635 } 636 637 static int 638 server_input_channel_open(int type, u_int32_t seq, struct ssh *ssh) 639 { 640 Channel *c = NULL; 641 char *ctype; 642 const char *errmsg = NULL; 643 int rchan, reason = SSH2_OPEN_CONNECT_FAILED; 644 u_int rmaxpack, rwindow, len; 645 646 ctype = packet_get_string(&len); 647 rchan = packet_get_int(); 648 rwindow = packet_get_int(); 649 rmaxpack = packet_get_int(); 650 651 debug("server_input_channel_open: ctype %s rchan %d win %d max %d", 652 ctype, rchan, rwindow, rmaxpack); 653 654 if (strcmp(ctype, "session") == 0) { 655 c = server_request_session(ssh); 656 } else if (strcmp(ctype, "direct-tcpip") == 0) { 657 c = server_request_direct_tcpip(ssh, &reason, &errmsg); 658 } else if (strcmp(ctype, "direct-streamlocal@openssh.com") == 0) { 659 c = server_request_direct_streamlocal(ssh); 660 } else if (strcmp(ctype, "tun@openssh.com") == 0) { 661 c = server_request_tun(ssh); 662 } 663 if (c != NULL) { 664 debug("server_input_channel_open: confirm %s", ctype); 665 c->remote_id = rchan; 666 c->have_remote_id = 1; 667 c->remote_window = rwindow; 668 c->remote_maxpacket = rmaxpack; 669 if (c->type != SSH_CHANNEL_CONNECTING) { 670 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION); 671 packet_put_int(c->remote_id); 672 packet_put_int(c->self); 673 packet_put_int(c->local_window); 674 packet_put_int(c->local_maxpacket); 675 packet_send(); 676 } 677 } else { 678 debug("server_input_channel_open: failure %s", ctype); 679 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE); 680 packet_put_int(rchan); 681 packet_put_int(reason); 682 packet_put_cstring(errmsg ? errmsg : "open failed"); 683 packet_put_cstring(""); 684 packet_send(); 685 } 686 free(ctype); 687 return 0; 688 } 689 690 static int 691 server_input_hostkeys_prove(struct ssh *ssh, struct sshbuf **respp) 692 { 693 struct sshbuf *resp = NULL; 694 struct sshbuf *sigbuf = NULL; 695 struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL; 696 int r, ndx, kexsigtype, use_kexsigtype, success = 0; 697 const u_char *blob; 698 u_char *sig = 0; 699 size_t blen, slen; 700 701 if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL) 702 fatal("%s: sshbuf_new", __func__); 703 704 kexsigtype = sshkey_type_plain( 705 sshkey_type_from_name(ssh->kex->hostkey_alg)); 706 while (ssh_packet_remaining(ssh) > 0) { 707 sshkey_free(key); 708 key = NULL; 709 if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 || 710 (r = sshkey_from_blob(blob, blen, &key)) != 0) { 711 error("%s: couldn't parse key: %s", 712 __func__, ssh_err(r)); 713 goto out; 714 } 715 /* 716 * Better check that this is actually one of our hostkeys 717 * before attempting to sign anything with it. 718 */ 719 if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) { 720 error("%s: unknown host %s key", 721 __func__, sshkey_type(key)); 722 goto out; 723 } 724 /* 725 * XXX refactor: make kex->sign just use an index rather 726 * than passing in public and private keys 727 */ 728 if ((key_prv = get_hostkey_by_index(ndx)) == NULL && 729 (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) { 730 error("%s: can't retrieve hostkey %d", __func__, ndx); 731 goto out; 732 } 733 sshbuf_reset(sigbuf); 734 free(sig); 735 sig = NULL; 736 /* 737 * For RSA keys, prefer to use the signature type negotiated 738 * during KEX to the default (SHA1). 739 */ 740 use_kexsigtype = kexsigtype == KEY_RSA && 741 sshkey_type_plain(key->type) == KEY_RSA; 742 if ((r = sshbuf_put_cstring(sigbuf, 743 "hostkeys-prove-00@openssh.com")) != 0 || 744 (r = sshbuf_put_string(sigbuf, 745 ssh->kex->session_id, ssh->kex->session_id_len)) != 0 || 746 (r = sshkey_puts(key, sigbuf)) != 0 || 747 (r = ssh->kex->sign(key_prv, key_pub, &sig, &slen, 748 sshbuf_ptr(sigbuf), sshbuf_len(sigbuf), 749 use_kexsigtype ? ssh->kex->hostkey_alg : NULL, 0)) != 0 || 750 (r = sshbuf_put_string(resp, sig, slen)) != 0) { 751 error("%s: couldn't prepare signature: %s", 752 __func__, ssh_err(r)); 753 goto out; 754 } 755 } 756 /* Success */ 757 *respp = resp; 758 resp = NULL; /* don't free it */ 759 success = 1; 760 out: 761 free(sig); 762 sshbuf_free(resp); 763 sshbuf_free(sigbuf); 764 sshkey_free(key); 765 return success; 766 } 767 768 static int 769 server_input_global_request(int type, u_int32_t seq, struct ssh *ssh) 770 { 771 char *rtype; 772 int want_reply; 773 int r, success = 0, allocated_listen_port = 0; 774 struct sshbuf *resp = NULL; 775 struct passwd *pw = the_authctxt->pw; 776 777 if (pw == NULL || !the_authctxt->valid) 778 fatal("server_input_global_request: no/invalid user"); 779 780 rtype = packet_get_string(NULL); 781 want_reply = packet_get_char(); 782 debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply); 783 784 /* -R style forwarding */ 785 if (strcmp(rtype, "tcpip-forward") == 0) { 786 struct Forward fwd; 787 788 memset(&fwd, 0, sizeof(fwd)); 789 fwd.listen_host = packet_get_string(NULL); 790 fwd.listen_port = (u_short)packet_get_int(); 791 debug("server_input_global_request: tcpip-forward listen %s port %d", 792 fwd.listen_host, fwd.listen_port); 793 794 /* check permissions */ 795 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 || 796 !auth_opts->permit_port_forwarding_flag || 797 options.disable_forwarding || 798 (!want_reply && fwd.listen_port == 0) || 799 (fwd.listen_port != 0 && 800 !bind_permitted(fwd.listen_port, pw->pw_uid))) { 801 success = 0; 802 packet_send_debug("Server has disabled port forwarding."); 803 } else { 804 /* Start listening on the port */ 805 success = channel_setup_remote_fwd_listener(ssh, &fwd, 806 &allocated_listen_port, &options.fwd_opts); 807 } 808 free(fwd.listen_host); 809 if ((resp = sshbuf_new()) == NULL) 810 fatal("%s: sshbuf_new", __func__); 811 if (allocated_listen_port != 0 && 812 (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0) 813 fatal("%s: sshbuf_put_u32: %s", __func__, ssh_err(r)); 814 } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) { 815 struct Forward fwd; 816 817 memset(&fwd, 0, sizeof(fwd)); 818 fwd.listen_host = packet_get_string(NULL); 819 fwd.listen_port = (u_short)packet_get_int(); 820 debug("%s: cancel-tcpip-forward addr %s port %d", __func__, 821 fwd.listen_host, fwd.listen_port); 822 823 success = channel_cancel_rport_listener(ssh, &fwd); 824 free(fwd.listen_host); 825 } else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) { 826 struct Forward fwd; 827 828 memset(&fwd, 0, sizeof(fwd)); 829 fwd.listen_path = packet_get_string(NULL); 830 debug("server_input_global_request: streamlocal-forward listen path %s", 831 fwd.listen_path); 832 833 /* check permissions */ 834 if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0 835 || !auth_opts->permit_port_forwarding_flag || 836 options.disable_forwarding || 837 (pw->pw_uid != 0 && !use_privsep)) { 838 success = 0; 839 packet_send_debug("Server has disabled " 840 "streamlocal forwarding."); 841 } else { 842 /* Start listening on the socket */ 843 success = channel_setup_remote_fwd_listener(ssh, 844 &fwd, NULL, &options.fwd_opts); 845 } 846 free(fwd.listen_path); 847 } else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) { 848 struct Forward fwd; 849 850 memset(&fwd, 0, sizeof(fwd)); 851 fwd.listen_path = packet_get_string(NULL); 852 debug("%s: cancel-streamlocal-forward path %s", __func__, 853 fwd.listen_path); 854 855 success = channel_cancel_rport_listener(ssh, &fwd); 856 free(fwd.listen_path); 857 } else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) { 858 no_more_sessions = 1; 859 success = 1; 860 } else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) { 861 success = server_input_hostkeys_prove(ssh, &resp); 862 } 863 if (want_reply) { 864 packet_start(success ? 865 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE); 866 if (success && resp != NULL) 867 ssh_packet_put_raw(ssh, sshbuf_ptr(resp), 868 sshbuf_len(resp)); 869 packet_send(); 870 packet_write_wait(); 871 } 872 free(rtype); 873 sshbuf_free(resp); 874 return 0; 875 } 876 877 static int 878 server_input_channel_req(int type, u_int32_t seq, struct ssh *ssh) 879 { 880 Channel *c; 881 int id, reply, success = 0; 882 char *rtype; 883 884 id = packet_get_int(); 885 rtype = packet_get_string(NULL); 886 reply = packet_get_char(); 887 888 debug("server_input_channel_req: channel %d request %s reply %d", 889 id, rtype, reply); 890 891 if ((c = channel_lookup(ssh, id)) == NULL) 892 packet_disconnect("server_input_channel_req: " 893 "unknown channel %d", id); 894 if (!strcmp(rtype, "eow@openssh.com")) { 895 packet_check_eom(); 896 chan_rcvd_eow(ssh, c); 897 } else if ((c->type == SSH_CHANNEL_LARVAL || 898 c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0) 899 success = session_input_channel_req(ssh, c, rtype); 900 if (reply && !(c->flags & CHAN_CLOSE_SENT)) { 901 if (!c->have_remote_id) 902 fatal("%s: channel %d: no remote_id", 903 __func__, c->self); 904 packet_start(success ? 905 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE); 906 packet_put_int(c->remote_id); 907 packet_send(); 908 } 909 free(rtype); 910 return 0; 911 } 912 913 static void 914 server_init_dispatch(void) 915 { 916 debug("server_init_dispatch"); 917 dispatch_init(&dispatch_protocol_error); 918 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose); 919 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data); 920 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof); 921 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data); 922 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open); 923 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation); 924 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure); 925 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req); 926 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust); 927 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request); 928 /* client_alive */ 929 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive); 930 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive); 931 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive); 932 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive); 933 /* rekeying */ 934 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit); 935 } 936