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