1 /* $OpenBSD: serverloop.c,v 1.240 2024/06/17 08:28:31 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 "includes.h" 39 40 #include <sys/types.h> 41 #include <sys/wait.h> 42 #include <sys/socket.h> 43 #ifdef HAVE_SYS_TIME_H 44 # include <sys/time.h> 45 #endif 46 47 #include <netinet/in.h> 48 49 #include <errno.h> 50 #include <fcntl.h> 51 #include <pwd.h> 52 #include <limits.h> 53 #ifdef HAVE_POLL_H 54 #include <poll.h> 55 #endif 56 #include <signal.h> 57 #include <string.h> 58 #include <termios.h> 59 #include <unistd.h> 60 #include <stdarg.h> 61 62 #include "openbsd-compat/sys-queue.h" 63 #include "xmalloc.h" 64 #include "packet.h" 65 #include "sshbuf.h" 66 #include "log.h" 67 #include "misc.h" 68 #include "servconf.h" 69 #include "canohost.h" 70 #include "sshpty.h" 71 #include "channels.h" 72 #include "ssh2.h" 73 #include "sshkey.h" 74 #include "cipher.h" 75 #include "kex.h" 76 #include "hostfile.h" 77 #include "auth.h" 78 #include "session.h" 79 #include "dispatch.h" 80 #include "auth-options.h" 81 #include "serverloop.h" 82 #include "ssherr.h" 83 84 extern ServerOptions options; 85 86 /* XXX */ 87 extern Authctxt *the_authctxt; 88 extern struct sshauthopt *auth_opts; 89 90 static int no_more_sessions = 0; /* Disallow further sessions. */ 91 92 static volatile sig_atomic_t child_terminated = 0; /* The child has terminated. */ 93 94 /* prototypes */ 95 static void server_init_dispatch(struct ssh *); 96 97 /* requested tunnel forwarding interface(s), shared with session.c */ 98 char *tun_fwd_ifnames = NULL; 99 100 static void 101 sigchld_handler(int sig) 102 { 103 child_terminated = 1; 104 } 105 106 static void 107 client_alive_check(struct ssh *ssh) 108 { 109 char remote_id[512]; 110 int r, channel_id; 111 112 /* timeout, check to see how many we have had */ 113 if (options.client_alive_count_max > 0 && 114 ssh_packet_inc_alive_timeouts(ssh) > 115 options.client_alive_count_max) { 116 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id)); 117 logit("Timeout, client not responding from %s", remote_id); 118 cleanup_exit(255); 119 } 120 121 /* 122 * send a bogus global/channel request with "wantreply", 123 * we should get back a failure 124 */ 125 if ((channel_id = channel_find_open(ssh)) == -1) { 126 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 127 (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) 128 != 0 || 129 (r = sshpkt_put_u8(ssh, 1)) != 0) /* boolean: want reply */ 130 fatal_fr(r, "compose"); 131 } else { 132 channel_request_start(ssh, channel_id, 133 "keepalive@openssh.com", 1); 134 } 135 if ((r = sshpkt_send(ssh)) != 0) 136 fatal_fr(r, "send"); 137 } 138 139 /* 140 * Sleep in ppoll() until we can do something. 141 * Optionally, a maximum time can be specified for the duration of 142 * the wait (0 = infinite). 143 */ 144 static void 145 wait_until_can_do_something(struct ssh *ssh, 146 int connection_in, int connection_out, struct pollfd **pfdp, 147 u_int *npfd_allocp, u_int *npfd_activep, sigset_t *sigsetp, 148 int *conn_in_readyp, int *conn_out_readyp) 149 { 150 struct timespec timeout; 151 char remote_id[512]; 152 int ret; 153 int client_alive_scheduled = 0; 154 u_int p; 155 time_t now; 156 static time_t last_client_time, unused_connection_expiry; 157 158 *conn_in_readyp = *conn_out_readyp = 0; 159 160 /* Prepare channel poll. First two pollfd entries are reserved */ 161 ptimeout_init(&timeout); 162 channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep, 2, &timeout); 163 now = monotime(); 164 if (*npfd_activep < 2) 165 fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */ 166 if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) { 167 ptimeout_deadline_sec(&timeout, 168 ssh_packet_get_rekey_timeout(ssh)); 169 } 170 171 /* 172 * If no channels are open and UnusedConnectionTimeout is set, then 173 * start the clock to terminate the connection. 174 */ 175 if (options.unused_connection_timeout != 0) { 176 if (channel_still_open(ssh) || unused_connection_expiry == 0) { 177 unused_connection_expiry = now + 178 options.unused_connection_timeout; 179 } 180 ptimeout_deadline_monotime(&timeout, unused_connection_expiry); 181 } 182 183 /* 184 * if using client_alive, set the max timeout accordingly, 185 * and indicate that this particular timeout was for client 186 * alive by setting the client_alive_scheduled flag. 187 * 188 * this could be randomized somewhat to make traffic 189 * analysis more difficult, but we're not doing it yet. 190 */ 191 if (options.client_alive_interval) { 192 /* Time we last heard from the client OR sent a keepalive */ 193 if (last_client_time == 0) 194 last_client_time = now; 195 ptimeout_deadline_sec(&timeout, options.client_alive_interval); 196 /* XXX ? deadline_monotime(last_client_time + alive_interval) */ 197 client_alive_scheduled = 1; 198 } 199 200 #if 0 201 /* wrong: bad condition XXX */ 202 if (channel_not_very_much_buffered_data()) 203 #endif 204 /* Monitor client connection on reserved pollfd entries */ 205 (*pfdp)[0].fd = connection_in; 206 (*pfdp)[0].events = POLLIN; 207 (*pfdp)[1].fd = connection_out; 208 (*pfdp)[1].events = ssh_packet_have_data_to_write(ssh) ? POLLOUT : 0; 209 210 /* 211 * If child has terminated and there is enough buffer space to read 212 * from it, then read as much as is available and exit. 213 */ 214 if (child_terminated && ssh_packet_not_very_much_data_to_write(ssh)) 215 ptimeout_deadline_ms(&timeout, 100); 216 217 /* Wait for something to happen, or the timeout to expire. */ 218 ret = ppoll(*pfdp, *npfd_activep, ptimeout_get_tsp(&timeout), sigsetp); 219 220 if (ret == -1) { 221 for (p = 0; p < *npfd_activep; p++) 222 (*pfdp)[p].revents = 0; 223 if (errno != EINTR) 224 fatal_f("ppoll: %.100s", strerror(errno)); 225 return; 226 } 227 228 *conn_in_readyp = (*pfdp)[0].revents != 0; 229 *conn_out_readyp = (*pfdp)[1].revents != 0; 230 231 now = monotime(); /* need to reset after ppoll() */ 232 /* ClientAliveInterval probing */ 233 if (client_alive_scheduled) { 234 if (ret == 0 && 235 now >= last_client_time + options.client_alive_interval) { 236 /* ppoll timed out and we're due to probe */ 237 client_alive_check(ssh); 238 last_client_time = now; 239 } else if (ret != 0 && *conn_in_readyp) { 240 /* Data from peer; reset probe timer. */ 241 last_client_time = now; 242 } 243 } 244 245 /* UnusedConnectionTimeout handling */ 246 if (unused_connection_expiry != 0 && 247 now > unused_connection_expiry && !channel_still_open(ssh)) { 248 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id)); 249 logit("terminating inactive connection from %s", remote_id); 250 cleanup_exit(255); 251 } 252 } 253 254 /* 255 * Processes input from the client and the program. Input data is stored 256 * in buffers and processed later. 257 */ 258 static int 259 process_input(struct ssh *ssh, int connection_in) 260 { 261 int r; 262 263 if ((r = ssh_packet_process_read(ssh, connection_in)) == 0) 264 return 0; /* success */ 265 if (r == SSH_ERR_SYSTEM_ERROR) { 266 if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) 267 return 0; 268 if (errno == EPIPE) { 269 logit("Connection closed by %.100s port %d", 270 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 271 return -1; 272 } 273 logit("Read error from remote host %s port %d: %s", 274 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), 275 strerror(errno)); 276 cleanup_exit(255); 277 } 278 return -1; 279 } 280 281 /* 282 * Sends data from internal buffers to client program stdin. 283 */ 284 static void 285 process_output(struct ssh *ssh, int connection_out) 286 { 287 int r; 288 289 /* Send any buffered packet data to the client. */ 290 if ((r = ssh_packet_write_poll(ssh)) != 0) { 291 sshpkt_fatal(ssh, r, "%s: ssh_packet_write_poll", 292 __func__); 293 } 294 } 295 296 static void 297 process_buffered_input_packets(struct ssh *ssh) 298 { 299 ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, NULL); 300 } 301 302 static void 303 collect_children(struct ssh *ssh) 304 { 305 pid_t pid; 306 int status; 307 308 if (child_terminated) { 309 debug("Received SIGCHLD."); 310 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 311 (pid == -1 && errno == EINTR)) 312 if (pid > 0) 313 session_close_by_pid(ssh, pid, status); 314 child_terminated = 0; 315 } 316 } 317 318 void 319 server_loop2(struct ssh *ssh, Authctxt *authctxt) 320 { 321 struct pollfd *pfd = NULL; 322 u_int npfd_alloc = 0, npfd_active = 0; 323 int r, conn_in_ready, conn_out_ready; 324 u_int connection_in, connection_out; 325 sigset_t bsigset, osigset; 326 327 debug("Entering interactive session for SSH2."); 328 329 if (sigemptyset(&bsigset) == -1 || sigaddset(&bsigset, SIGCHLD) == -1) 330 error_f("bsigset setup: %s", strerror(errno)); 331 ssh_signal(SIGCHLD, sigchld_handler); 332 child_terminated = 0; 333 connection_in = ssh_packet_get_connection_in(ssh); 334 connection_out = ssh_packet_get_connection_out(ssh); 335 336 server_init_dispatch(ssh); 337 338 for (;;) { 339 process_buffered_input_packets(ssh); 340 341 if (!ssh_packet_is_rekeying(ssh) && 342 ssh_packet_not_very_much_data_to_write(ssh)) 343 channel_output_poll(ssh); 344 345 /* 346 * Block SIGCHLD while we check for dead children, then pass 347 * the old signal mask through to ppoll() so that it'll wake 348 * up immediately if a child exits after we've called waitpid(). 349 */ 350 if (sigprocmask(SIG_BLOCK, &bsigset, &osigset) == -1) 351 error_f("bsigset sigprocmask: %s", strerror(errno)); 352 collect_children(ssh); 353 wait_until_can_do_something(ssh, connection_in, connection_out, 354 &pfd, &npfd_alloc, &npfd_active, &osigset, 355 &conn_in_ready, &conn_out_ready); 356 if (sigprocmask(SIG_SETMASK, &osigset, NULL) == -1) 357 error_f("osigset sigprocmask: %s", strerror(errno)); 358 359 channel_after_poll(ssh, pfd, npfd_active); 360 if (conn_in_ready && 361 process_input(ssh, connection_in) < 0) 362 break; 363 /* A timeout may have triggered rekeying */ 364 if ((r = ssh_packet_check_rekey(ssh)) != 0) 365 fatal_fr(r, "cannot start rekeying"); 366 if (conn_out_ready) 367 process_output(ssh, connection_out); 368 } 369 collect_children(ssh); 370 free(pfd); 371 372 /* free all channels, no more reads and writes */ 373 channel_free_all(ssh); 374 375 /* free remaining sessions, e.g. remove wtmp entries */ 376 session_destroy_all(ssh, NULL); 377 } 378 379 static int 380 server_input_keep_alive(int type, u_int32_t seq, struct ssh *ssh) 381 { 382 debug("Got %d/%u for keepalive", type, seq); 383 /* 384 * reset timeout, since we got a sane answer from the client. 385 * even if this was generated by something other than 386 * the bogus CHANNEL_REQUEST we send for keepalives. 387 */ 388 ssh_packet_set_alive_timeouts(ssh, 0); 389 return 0; 390 } 391 392 static Channel * 393 server_request_direct_tcpip(struct ssh *ssh, int *reason, const char **errmsg) 394 { 395 Channel *c = NULL; 396 char *target = NULL, *originator = NULL; 397 u_int target_port = 0, originator_port = 0; 398 int r; 399 400 if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 || 401 (r = sshpkt_get_u32(ssh, &target_port)) != 0 || 402 (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 || 403 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 || 404 (r = sshpkt_get_end(ssh)) != 0) 405 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 406 if (target_port > 0xFFFF) { 407 error_f("invalid target port"); 408 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED; 409 goto out; 410 } 411 if (originator_port > 0xFFFF) { 412 error_f("invalid originator port"); 413 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED; 414 goto out; 415 } 416 417 debug_f("originator %s port %u, target %s port %u", 418 originator, originator_port, target, target_port); 419 420 /* XXX fine grained permissions */ 421 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 && 422 auth_opts->permit_port_forwarding_flag && 423 !options.disable_forwarding) { 424 c = channel_connect_to_port(ssh, target, target_port, 425 "direct-tcpip", "direct-tcpip", reason, errmsg); 426 } else { 427 logit("refused local port forward: " 428 "originator %s port %d, target %s port %d", 429 originator, originator_port, target, target_port); 430 if (reason != NULL) 431 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED; 432 } 433 434 out: 435 free(originator); 436 free(target); 437 return c; 438 } 439 440 static Channel * 441 server_request_direct_streamlocal(struct ssh *ssh) 442 { 443 Channel *c = NULL; 444 char *target = NULL, *originator = NULL; 445 u_int originator_port = 0; 446 struct passwd *pw = the_authctxt->pw; 447 int r; 448 449 if (pw == NULL || !the_authctxt->valid) 450 fatal_f("no/invalid user"); 451 452 if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 || 453 (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 || 454 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 || 455 (r = sshpkt_get_end(ssh)) != 0) 456 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 457 if (originator_port > 0xFFFF) { 458 error_f("invalid originator port"); 459 goto out; 460 } 461 462 debug_f("originator %s port %d, target %s", 463 originator, originator_port, target); 464 465 /* XXX fine grained permissions */ 466 if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 && 467 auth_opts->permit_port_forwarding_flag && 468 !options.disable_forwarding) { 469 c = channel_connect_to_path(ssh, target, 470 "direct-streamlocal@openssh.com", "direct-streamlocal"); 471 } else { 472 logit("refused streamlocal port forward: " 473 "originator %s port %d, target %s", 474 originator, originator_port, target); 475 } 476 477 out: 478 free(originator); 479 free(target); 480 return c; 481 } 482 483 static Channel * 484 server_request_tun(struct ssh *ssh) 485 { 486 Channel *c = NULL; 487 u_int mode, tun; 488 int r, sock; 489 char *tmp, *ifname = NULL; 490 491 if ((r = sshpkt_get_u32(ssh, &mode)) != 0) 492 sshpkt_fatal(ssh, r, "%s: parse mode", __func__); 493 switch (mode) { 494 case SSH_TUNMODE_POINTOPOINT: 495 case SSH_TUNMODE_ETHERNET: 496 break; 497 default: 498 ssh_packet_send_debug(ssh, "Unsupported tunnel device mode."); 499 return NULL; 500 } 501 if ((options.permit_tun & mode) == 0) { 502 ssh_packet_send_debug(ssh, "Server has rejected tunnel device " 503 "forwarding"); 504 return NULL; 505 } 506 507 if ((r = sshpkt_get_u32(ssh, &tun)) != 0) 508 sshpkt_fatal(ssh, r, "%s: parse device", __func__); 509 if (tun > INT_MAX) { 510 debug_f("invalid tun"); 511 goto done; 512 } 513 if (auth_opts->force_tun_device != -1) { 514 if (tun != SSH_TUNID_ANY && 515 auth_opts->force_tun_device != (int)tun) 516 goto done; 517 tun = auth_opts->force_tun_device; 518 } 519 sock = tun_open(tun, mode, &ifname); 520 if (sock < 0) 521 goto done; 522 debug("Tunnel forwarding using interface %s", ifname); 523 524 c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1, 525 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1); 526 c->datagram = 1; 527 #if defined(SSH_TUN_FILTER) 528 if (mode == SSH_TUNMODE_POINTOPOINT) 529 channel_register_filter(ssh, c->self, sys_tun_infilter, 530 sys_tun_outfilter, NULL, NULL); 531 #endif 532 533 /* 534 * Update the list of names exposed to the session 535 * XXX remove these if the tunnels are closed (won't matter 536 * much if they are already in the environment though) 537 */ 538 tmp = tun_fwd_ifnames; 539 xasprintf(&tun_fwd_ifnames, "%s%s%s", 540 tun_fwd_ifnames == NULL ? "" : tun_fwd_ifnames, 541 tun_fwd_ifnames == NULL ? "" : ",", 542 ifname); 543 free(tmp); 544 free(ifname); 545 546 done: 547 if (c == NULL) 548 ssh_packet_send_debug(ssh, "Failed to open the tunnel device."); 549 return c; 550 } 551 552 static Channel * 553 server_request_session(struct ssh *ssh) 554 { 555 Channel *c; 556 int r; 557 558 debug("input_session_request"); 559 if ((r = sshpkt_get_end(ssh)) != 0) 560 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 561 562 if (no_more_sessions) { 563 ssh_packet_disconnect(ssh, "Possible attack: attempt to open a " 564 "session after additional sessions disabled"); 565 } 566 567 /* 568 * A server session has no fd to read or write until a 569 * CHANNEL_REQUEST for a shell is made, so we set the type to 570 * SSH_CHANNEL_LARVAL. Additionally, a callback for handling all 571 * CHANNEL_REQUEST messages is registered. 572 */ 573 c = channel_new(ssh, "session", SSH_CHANNEL_LARVAL, 574 -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT, 575 0, "server-session", 1); 576 if (session_open(the_authctxt, c->self) != 1) { 577 debug("session open failed, free channel %d", c->self); 578 channel_free(ssh, c); 579 return NULL; 580 } 581 channel_register_cleanup(ssh, c->self, session_close_by_channel, 0); 582 return c; 583 } 584 585 static int 586 server_input_channel_open(int type, u_int32_t seq, struct ssh *ssh) 587 { 588 Channel *c = NULL; 589 char *ctype = NULL; 590 const char *errmsg = NULL; 591 int r, reason = SSH2_OPEN_CONNECT_FAILED; 592 u_int rchan = 0, rmaxpack = 0, rwindow = 0; 593 594 if ((r = sshpkt_get_cstring(ssh, &ctype, NULL)) != 0 || 595 (r = sshpkt_get_u32(ssh, &rchan)) != 0 || 596 (r = sshpkt_get_u32(ssh, &rwindow)) != 0 || 597 (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0) 598 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 599 debug_f("ctype %s rchan %u win %u max %u", 600 ctype, rchan, rwindow, rmaxpack); 601 602 if (strcmp(ctype, "session") == 0) { 603 c = server_request_session(ssh); 604 } else if (strcmp(ctype, "direct-tcpip") == 0) { 605 c = server_request_direct_tcpip(ssh, &reason, &errmsg); 606 } else if (strcmp(ctype, "direct-streamlocal@openssh.com") == 0) { 607 c = server_request_direct_streamlocal(ssh); 608 } else if (strcmp(ctype, "tun@openssh.com") == 0) { 609 c = server_request_tun(ssh); 610 } 611 if (c != NULL) { 612 debug_f("confirm %s", ctype); 613 c->remote_id = rchan; 614 c->have_remote_id = 1; 615 c->remote_window = rwindow; 616 c->remote_maxpacket = rmaxpack; 617 if (c->type != SSH_CHANNEL_CONNECTING) { 618 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 || 619 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 || 620 (r = sshpkt_put_u32(ssh, c->self)) != 0 || 621 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 || 622 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 || 623 (r = sshpkt_send(ssh)) != 0) { 624 sshpkt_fatal(ssh, r, 625 "%s: send open confirm", __func__); 626 } 627 } 628 } else { 629 debug_f("failure %s", ctype); 630 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 || 631 (r = sshpkt_put_u32(ssh, rchan)) != 0 || 632 (r = sshpkt_put_u32(ssh, reason)) != 0 || 633 (r = sshpkt_put_cstring(ssh, errmsg ? errmsg : "open failed")) != 0 || 634 (r = sshpkt_put_cstring(ssh, "")) != 0 || 635 (r = sshpkt_send(ssh)) != 0) { 636 sshpkt_fatal(ssh, r, 637 "%s: send open failure", __func__); 638 } 639 } 640 free(ctype); 641 return 0; 642 } 643 644 static int 645 server_input_hostkeys_prove(struct ssh *ssh, struct sshbuf **respp) 646 { 647 struct sshbuf *resp = NULL; 648 struct sshbuf *sigbuf = NULL; 649 struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL; 650 int r, ndx, success = 0; 651 const u_char *blob; 652 const char *sigalg, *kex_rsa_sigalg = NULL; 653 u_char *sig = 0; 654 size_t blen, slen; 655 656 if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL) 657 fatal_f("sshbuf_new"); 658 if (sshkey_type_plain(sshkey_type_from_name( 659 ssh->kex->hostkey_alg)) == KEY_RSA) 660 kex_rsa_sigalg = ssh->kex->hostkey_alg; 661 while (ssh_packet_remaining(ssh) > 0) { 662 sshkey_free(key); 663 key = NULL; 664 if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 || 665 (r = sshkey_from_blob(blob, blen, &key)) != 0) { 666 error_fr(r, "parse key"); 667 goto out; 668 } 669 /* 670 * Better check that this is actually one of our hostkeys 671 * before attempting to sign anything with it. 672 */ 673 if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) { 674 error_f("unknown host %s key", sshkey_type(key)); 675 goto out; 676 } 677 /* 678 * XXX refactor: make kex->sign just use an index rather 679 * than passing in public and private keys 680 */ 681 if ((key_prv = get_hostkey_by_index(ndx)) == NULL && 682 (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) { 683 error_f("can't retrieve hostkey %d", ndx); 684 goto out; 685 } 686 sshbuf_reset(sigbuf); 687 free(sig); 688 sig = NULL; 689 /* 690 * For RSA keys, prefer to use the signature type negotiated 691 * during KEX to the default (SHA1). 692 */ 693 sigalg = NULL; 694 if (sshkey_type_plain(key->type) == KEY_RSA) { 695 if (kex_rsa_sigalg != NULL) 696 sigalg = kex_rsa_sigalg; 697 else if (ssh->kex->flags & KEX_RSA_SHA2_512_SUPPORTED) 698 sigalg = "rsa-sha2-512"; 699 else if (ssh->kex->flags & KEX_RSA_SHA2_256_SUPPORTED) 700 sigalg = "rsa-sha2-256"; 701 } 702 debug3_f("sign %s key (index %d) using sigalg %s", 703 sshkey_type(key), ndx, sigalg == NULL ? "default" : sigalg); 704 if ((r = sshbuf_put_cstring(sigbuf, 705 "hostkeys-prove-00@openssh.com")) != 0 || 706 (r = sshbuf_put_stringb(sigbuf, 707 ssh->kex->session_id)) != 0 || 708 (r = sshkey_puts(key, sigbuf)) != 0 || 709 (r = ssh->kex->sign(ssh, key_prv, key_pub, &sig, &slen, 710 sshbuf_ptr(sigbuf), sshbuf_len(sigbuf), sigalg)) != 0 || 711 (r = sshbuf_put_string(resp, sig, slen)) != 0) { 712 error_fr(r, "assemble signature"); 713 goto out; 714 } 715 } 716 /* Success */ 717 *respp = resp; 718 resp = NULL; /* don't free it */ 719 success = 1; 720 out: 721 free(sig); 722 sshbuf_free(resp); 723 sshbuf_free(sigbuf); 724 sshkey_free(key); 725 return success; 726 } 727 728 static int 729 server_input_global_request(int type, u_int32_t seq, struct ssh *ssh) 730 { 731 char *rtype = NULL; 732 u_char want_reply = 0; 733 int r, success = 0, allocated_listen_port = 0; 734 u_int port = 0; 735 struct sshbuf *resp = NULL; 736 struct passwd *pw = the_authctxt->pw; 737 struct Forward fwd; 738 739 memset(&fwd, 0, sizeof(fwd)); 740 if (pw == NULL || !the_authctxt->valid) 741 fatal_f("no/invalid user"); 742 743 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 || 744 (r = sshpkt_get_u8(ssh, &want_reply)) != 0) 745 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 746 debug_f("rtype %s want_reply %d", rtype, want_reply); 747 748 /* -R style forwarding */ 749 if (strcmp(rtype, "tcpip-forward") == 0) { 750 if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 || 751 (r = sshpkt_get_u32(ssh, &port)) != 0) 752 sshpkt_fatal(ssh, r, "%s: parse tcpip-forward", __func__); 753 debug_f("tcpip-forward listen %s port %u", 754 fwd.listen_host, port); 755 if (port <= INT_MAX) 756 fwd.listen_port = (int)port; 757 /* check permissions */ 758 if (port > INT_MAX || 759 (options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 || 760 !auth_opts->permit_port_forwarding_flag || 761 options.disable_forwarding || 762 (!want_reply && fwd.listen_port == 0)) { 763 success = 0; 764 ssh_packet_send_debug(ssh, "Server has disabled port forwarding."); 765 } else { 766 /* Start listening on the port */ 767 success = channel_setup_remote_fwd_listener(ssh, &fwd, 768 &allocated_listen_port, &options.fwd_opts); 769 } 770 if ((resp = sshbuf_new()) == NULL) 771 fatal_f("sshbuf_new"); 772 if (allocated_listen_port != 0 && 773 (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0) 774 fatal_fr(r, "sshbuf_put_u32"); 775 } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) { 776 if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 || 777 (r = sshpkt_get_u32(ssh, &port)) != 0) 778 sshpkt_fatal(ssh, r, "%s: parse cancel-tcpip-forward", __func__); 779 780 debug_f("cancel-tcpip-forward addr %s port %d", 781 fwd.listen_host, port); 782 if (port <= INT_MAX) { 783 fwd.listen_port = (int)port; 784 success = channel_cancel_rport_listener(ssh, &fwd); 785 } 786 } else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) { 787 if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0) 788 sshpkt_fatal(ssh, r, "%s: parse streamlocal-forward@openssh.com", __func__); 789 debug_f("streamlocal-forward listen path %s", 790 fwd.listen_path); 791 792 /* check permissions */ 793 if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0 794 || !auth_opts->permit_port_forwarding_flag || 795 options.disable_forwarding) { 796 success = 0; 797 ssh_packet_send_debug(ssh, "Server has disabled " 798 "streamlocal forwarding."); 799 } else { 800 /* Start listening on the socket */ 801 success = channel_setup_remote_fwd_listener(ssh, 802 &fwd, NULL, &options.fwd_opts); 803 } 804 } else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) { 805 if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0) 806 sshpkt_fatal(ssh, r, "%s: parse cancel-streamlocal-forward@openssh.com", __func__); 807 debug_f("cancel-streamlocal-forward path %s", 808 fwd.listen_path); 809 810 success = channel_cancel_rport_listener(ssh, &fwd); 811 } else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) { 812 no_more_sessions = 1; 813 success = 1; 814 } else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) { 815 success = server_input_hostkeys_prove(ssh, &resp); 816 } 817 /* XXX sshpkt_get_end() */ 818 if (want_reply) { 819 if ((r = sshpkt_start(ssh, success ? 820 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE)) != 0 || 821 (success && resp != NULL && (r = sshpkt_putb(ssh, resp)) != 0) || 822 (r = sshpkt_send(ssh)) != 0 || 823 (r = ssh_packet_write_wait(ssh)) != 0) 824 sshpkt_fatal(ssh, r, "%s: send reply", __func__); 825 } 826 free(fwd.listen_host); 827 free(fwd.listen_path); 828 free(rtype); 829 sshbuf_free(resp); 830 return 0; 831 } 832 833 static int 834 server_input_channel_req(int type, u_int32_t seq, struct ssh *ssh) 835 { 836 Channel *c; 837 int r, success = 0; 838 char *rtype = NULL; 839 u_char want_reply = 0; 840 u_int id = 0; 841 842 if ((r = sshpkt_get_u32(ssh, &id)) != 0 || 843 (r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 || 844 (r = sshpkt_get_u8(ssh, &want_reply)) != 0) 845 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 846 847 debug("server_input_channel_req: channel %u request %s reply %d", 848 id, rtype, want_reply); 849 850 if (id >= INT_MAX || (c = channel_lookup(ssh, (int)id)) == NULL) { 851 ssh_packet_disconnect(ssh, "%s: unknown channel %d", 852 __func__, id); 853 } 854 if (!strcmp(rtype, "eow@openssh.com")) { 855 if ((r = sshpkt_get_end(ssh)) != 0) 856 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 857 chan_rcvd_eow(ssh, c); 858 } else if ((c->type == SSH_CHANNEL_LARVAL || 859 c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0) 860 success = session_input_channel_req(ssh, c, rtype); 861 if (want_reply && !(c->flags & CHAN_CLOSE_SENT)) { 862 if (!c->have_remote_id) 863 fatal_f("channel %d: no remote_id", c->self); 864 if ((r = sshpkt_start(ssh, success ? 865 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 || 866 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 || 867 (r = sshpkt_send(ssh)) != 0) 868 sshpkt_fatal(ssh, r, "%s: send reply", __func__); 869 } 870 free(rtype); 871 return 0; 872 } 873 874 static void 875 server_init_dispatch(struct ssh *ssh) 876 { 877 debug("server_init_dispatch"); 878 ssh_dispatch_init(ssh, &dispatch_protocol_error); 879 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose); 880 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data); 881 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof); 882 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data); 883 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open); 884 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation); 885 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure); 886 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req); 887 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust); 888 ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request); 889 /* client_alive */ 890 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive); 891 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive); 892 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive); 893 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive); 894 /* rekeying */ 895 ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit); 896 } 897