1 /* $OpenBSD: serverloop.c,v 1.213 2019/01/19 22:30: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 * Server main loop for handling the interactive session. 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 * SSH2 support by Markus Friedl. 15 * Copyright (c) 2000, 2001 Markus Friedl. 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 #include <sys/types.h> 39 #include <sys/wait.h> 40 #include <sys/socket.h> 41 #include <sys/time.h> 42 #include <sys/queue.h> 43 44 #include <netinet/in.h> 45 46 #include <errno.h> 47 #include <fcntl.h> 48 #include <pwd.h> 49 #include <limits.h> 50 #include <signal.h> 51 #include <string.h> 52 #include <termios.h> 53 #include <unistd.h> 54 #include <stdarg.h> 55 56 #include "xmalloc.h" 57 #include "packet.h" 58 #include "sshbuf.h" 59 #include "log.h" 60 #include "misc.h" 61 #include "servconf.h" 62 #include "canohost.h" 63 #include "sshpty.h" 64 #include "channels.h" 65 #include "compat.h" 66 #include "ssh2.h" 67 #include "sshkey.h" 68 #include "cipher.h" 69 #include "kex.h" 70 #include "hostfile.h" 71 #include "auth.h" 72 #include "session.h" 73 #include "dispatch.h" 74 #include "auth-options.h" 75 #include "serverloop.h" 76 #include "ssherr.h" 77 78 extern ServerOptions options; 79 80 /* XXX */ 81 extern Authctxt *the_authctxt; 82 extern struct sshauthopt *auth_opts; 83 extern int use_privsep; 84 85 static int no_more_sessions = 0; /* Disallow further sessions. */ 86 87 /* 88 * This SIGCHLD kludge is used to detect when the child exits. The server 89 * will exit after that, as soon as forwarded connections have terminated. 90 */ 91 92 static volatile sig_atomic_t child_terminated = 0; /* The child has terminated. */ 93 94 /* Cleanup on signals (!use_privsep case only) */ 95 static volatile sig_atomic_t received_sigterm = 0; 96 97 /* prototypes */ 98 static void server_init_dispatch(struct ssh *); 99 100 /* requested tunnel forwarding interface(s), shared with session.c */ 101 char *tun_fwd_ifnames = NULL; 102 103 /* returns 1 if bind to specified port by specified user is permitted */ 104 static int 105 bind_permitted(int port, uid_t uid) 106 { 107 if (use_privsep) 108 return 1; /* allow system to decide */ 109 if (port < IPPORT_RESERVED && uid != 0) 110 return 0; 111 return 1; 112 } 113 114 /* 115 * we write to this pipe if a SIGCHLD is caught in order to avoid 116 * the race between select() and child_terminated 117 */ 118 static int notify_pipe[2]; 119 static void 120 notify_setup(void) 121 { 122 if (pipe(notify_pipe) < 0) { 123 error("pipe(notify_pipe) failed %s", strerror(errno)); 124 } else if ((fcntl(notify_pipe[0], F_SETFD, FD_CLOEXEC) == -1) || 125 (fcntl(notify_pipe[1], F_SETFD, FD_CLOEXEC) == -1)) { 126 error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno)); 127 close(notify_pipe[0]); 128 close(notify_pipe[1]); 129 } else { 130 set_nonblock(notify_pipe[0]); 131 set_nonblock(notify_pipe[1]); 132 return; 133 } 134 notify_pipe[0] = -1; /* read end */ 135 notify_pipe[1] = -1; /* write end */ 136 } 137 static void 138 notify_parent(void) 139 { 140 if (notify_pipe[1] != -1) 141 (void)write(notify_pipe[1], "", 1); 142 } 143 static void 144 notify_prepare(fd_set *readset) 145 { 146 if (notify_pipe[0] != -1) 147 FD_SET(notify_pipe[0], readset); 148 } 149 static void 150 notify_done(fd_set *readset) 151 { 152 char c; 153 154 if (notify_pipe[0] != -1 && FD_ISSET(notify_pipe[0], readset)) 155 while (read(notify_pipe[0], &c, 1) != -1) 156 debug2("%s: reading", __func__); 157 } 158 159 /*ARGSUSED*/ 160 static void 161 sigchld_handler(int sig) 162 { 163 int save_errno = errno; 164 child_terminated = 1; 165 notify_parent(); 166 errno = save_errno; 167 } 168 169 /*ARGSUSED*/ 170 static void 171 sigterm_handler(int sig) 172 { 173 received_sigterm = sig; 174 } 175 176 static void 177 client_alive_check(struct ssh *ssh) 178 { 179 char remote_id[512]; 180 int r, channel_id; 181 182 /* timeout, check to see how many we have had */ 183 if (ssh_packet_inc_alive_timeouts(ssh) > 184 options.client_alive_count_max) { 185 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id)); 186 logit("Timeout, client not responding from %s", remote_id); 187 cleanup_exit(255); 188 } 189 190 /* 191 * send a bogus global/channel request with "wantreply", 192 * we should get back a failure 193 */ 194 if ((channel_id = channel_find_open(ssh)) == -1) { 195 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 196 (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) 197 != 0 || 198 (r = sshpkt_put_u8(ssh, 1)) != 0) /* boolean: want reply */ 199 fatal("%s: %s", __func__, ssh_err(r)); 200 } else { 201 channel_request_start(ssh, channel_id, 202 "keepalive@openssh.com", 1); 203 } 204 if ((r = sshpkt_send(ssh)) != 0) 205 fatal("%s: %s", __func__, ssh_err(r)); 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 (ssh_packet_have_data_to_write(ssh)) 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 && ssh_packet_not_very_much_data_to_write(ssh)) 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 r, 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 if ((r = ssh_packet_process_incoming(ssh, buf, len)) 334 != 0) 335 fatal("%s: ssh_packet_process_incoming: %s", 336 __func__, ssh_err(r)); 337 } 338 } 339 return 0; 340 } 341 342 /* 343 * Sends data from internal buffers to client program stdin. 344 */ 345 static void 346 process_output(struct ssh *ssh, fd_set *writeset, int connection_out) 347 { 348 int r; 349 350 /* Send any buffered packet data to the client. */ 351 if (FD_ISSET(connection_out, writeset)) { 352 if ((r = ssh_packet_write_poll(ssh)) != 0) 353 fatal("%s: ssh_packet_write_poll: %s", 354 __func__, ssh_err(r)); 355 } 356 } 357 358 static void 359 process_buffered_input_packets(struct ssh *ssh) 360 { 361 ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, NULL); 362 } 363 364 static void 365 collect_children(struct ssh *ssh) 366 { 367 pid_t pid; 368 sigset_t oset, nset; 369 int status; 370 371 /* block SIGCHLD while we check for dead children */ 372 sigemptyset(&nset); 373 sigaddset(&nset, SIGCHLD); 374 sigprocmask(SIG_BLOCK, &nset, &oset); 375 if (child_terminated) { 376 debug("Received SIGCHLD."); 377 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 378 (pid < 0 && errno == EINTR)) 379 if (pid > 0) 380 session_close_by_pid(ssh, pid, status); 381 child_terminated = 0; 382 } 383 sigprocmask(SIG_SETMASK, &oset, NULL); 384 } 385 386 void 387 server_loop2(struct ssh *ssh, Authctxt *authctxt) 388 { 389 fd_set *readset = NULL, *writeset = NULL; 390 int max_fd; 391 u_int nalloc = 0, connection_in, connection_out; 392 u_int64_t rekey_timeout_ms = 0; 393 394 debug("Entering interactive session for SSH2."); 395 396 signal(SIGCHLD, sigchld_handler); 397 child_terminated = 0; 398 connection_in = ssh_packet_get_connection_in(ssh); 399 connection_out = ssh_packet_get_connection_out(ssh); 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(ssh); 413 414 for (;;) { 415 process_buffered_input_packets(ssh); 416 417 if (!ssh_packet_is_rekeying(ssh) && 418 ssh_packet_not_very_much_data_to_write(ssh)) 419 channel_output_poll(ssh); 420 if (options.rekey_interval > 0 && 421 !ssh_packet_is_rekeying(ssh)) { 422 rekey_timeout_ms = ssh_packet_get_rekey_timeout(ssh) * 423 1000; 424 } else { 425 rekey_timeout_ms = 0; 426 } 427 428 wait_until_can_do_something(ssh, connection_in, connection_out, 429 &readset, &writeset, &max_fd, &nalloc, rekey_timeout_ms); 430 431 if (received_sigterm) { 432 logit("Exiting on signal %d", (int)received_sigterm); 433 /* Clean up sessions, utmp, etc. */ 434 cleanup_exit(255); 435 } 436 437 collect_children(ssh); 438 if (!ssh_packet_is_rekeying(ssh)) 439 channel_after_select(ssh, readset, writeset); 440 if (process_input(ssh, readset, connection_in) < 0) 441 break; 442 process_output(ssh, writeset, connection_out); 443 } 444 collect_children(ssh); 445 446 free(readset); 447 free(writeset); 448 449 /* free all channels, no more reads and writes */ 450 channel_free_all(ssh); 451 452 /* free remaining sessions, e.g. remove wtmp entries */ 453 session_destroy_all(ssh, NULL); 454 } 455 456 static int 457 server_input_keep_alive(int type, u_int32_t seq, struct ssh *ssh) 458 { 459 debug("Got %d/%u for keepalive", type, seq); 460 /* 461 * reset timeout, since we got a sane answer from the client. 462 * even if this was generated by something other than 463 * the bogus CHANNEL_REQUEST we send for keepalives. 464 */ 465 ssh_packet_set_alive_timeouts(ssh, 0); 466 return 0; 467 } 468 469 static Channel * 470 server_request_direct_tcpip(struct ssh *ssh, int *reason, const char **errmsg) 471 { 472 Channel *c = NULL; 473 char *target = NULL, *originator = NULL; 474 u_int target_port = 0, originator_port = 0; 475 int r; 476 477 if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 || 478 (r = sshpkt_get_u32(ssh, &target_port)) != 0 || 479 (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 || 480 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 || 481 (r = sshpkt_get_end(ssh)) != 0) 482 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 483 if (target_port > 0xFFFF) { 484 error("%s: invalid target port", __func__); 485 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED; 486 goto out; 487 } 488 if (originator_port > 0xFFFF) { 489 error("%s: invalid originator port", __func__); 490 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED; 491 goto out; 492 } 493 494 debug("%s: originator %s port %u, target %s port %u", __func__, 495 originator, originator_port, target, target_port); 496 497 /* XXX fine grained permissions */ 498 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 && 499 auth_opts->permit_port_forwarding_flag && 500 !options.disable_forwarding) { 501 c = channel_connect_to_port(ssh, target, target_port, 502 "direct-tcpip", "direct-tcpip", reason, errmsg); 503 } else { 504 logit("refused local port forward: " 505 "originator %s port %d, target %s port %d", 506 originator, originator_port, target, target_port); 507 if (reason != NULL) 508 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED; 509 } 510 511 out: 512 free(originator); 513 free(target); 514 return c; 515 } 516 517 static Channel * 518 server_request_direct_streamlocal(struct ssh *ssh) 519 { 520 Channel *c = NULL; 521 char *target = NULL, *originator = NULL; 522 u_int originator_port = 0; 523 struct passwd *pw = the_authctxt->pw; 524 int r; 525 526 if (pw == NULL || !the_authctxt->valid) 527 fatal("%s: no/invalid user", __func__); 528 529 if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 || 530 (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 || 531 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 || 532 (r = sshpkt_get_end(ssh)) != 0) 533 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 534 if (originator_port > 0xFFFF) { 535 error("%s: invalid originator port", __func__); 536 goto out; 537 } 538 539 debug("%s: originator %s port %d, target %s", __func__, 540 originator, originator_port, target); 541 542 /* XXX fine grained permissions */ 543 if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 && 544 auth_opts->permit_port_forwarding_flag && 545 !options.disable_forwarding && (pw->pw_uid == 0 || use_privsep)) { 546 c = channel_connect_to_path(ssh, target, 547 "direct-streamlocal@openssh.com", "direct-streamlocal"); 548 } else { 549 logit("refused streamlocal port forward: " 550 "originator %s port %d, target %s", 551 originator, originator_port, target); 552 } 553 554 out: 555 free(originator); 556 free(target); 557 return c; 558 } 559 560 static Channel * 561 server_request_tun(struct ssh *ssh) 562 { 563 Channel *c = NULL; 564 u_int mode, tun; 565 int r, sock; 566 char *tmp, *ifname = NULL; 567 568 if ((r = sshpkt_get_u32(ssh, &mode)) != 0) 569 sshpkt_fatal(ssh, r, "%s: parse mode", __func__); 570 switch (mode) { 571 case SSH_TUNMODE_POINTOPOINT: 572 case SSH_TUNMODE_ETHERNET: 573 break; 574 default: 575 ssh_packet_send_debug(ssh, "Unsupported tunnel device mode."); 576 return NULL; 577 } 578 if ((options.permit_tun & mode) == 0) { 579 ssh_packet_send_debug(ssh, "Server has rejected tunnel device " 580 "forwarding"); 581 return NULL; 582 } 583 584 if ((r = sshpkt_get_u32(ssh, &tun)) != 0) 585 sshpkt_fatal(ssh, r, "%s: parse device", __func__); 586 if (tun > INT_MAX) { 587 debug("%s: invalid tun", __func__); 588 goto done; 589 } 590 if (auth_opts->force_tun_device != -1) { 591 if (tun != SSH_TUNID_ANY && 592 auth_opts->force_tun_device != (int)tun) 593 goto done; 594 tun = auth_opts->force_tun_device; 595 } 596 sock = tun_open(tun, mode, &ifname); 597 if (sock < 0) 598 goto done; 599 debug("Tunnel forwarding using interface %s", ifname); 600 601 c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1, 602 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1); 603 c->datagram = 1; 604 605 /* 606 * Update the list of names exposed to the session 607 * XXX remove these if the tunnels are closed (won't matter 608 * much if they are already in the environment though) 609 */ 610 tmp = tun_fwd_ifnames; 611 xasprintf(&tun_fwd_ifnames, "%s%s%s", 612 tun_fwd_ifnames == NULL ? "" : tun_fwd_ifnames, 613 tun_fwd_ifnames == NULL ? "" : ",", 614 ifname); 615 free(tmp); 616 free(ifname); 617 618 done: 619 if (c == NULL) 620 ssh_packet_send_debug(ssh, "Failed to open the tunnel device."); 621 return c; 622 } 623 624 static Channel * 625 server_request_session(struct ssh *ssh) 626 { 627 Channel *c; 628 int r; 629 630 debug("input_session_request"); 631 if ((r = sshpkt_get_end(ssh)) != 0) 632 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 633 634 if (no_more_sessions) { 635 ssh_packet_disconnect(ssh, "Possible attack: attempt to open a " 636 "session after additional sessions disabled"); 637 } 638 639 /* 640 * A server session has no fd to read or write until a 641 * CHANNEL_REQUEST for a shell is made, so we set the type to 642 * SSH_CHANNEL_LARVAL. Additionally, a callback for handling all 643 * CHANNEL_REQUEST messages is registered. 644 */ 645 c = channel_new(ssh, "session", SSH_CHANNEL_LARVAL, 646 -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT, 647 0, "server-session", 1); 648 if (session_open(the_authctxt, c->self) != 1) { 649 debug("session open failed, free channel %d", c->self); 650 channel_free(ssh, c); 651 return NULL; 652 } 653 channel_register_cleanup(ssh, c->self, session_close_by_channel, 0); 654 return c; 655 } 656 657 static int 658 server_input_channel_open(int type, u_int32_t seq, struct ssh *ssh) 659 { 660 Channel *c = NULL; 661 char *ctype = NULL; 662 const char *errmsg = NULL; 663 int r, reason = SSH2_OPEN_CONNECT_FAILED; 664 u_int rchan = 0, rmaxpack = 0, rwindow = 0; 665 666 if ((r = sshpkt_get_cstring(ssh, &ctype, NULL)) != 0 || 667 (r = sshpkt_get_u32(ssh, &rchan)) != 0 || 668 (r = sshpkt_get_u32(ssh, &rwindow)) != 0 || 669 (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0) 670 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 671 debug("%s: ctype %s rchan %u win %u max %u", __func__, 672 ctype, rchan, rwindow, rmaxpack); 673 674 if (rchan > INT_MAX) { 675 error("%s: invalid remote channel ID", __func__); 676 } else if (strcmp(ctype, "session") == 0) { 677 c = server_request_session(ssh); 678 } else if (strcmp(ctype, "direct-tcpip") == 0) { 679 c = server_request_direct_tcpip(ssh, &reason, &errmsg); 680 } else if (strcmp(ctype, "direct-streamlocal@openssh.com") == 0) { 681 c = server_request_direct_streamlocal(ssh); 682 } else if (strcmp(ctype, "tun@openssh.com") == 0) { 683 c = server_request_tun(ssh); 684 } 685 if (c != NULL) { 686 debug("%s: confirm %s", __func__, ctype); 687 c->remote_id = (int)rchan; 688 c->have_remote_id = 1; 689 c->remote_window = rwindow; 690 c->remote_maxpacket = rmaxpack; 691 if (c->type != SSH_CHANNEL_CONNECTING) { 692 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 || 693 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 || 694 (r = sshpkt_put_u32(ssh, c->self)) != 0 || 695 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 || 696 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 || 697 (r = sshpkt_send(ssh)) != 0) { 698 sshpkt_fatal(ssh, r, 699 "%s: send open confirm", __func__); 700 } 701 } 702 } else { 703 debug("%s: failure %s", __func__, ctype); 704 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 || 705 (r = sshpkt_put_u32(ssh, rchan)) != 0 || 706 (r = sshpkt_put_u32(ssh, reason)) != 0 || 707 (r = sshpkt_put_cstring(ssh, errmsg ? errmsg : "open failed")) != 0 || 708 (r = sshpkt_put_cstring(ssh, "")) != 0 || 709 (r = sshpkt_send(ssh)) != 0) { 710 sshpkt_fatal(ssh, r, 711 "%s: send open failure", __func__); 712 } 713 } 714 free(ctype); 715 return 0; 716 } 717 718 static int 719 server_input_hostkeys_prove(struct ssh *ssh, struct sshbuf **respp) 720 { 721 struct sshbuf *resp = NULL; 722 struct sshbuf *sigbuf = NULL; 723 struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL; 724 int r, ndx, kexsigtype, use_kexsigtype, success = 0; 725 const u_char *blob; 726 u_char *sig = 0; 727 size_t blen, slen; 728 729 if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL) 730 fatal("%s: sshbuf_new", __func__); 731 732 kexsigtype = sshkey_type_plain( 733 sshkey_type_from_name(ssh->kex->hostkey_alg)); 734 while (ssh_packet_remaining(ssh) > 0) { 735 sshkey_free(key); 736 key = NULL; 737 if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 || 738 (r = sshkey_from_blob(blob, blen, &key)) != 0) { 739 error("%s: couldn't parse key: %s", 740 __func__, ssh_err(r)); 741 goto out; 742 } 743 /* 744 * Better check that this is actually one of our hostkeys 745 * before attempting to sign anything with it. 746 */ 747 if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) { 748 error("%s: unknown host %s key", 749 __func__, sshkey_type(key)); 750 goto out; 751 } 752 /* 753 * XXX refactor: make kex->sign just use an index rather 754 * than passing in public and private keys 755 */ 756 if ((key_prv = get_hostkey_by_index(ndx)) == NULL && 757 (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) { 758 error("%s: can't retrieve hostkey %d", __func__, ndx); 759 goto out; 760 } 761 sshbuf_reset(sigbuf); 762 free(sig); 763 sig = NULL; 764 /* 765 * For RSA keys, prefer to use the signature type negotiated 766 * during KEX to the default (SHA1). 767 */ 768 use_kexsigtype = kexsigtype == KEY_RSA && 769 sshkey_type_plain(key->type) == KEY_RSA; 770 if ((r = sshbuf_put_cstring(sigbuf, 771 "hostkeys-prove-00@openssh.com")) != 0 || 772 (r = sshbuf_put_string(sigbuf, 773 ssh->kex->session_id, ssh->kex->session_id_len)) != 0 || 774 (r = sshkey_puts(key, sigbuf)) != 0 || 775 (r = ssh->kex->sign(ssh, key_prv, key_pub, &sig, &slen, 776 sshbuf_ptr(sigbuf), sshbuf_len(sigbuf), 777 use_kexsigtype ? ssh->kex->hostkey_alg : NULL)) != 0 || 778 (r = sshbuf_put_string(resp, sig, slen)) != 0) { 779 error("%s: couldn't prepare signature: %s", 780 __func__, ssh_err(r)); 781 goto out; 782 } 783 } 784 /* Success */ 785 *respp = resp; 786 resp = NULL; /* don't free it */ 787 success = 1; 788 out: 789 free(sig); 790 sshbuf_free(resp); 791 sshbuf_free(sigbuf); 792 sshkey_free(key); 793 return success; 794 } 795 796 static int 797 server_input_global_request(int type, u_int32_t seq, struct ssh *ssh) 798 { 799 char *rtype = NULL; 800 u_char want_reply = 0; 801 int r, success = 0, allocated_listen_port = 0; 802 u_int port = 0; 803 struct sshbuf *resp = NULL; 804 struct passwd *pw = the_authctxt->pw; 805 struct Forward fwd; 806 807 memset(&fwd, 0, sizeof(fwd)); 808 if (pw == NULL || !the_authctxt->valid) 809 fatal("%s: no/invalid user", __func__); 810 811 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 || 812 (r = sshpkt_get_u8(ssh, &want_reply)) != 0) 813 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 814 debug("%s: rtype %s want_reply %d", __func__, rtype, want_reply); 815 816 /* -R style forwarding */ 817 if (strcmp(rtype, "tcpip-forward") == 0) { 818 if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 || 819 (r = sshpkt_get_u32(ssh, &port)) != 0) 820 sshpkt_fatal(ssh, r, "%s: parse tcpip-forward", __func__); 821 debug("%s: tcpip-forward listen %s port %u", __func__, 822 fwd.listen_host, port); 823 if (port <= INT_MAX) 824 fwd.listen_port = (int)port; 825 /* check permissions */ 826 if (port > INT_MAX || 827 (options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 || 828 !auth_opts->permit_port_forwarding_flag || 829 options.disable_forwarding || 830 (!want_reply && fwd.listen_port == 0) || 831 (fwd.listen_port != 0 && 832 !bind_permitted(fwd.listen_port, pw->pw_uid))) { 833 success = 0; 834 ssh_packet_send_debug(ssh, "Server has disabled port forwarding."); 835 } else { 836 /* Start listening on the port */ 837 success = channel_setup_remote_fwd_listener(ssh, &fwd, 838 &allocated_listen_port, &options.fwd_opts); 839 } 840 if ((resp = sshbuf_new()) == NULL) 841 fatal("%s: sshbuf_new", __func__); 842 if (allocated_listen_port != 0 && 843 (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0) 844 fatal("%s: sshbuf_put_u32: %s", __func__, ssh_err(r)); 845 } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) { 846 if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 || 847 (r = sshpkt_get_u32(ssh, &port)) != 0) 848 sshpkt_fatal(ssh, r, "%s: parse cancel-tcpip-forward", __func__); 849 850 debug("%s: cancel-tcpip-forward addr %s port %d", __func__, 851 fwd.listen_host, port); 852 if (port <= INT_MAX) { 853 fwd.listen_port = (int)port; 854 success = channel_cancel_rport_listener(ssh, &fwd); 855 } 856 } else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) { 857 if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0) 858 sshpkt_fatal(ssh, r, "%s: parse streamlocal-forward@openssh.com", __func__); 859 debug("%s: streamlocal-forward listen path %s", __func__, 860 fwd.listen_path); 861 862 /* check permissions */ 863 if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0 864 || !auth_opts->permit_port_forwarding_flag || 865 options.disable_forwarding || 866 (pw->pw_uid != 0 && !use_privsep)) { 867 success = 0; 868 ssh_packet_send_debug(ssh, "Server has disabled " 869 "streamlocal forwarding."); 870 } else { 871 /* Start listening on the socket */ 872 success = channel_setup_remote_fwd_listener(ssh, 873 &fwd, NULL, &options.fwd_opts); 874 } 875 } else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) { 876 if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0) 877 sshpkt_fatal(ssh, r, "%s: parse cancel-streamlocal-forward@openssh.com", __func__); 878 debug("%s: cancel-streamlocal-forward path %s", __func__, 879 fwd.listen_path); 880 881 success = channel_cancel_rport_listener(ssh, &fwd); 882 } else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) { 883 no_more_sessions = 1; 884 success = 1; 885 } else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) { 886 success = server_input_hostkeys_prove(ssh, &resp); 887 } 888 /* XXX sshpkt_get_end() */ 889 if (want_reply) { 890 if ((r = sshpkt_start(ssh, success ? 891 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE)) != 0 || 892 (success && resp != NULL && (r = sshpkt_putb(ssh, resp)) != 0) || 893 (r = sshpkt_send(ssh)) != 0 || 894 (r = ssh_packet_write_wait(ssh)) != 0) 895 sshpkt_fatal(ssh, r, "%s: send reply", __func__); 896 } 897 free(fwd.listen_host); 898 free(fwd.listen_path); 899 free(rtype); 900 sshbuf_free(resp); 901 return 0; 902 } 903 904 static int 905 server_input_channel_req(int type, u_int32_t seq, struct ssh *ssh) 906 { 907 Channel *c; 908 int r, success = 0; 909 char *rtype = NULL; 910 u_char want_reply = 0; 911 u_int id = 0; 912 913 if ((r = sshpkt_get_u32(ssh, &id)) != 0 || 914 (r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 || 915 (r = sshpkt_get_u8(ssh, &want_reply)) != 0) 916 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 917 918 debug("server_input_channel_req: channel %u request %s reply %d", 919 id, rtype, want_reply); 920 921 if (id >= INT_MAX || (c = channel_lookup(ssh, (int)id)) == NULL) { 922 ssh_packet_disconnect(ssh, "%s: unknown channel %d", 923 __func__, id); 924 } 925 if (!strcmp(rtype, "eow@openssh.com")) { 926 if ((r = sshpkt_get_end(ssh)) != 0) 927 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 928 chan_rcvd_eow(ssh, c); 929 } else if ((c->type == SSH_CHANNEL_LARVAL || 930 c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0) 931 success = session_input_channel_req(ssh, c, rtype); 932 if (want_reply && !(c->flags & CHAN_CLOSE_SENT)) { 933 if (!c->have_remote_id) 934 fatal("%s: channel %d: no remote_id", 935 __func__, c->self); 936 if ((r = sshpkt_start(ssh, success ? 937 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 || 938 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 || 939 (r = sshpkt_send(ssh)) != 0) 940 sshpkt_fatal(ssh, r, "%s: send reply", __func__); 941 } 942 free(rtype); 943 return 0; 944 } 945 946 static void 947 server_init_dispatch(struct ssh *ssh) 948 { 949 debug("server_init_dispatch"); 950 ssh_dispatch_init(ssh, &dispatch_protocol_error); 951 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose); 952 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data); 953 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof); 954 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data); 955 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open); 956 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation); 957 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure); 958 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req); 959 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust); 960 ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request); 961 /* client_alive */ 962 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive); 963 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive); 964 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive); 965 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive); 966 /* rekeying */ 967 ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit); 968 } 969