1 /* $NetBSD: serverloop.c,v 1.32 2022/02/23 19:07:20 christos Exp $ */ 2 /* $OpenBSD: serverloop.c,v 1.231 2022/01/22 00:49:34 djm Exp $ */ 3 /* 4 * Author: Tatu Ylonen <ylo@cs.hut.fi> 5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 6 * All rights reserved 7 * Server main loop for handling the interactive session. 8 * 9 * As far as I am concerned, the code I have written for this software 10 * can be used freely for any purpose. Any derived versions of this 11 * software must be clearly marked as such, and if the derived work is 12 * incompatible with the protocol description in the RFC file, it must be 13 * called by a name other than "ssh" or "Secure Shell". 14 * 15 * SSH2 support by Markus Friedl. 16 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved. 17 * 18 * Redistribution and use in source and binary forms, with or without 19 * modification, are permitted provided that the following conditions 20 * are met: 21 * 1. Redistributions of source code must retain the above copyright 22 * notice, this list of conditions and the following disclaimer. 23 * 2. Redistributions in binary form must reproduce the above copyright 24 * notice, this list of conditions and the following disclaimer in the 25 * documentation and/or other materials provided with the distribution. 26 * 27 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 28 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 29 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 30 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 31 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 36 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 37 */ 38 39 #include "includes.h" 40 __RCSID("$NetBSD: serverloop.c,v 1.32 2022/02/23 19:07:20 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 "compat.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 static u_long stdin_bytes = 0; /* Number of bytes written to stdin. */ 85 static u_long fdout_bytes = 0; /* Number of stdout bytes read from program. */ 86 87 extern ServerOptions options; 88 89 /* XXX */ 90 extern Authctxt *the_authctxt; 91 extern struct sshauthopt *auth_opts; 92 extern int use_privsep; 93 94 static int no_more_sessions = 0; /* Disallow further sessions. */ 95 96 static volatile sig_atomic_t child_terminated = 0; /* The child has terminated. */ 97 98 /* Cleanup on signals (!use_privsep case only) */ 99 static volatile sig_atomic_t received_sigterm = 0; 100 101 /* prototypes */ 102 static void server_init_dispatch(struct ssh *); 103 104 /* requested tunnel forwarding interface(s), shared with session.c */ 105 char *tun_fwd_ifnames = NULL; 106 107 /* returns 1 if bind to specified port by specified user is permitted */ 108 static int 109 bind_permitted(int port, uid_t uid) 110 { 111 if (use_privsep) 112 return 1; /* allow system to decide */ 113 if (port < IPPORT_RESERVED && uid != 0) 114 return 0; 115 return 1; 116 } 117 118 /* 119 * Returns current time in seconds from Jan 1, 1970 with the maximum 120 * available resolution. 121 */ 122 123 static double 124 get_current_time(void) 125 { 126 struct timeval tv; 127 gettimeofday(&tv, NULL); 128 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0; 129 } 130 131 /*ARGSUSED*/ 132 static void 133 sigchld_handler(int sig) 134 { 135 child_terminated = 1; 136 } 137 138 /*ARGSUSED*/ 139 static void 140 sigterm_handler(int sig) 141 { 142 received_sigterm = sig; 143 } 144 145 static void 146 client_alive_check(struct ssh *ssh) 147 { 148 char remote_id[512]; 149 int r, channel_id; 150 151 /* timeout, check to see how many we have had */ 152 if (options.client_alive_count_max > 0 && 153 ssh_packet_inc_alive_timeouts(ssh) > 154 options.client_alive_count_max) { 155 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id)); 156 logit("Timeout, client not responding from %s", remote_id); 157 cleanup_exit(255); 158 } 159 160 /* 161 * send a bogus global/channel request with "wantreply", 162 * we should get back a failure 163 */ 164 if ((channel_id = channel_find_open(ssh)) == -1) { 165 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 166 (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) 167 != 0 || 168 (r = sshpkt_put_u8(ssh, 1)) != 0) /* boolean: want reply */ 169 fatal_fr(r, "compose"); 170 } else { 171 channel_request_start(ssh, channel_id, 172 "keepalive@openssh.com", 1); 173 } 174 if ((r = sshpkt_send(ssh)) != 0) 175 fatal_fr(r, "send"); 176 } 177 178 /* 179 * Sleep in ppoll() until we can do something. 180 * Optionally, a maximum time can be specified for the duration of 181 * the wait (0 = infinite). 182 */ 183 static void 184 wait_until_can_do_something(struct ssh *ssh, 185 int connection_in, int connection_out, struct pollfd **pfdp, 186 u_int *npfd_allocp, u_int *npfd_activep, u_int64_t max_time_ms, 187 sigset_t *sigsetp, int *conn_in_readyp, int *conn_out_readyp) 188 { 189 struct timespec ts, *tsp; 190 int ret; 191 time_t minwait_secs = 0; 192 int client_alive_scheduled = 0; 193 u_int p; 194 /* time we last heard from the client OR sent a keepalive */ 195 static time_t last_client_time; 196 197 *conn_in_readyp = *conn_out_readyp = 0; 198 199 /* Prepare channel poll. First two pollfd entries are reserved */ 200 channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep, 201 2, &minwait_secs); 202 if (*npfd_activep < 2) 203 fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */ 204 205 /* XXX need proper deadline system for rekey/client alive */ 206 if (minwait_secs != 0) 207 max_time_ms = MINIMUM(max_time_ms, (u_int)minwait_secs * 1000); 208 209 /* 210 * if using client_alive, set the max timeout accordingly, 211 * and indicate that this particular timeout was for client 212 * alive by setting the client_alive_scheduled flag. 213 * 214 * this could be randomized somewhat to make traffic 215 * analysis more difficult, but we're not doing it yet. 216 */ 217 if (options.client_alive_interval) { 218 uint64_t keepalive_ms = 219 (uint64_t)options.client_alive_interval * 1000; 220 221 if (max_time_ms == 0 || max_time_ms > keepalive_ms) { 222 max_time_ms = keepalive_ms; 223 client_alive_scheduled = 1; 224 } 225 if (last_client_time == 0) 226 last_client_time = monotime(); 227 } 228 229 #if 0 230 /* wrong: bad condition XXX */ 231 if (channel_not_very_much_buffered_data()) 232 #endif 233 /* Monitor client connection on reserved pollfd entries */ 234 (*pfdp)[0].fd = connection_in; 235 (*pfdp)[0].events = POLLIN; 236 (*pfdp)[1].fd = connection_out; 237 (*pfdp)[1].events = ssh_packet_have_data_to_write(ssh) ? POLLOUT : 0; 238 239 /* 240 * If child has terminated and there is enough buffer space to read 241 * from it, then read as much as is available and exit. 242 */ 243 if (child_terminated && ssh_packet_not_very_much_data_to_write(ssh)) 244 if (max_time_ms == 0 || client_alive_scheduled) 245 max_time_ms = 100; 246 247 if (max_time_ms == 0) 248 tsp = NULL; 249 else { 250 ts.tv_sec = max_time_ms / 1000; 251 ts.tv_nsec = 1000000 * (max_time_ms % 1000); 252 tsp = &ts; 253 } 254 255 /* Wait for something to happen, or the timeout to expire. */ 256 ret = ppoll(*pfdp, *npfd_activep, tsp, sigsetp); 257 258 if (ret == -1) { 259 for (p = 0; p < *npfd_activep; p++) 260 (*pfdp)[p].revents = 0; 261 if (errno != EINTR) 262 fatal_f("ppoll: %.100s", strerror(errno)); 263 return; 264 } 265 266 *conn_in_readyp = (*pfdp)[0].revents != 0; 267 *conn_out_readyp = (*pfdp)[1].revents != 0; 268 269 if (client_alive_scheduled) { 270 time_t now = monotime(); 271 272 /* 273 * If the ppoll timed out, or returned for some other reason 274 * but we haven't heard from the client in time, send keepalive. 275 */ 276 if (ret == 0 || (last_client_time != 0 && last_client_time + 277 options.client_alive_interval <= now)) { 278 client_alive_check(ssh); 279 last_client_time = now; 280 } else if (*conn_in_readyp) 281 last_client_time = now; 282 } 283 } 284 285 /* 286 * Processes input from the client and the program. Input data is stored 287 * in buffers and processed later. 288 */ 289 static int 290 process_input(struct ssh *ssh, int connection_in) 291 { 292 int r; 293 294 if ((r = ssh_packet_process_read(ssh, connection_in)) == 0) 295 return 0; /* success */ 296 if (r == SSH_ERR_SYSTEM_ERROR) { 297 if (errno == EAGAIN || errno == EINTR) 298 return 0; 299 if (errno == EPIPE) { 300 verbose("Connection closed by %.100s port %d", 301 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 302 return -1; 303 } 304 verbose("Read error from remote host %s port %d: %s", 305 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), 306 strerror(errno)); 307 cleanup_exit(254); 308 } 309 return -1; 310 } 311 312 /* 313 * Sends data from internal buffers to client program stdin. 314 */ 315 static void 316 process_output(struct ssh *ssh, int connection_out) 317 { 318 int r; 319 320 /* Send any buffered packet data to the client. */ 321 if ((r = ssh_packet_write_poll(ssh)) < 0) { 322 sshpkt_fatal(ssh, r, "%s: ssh_packet_write_poll", 323 __func__); 324 } 325 } 326 327 static void 328 process_buffered_input_packets(struct ssh *ssh) 329 { 330 ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, NULL); 331 } 332 333 static void 334 collect_children(struct ssh *ssh) 335 { 336 pid_t pid; 337 int status; 338 339 if (child_terminated) { 340 debug("Received SIGCHLD."); 341 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 342 (pid == -1 && errno == EINTR)) 343 if (pid > 0) 344 session_close_by_pid(ssh, pid, status); 345 child_terminated = 0; 346 } 347 } 348 349 void 350 server_loop2(struct ssh *ssh, Authctxt *authctxt) 351 { 352 struct pollfd *pfd = NULL; 353 u_int npfd_alloc = 0, npfd_active = 0; 354 int r, conn_in_ready, conn_out_ready; 355 u_int connection_in, connection_out; 356 u_int64_t rekey_timeout_ms = 0; 357 double start_time, total_time; 358 sigset_t bsigset, osigset; 359 360 debug("Entering interactive session for SSH2."); 361 start_time = get_current_time(); 362 363 if (sigemptyset(&bsigset) == -1 || sigaddset(&bsigset, SIGCHLD) == -1) 364 error_f("bsigset setup: %s", strerror(errno)); 365 ssh_signal(SIGCHLD, sigchld_handler); 366 child_terminated = 0; 367 connection_in = ssh_packet_get_connection_in(ssh); 368 connection_out = ssh_packet_get_connection_out(ssh); 369 370 if (!use_privsep) { 371 ssh_signal(SIGTERM, sigterm_handler); 372 ssh_signal(SIGINT, sigterm_handler); 373 ssh_signal(SIGQUIT, sigterm_handler); 374 } 375 376 server_init_dispatch(ssh); 377 378 for (;;) { 379 process_buffered_input_packets(ssh); 380 381 if (!ssh_packet_is_rekeying(ssh) && 382 ssh_packet_not_very_much_data_to_write(ssh)) 383 channel_output_poll(ssh); 384 if (options.rekey_interval > 0 && 385 !ssh_packet_is_rekeying(ssh)) { 386 rekey_timeout_ms = ssh_packet_get_rekey_timeout(ssh) * 387 1000; 388 } else { 389 rekey_timeout_ms = 0; 390 } 391 392 /* 393 * Block SIGCHLD while we check for dead children, then pass 394 * the old signal mask through to ppoll() so that it'll wake 395 * up immediately if a child exits after we've called waitpid(). 396 */ 397 if (sigprocmask(SIG_BLOCK, &bsigset, &osigset) == -1) 398 error_f("bsigset sigprocmask: %s", strerror(errno)); 399 collect_children(ssh); 400 wait_until_can_do_something(ssh, connection_in, connection_out, 401 &pfd, &npfd_alloc, &npfd_active, rekey_timeout_ms, &osigset, 402 &conn_in_ready, &conn_out_ready); 403 if (sigprocmask(SIG_UNBLOCK, &bsigset, &osigset) == -1) 404 error_f("osigset sigprocmask: %s", strerror(errno)); 405 406 if (received_sigterm) { 407 logit("Exiting on signal %d", (int)received_sigterm); 408 /* Clean up sessions, utmp, etc. */ 409 cleanup_exit(254); 410 } 411 412 if (!ssh_packet_is_rekeying(ssh)) 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