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