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