1 /* $OpenBSD: sshd.c,v 1.617 2025/04/07 08:12:22 dtucker Exp $ */ 2 /* 3 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved. 4 * Copyright (c) 2002 Niels Provos. All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 9 * 1. Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer. 11 * 2. Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * 15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 */ 26 27 #include "includes.h" 28 29 #include <sys/types.h> 30 #include <sys/ioctl.h> 31 #include <sys/mman.h> 32 #include <sys/socket.h> 33 #ifdef HAVE_SYS_STAT_H 34 # include <sys/stat.h> 35 #endif 36 #ifdef HAVE_SYS_TIME_H 37 # include <sys/time.h> 38 #endif 39 #include "openbsd-compat/sys-tree.h" 40 #include "openbsd-compat/sys-queue.h" 41 #include <sys/wait.h> 42 #include <sys/utsname.h> 43 44 #include <errno.h> 45 #include <fcntl.h> 46 #include <netdb.h> 47 #ifdef HAVE_PATHS_H 48 #include <paths.h> 49 #endif 50 #include <grp.h> 51 #ifdef HAVE_POLL_H 52 #include <poll.h> 53 #endif 54 #include <pwd.h> 55 #include <signal.h> 56 #include <stdarg.h> 57 #include <time.h> 58 #include <stdio.h> 59 #include <stdlib.h> 60 #include <string.h> 61 #include <unistd.h> 62 #include <limits.h> 63 64 #ifdef WITH_OPENSSL 65 #include <openssl/evp.h> 66 #include <openssl/rand.h> 67 #include "openbsd-compat/openssl-compat.h" 68 #endif 69 70 #ifdef HAVE_SECUREWARE 71 #include <sys/security.h> 72 #include <prot.h> 73 #endif 74 75 #ifdef __FreeBSD__ 76 #include <resolv.h> 77 #if defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H) 78 #include <gssapi/gssapi.h> 79 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_H) 80 #include <gssapi.h> 81 #endif 82 #endif 83 84 #include "xmalloc.h" 85 #include "ssh.h" 86 #include "sshpty.h" 87 #include "log.h" 88 #include "sshbuf.h" 89 #include "misc.h" 90 #include "servconf.h" 91 #include "compat.h" 92 #include "digest.h" 93 #include "sshkey.h" 94 #include "authfile.h" 95 #include "pathnames.h" 96 #include "canohost.h" 97 #include "hostfile.h" 98 #include "auth.h" 99 #include "authfd.h" 100 #include "msg.h" 101 #include "version.h" 102 #include "ssherr.h" 103 #include "sk-api.h" 104 #include "addr.h" 105 #include "srclimit.h" 106 #include "atomicio.h" 107 108 #ifdef LIBWRAP 109 #include <tcpd.h> 110 #include <syslog.h> 111 #endif /* LIBWRAP */ 112 113 /* Re-exec fds */ 114 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1) 115 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 2) 116 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 3) 117 118 extern char *__progname; 119 120 /* Server configuration options. */ 121 ServerOptions options; 122 123 /* 124 * Debug mode flag. This can be set on the command line. If debug 125 * mode is enabled, extra debugging output will be sent to the system 126 * log, the daemon will not go to background, and will exit after processing 127 * the first connection. 128 */ 129 int debug_flag = 0; 130 131 /* Saved arguments to main(). */ 132 static char **saved_argv; 133 static int saved_argc; 134 135 /* 136 * The sockets that the server is listening; this is used in the SIGHUP 137 * signal handler. 138 */ 139 #define MAX_LISTEN_SOCKS 16 140 static int listen_socks[MAX_LISTEN_SOCKS]; 141 static int num_listen_socks = 0; 142 143 /* 144 * Any really sensitive data in the application is contained in this 145 * structure. The idea is that this structure could be locked into memory so 146 * that the pages do not get written into swap. However, there are some 147 * problems. The private key contains BIGNUMs, and we do not (in principle) 148 * have access to the internals of them, and locking just the structure is 149 * not very useful. Currently, memory locking is not implemented. 150 */ 151 struct { 152 struct sshkey **host_keys; /* all private host keys */ 153 struct sshkey **host_pubkeys; /* all public host keys */ 154 struct sshkey **host_certificates; /* all public host certificates */ 155 int have_ssh2_key; 156 } sensitive_data; 157 158 /* This is set to true when a signal is received. */ 159 static volatile sig_atomic_t received_siginfo = 0; 160 static volatile sig_atomic_t received_sigchld = 0; 161 static volatile sig_atomic_t received_sighup = 0; 162 static volatile sig_atomic_t received_sigterm = 0; 163 164 /* record remote hostname or ip */ 165 u_int utmp_len = HOST_NAME_MAX+1; 166 167 /* 168 * The early_child/children array below is used for tracking children of the 169 * listening sshd process early in their lifespans, before they have 170 * completed authentication. This tracking is needed for four things: 171 * 172 * 1) Implementing the MaxStartups limit of concurrent unauthenticated 173 * connections. 174 * 2) Avoiding a race condition for SIGHUP processing, where child processes 175 * may have listen_socks open that could collide with main listener process 176 * after it restarts. 177 * 3) Ensuring that rexec'd sshd processes have received their initial state 178 * from the parent listen process before handling SIGHUP. 179 * 4) Tracking and logging unsuccessful exits from the preauth sshd monitor, 180 * including and especially those for LoginGraceTime timeouts. 181 * 182 * Child processes signal that they have completed closure of the listen_socks 183 * and (if applicable) received their rexec state by sending a char over their 184 * sock. 185 * 186 * Child processes signal that authentication has completed by sending a 187 * second char over the socket before closing it, otherwise the listener will 188 * continue tracking the child (and using up a MaxStartups slot) until the 189 * preauth subprocess exits, whereupon the listener will log its exit status. 190 * preauth processes will exit with a status of EXIT_LOGIN_GRACE to indicate 191 * they did not authenticate before the LoginGraceTime alarm fired. 192 */ 193 struct early_child { 194 int pipefd; 195 int early; /* Indicates child closed listener */ 196 char *id; /* human readable connection identifier */ 197 pid_t pid; 198 struct xaddr addr; 199 int have_addr; 200 int status, have_status; 201 struct sshbuf *config; 202 struct sshbuf *keys; 203 }; 204 static struct early_child *children; 205 static int children_active; 206 207 /* sshd_config buffer */ 208 struct sshbuf *cfg; 209 struct sshbuf *config; /* packed */ 210 211 /* Included files from the configuration file */ 212 struct include_list includes = TAILQ_HEAD_INITIALIZER(includes); 213 214 /* message to be displayed after login */ 215 struct sshbuf *loginmsg; 216 217 /* Unprivileged user */ 218 struct passwd *privsep_pw = NULL; 219 220 static char *listener_proctitle; 221 222 /* 223 * Close all listening sockets 224 */ 225 static void 226 close_listen_socks(void) 227 { 228 int i; 229 230 for (i = 0; i < num_listen_socks; i++) 231 close(listen_socks[i]); 232 num_listen_socks = 0; 233 } 234 235 /* Allocate and initialise the children array */ 236 static void 237 child_alloc(void) 238 { 239 int i; 240 241 children = xcalloc(options.max_startups, sizeof(*children)); 242 for (i = 0; i < options.max_startups; i++) { 243 children[i].pipefd = -1; 244 children[i].pid = -1; 245 } 246 } 247 248 /* Register a new connection in the children array; child pid comes later */ 249 static struct early_child * 250 child_register(int pipefd, int sockfd) 251 { 252 int i, lport, rport; 253 char *laddr = NULL, *raddr = NULL; 254 struct early_child *child = NULL; 255 struct sockaddr_storage addr; 256 socklen_t addrlen = sizeof(addr); 257 struct sockaddr *sa = (struct sockaddr *)&addr; 258 259 for (i = 0; i < options.max_startups; i++) { 260 if (children[i].pipefd != -1 || 261 children[i].config != NULL || 262 children[i].keys != NULL || 263 children[i].pid > 0) 264 continue; 265 child = &(children[i]); 266 break; 267 } 268 if (child == NULL) { 269 fatal_f("error: accepted connection when all %d child " 270 " slots full", options.max_startups); 271 } 272 child->pipefd = pipefd; 273 child->early = 1; 274 if ((child->config = sshbuf_fromb(config)) == NULL) 275 fatal_f("sshbuf_fromb failed"); 276 /* record peer address, if available */ 277 if (getpeername(sockfd, sa, &addrlen) == 0 && 278 addr_sa_to_xaddr(sa, addrlen, &child->addr) == 0) 279 child->have_addr = 1; 280 /* format peer address string for logs */ 281 if ((lport = get_local_port(sockfd)) == 0 || 282 (rport = get_peer_port(sockfd)) == 0) { 283 /* Not a TCP socket */ 284 raddr = get_peer_ipaddr(sockfd); 285 xasprintf(&child->id, "connection from %s", raddr); 286 } else { 287 laddr = get_local_ipaddr(sockfd); 288 raddr = get_peer_ipaddr(sockfd); 289 xasprintf(&child->id, "connection from %s to %s", raddr, laddr); 290 } 291 free(laddr); 292 free(raddr); 293 if (++children_active > options.max_startups) 294 fatal_f("internal error: more children than max_startups"); 295 296 return child; 297 } 298 299 /* 300 * Finally free a child entry. Don't call this directly. 301 */ 302 static void 303 child_finish(struct early_child *child) 304 { 305 if (children_active == 0) 306 fatal_f("internal error: children_active underflow"); 307 if (child->pipefd != -1) 308 close(child->pipefd); 309 sshbuf_free(child->config); 310 sshbuf_free(child->keys); 311 free(child->id); 312 memset(child, '\0', sizeof(*child)); 313 child->pipefd = -1; 314 child->pid = -1; 315 children_active--; 316 } 317 318 /* 319 * Close a child's pipe. This will not stop tracking the child immediately 320 * (it will still be tracked for waitpid()) unless force_final is set, or 321 * child has already exited. 322 */ 323 static void 324 child_close(struct early_child *child, int force_final, int quiet) 325 { 326 if (!quiet) 327 debug_f("enter%s", force_final ? " (forcing)" : ""); 328 if (child->pipefd != -1) { 329 close(child->pipefd); 330 child->pipefd = -1; 331 } 332 if (child->pid == -1 || force_final) 333 child_finish(child); 334 } 335 336 /* Record a child exit. Safe to call from signal handlers */ 337 static void 338 child_exit(pid_t pid, int status) 339 { 340 int i; 341 342 if (children == NULL || pid <= 0) 343 return; 344 for (i = 0; i < options.max_startups; i++) { 345 if (children[i].pid == pid) { 346 children[i].have_status = 1; 347 children[i].status = status; 348 break; 349 } 350 } 351 } 352 353 /* 354 * Reap a child entry that has exited, as previously flagged 355 * using child_exit(). 356 * Handles logging of exit condition and will finalise the child if its pipe 357 * had already been closed. 358 */ 359 static void 360 child_reap(struct early_child *child) 361 { 362 LogLevel level = SYSLOG_LEVEL_DEBUG1; 363 int was_crash, penalty_type = SRCLIMIT_PENALTY_NONE; 364 const char *child_status; 365 366 if (child->config) 367 child_status = " (sending config)"; 368 else if (child->keys) 369 child_status = " (sending keys)"; 370 else if (child->early) 371 child_status = " (early)"; 372 else 373 child_status = ""; 374 375 /* Log exit information */ 376 if (WIFSIGNALED(child->status)) { 377 /* 378 * Increase logging for signals potentially associated 379 * with serious conditions. 380 */ 381 if ((was_crash = signal_is_crash(WTERMSIG(child->status)))) 382 level = SYSLOG_LEVEL_ERROR; 383 do_log2(level, "session process %ld for %s killed by " 384 "signal %d%s", (long)child->pid, child->id, 385 WTERMSIG(child->status), child_status); 386 if (was_crash) 387 penalty_type = SRCLIMIT_PENALTY_CRASH; 388 } else if (!WIFEXITED(child->status)) { 389 penalty_type = SRCLIMIT_PENALTY_CRASH; 390 error("session process %ld for %s terminated abnormally, " 391 "status=0x%x%s", (long)child->pid, child->id, child->status, 392 child_status); 393 } else { 394 /* Normal exit. We care about the status */ 395 switch (WEXITSTATUS(child->status)) { 396 case 0: 397 debug3_f("preauth child %ld for %s completed " 398 "normally%s", (long)child->pid, child->id, 399 child_status); 400 break; 401 case EXIT_LOGIN_GRACE: 402 penalty_type = SRCLIMIT_PENALTY_GRACE_EXCEEDED; 403 logit("Timeout before authentication for %s, " 404 "pid = %ld%s", child->id, (long)child->pid, 405 child_status); 406 break; 407 case EXIT_CHILD_CRASH: 408 penalty_type = SRCLIMIT_PENALTY_CRASH; 409 logit("Session process %ld unpriv child crash for %s%s", 410 (long)child->pid, child->id, child_status); 411 break; 412 case EXIT_AUTH_ATTEMPTED: 413 penalty_type = SRCLIMIT_PENALTY_AUTHFAIL; 414 debug_f("preauth child %ld for %s exited " 415 "after unsuccessful auth attempt%s", 416 (long)child->pid, child->id, child_status); 417 break; 418 case EXIT_CONFIG_REFUSED: 419 penalty_type = SRCLIMIT_PENALTY_REFUSECONNECTION; 420 debug_f("preauth child %ld for %s prohibited by" 421 "RefuseConnection%s", 422 (long)child->pid, child->id, child_status); 423 break; 424 default: 425 penalty_type = SRCLIMIT_PENALTY_NOAUTH; 426 debug_f("preauth child %ld for %s exited " 427 "with status %d%s", (long)child->pid, child->id, 428 WEXITSTATUS(child->status), child_status); 429 break; 430 } 431 } 432 433 if (child->have_addr) 434 srclimit_penalise(&child->addr, penalty_type); 435 436 child->pid = -1; 437 child->have_status = 0; 438 if (child->pipefd == -1) 439 child_finish(child); 440 } 441 442 /* Reap all children that have exited; called after SIGCHLD */ 443 static void 444 child_reap_all_exited(void) 445 { 446 int i; 447 pid_t pid; 448 int status; 449 450 if (children == NULL) 451 return; 452 453 for (;;) { 454 if ((pid = waitpid(-1, &status, WNOHANG)) == 0) 455 break; 456 else if (pid == -1) { 457 if (errno == EINTR || errno == EAGAIN) 458 continue; 459 if (errno != ECHILD) 460 error_f("waitpid: %s", strerror(errno)); 461 break; 462 } 463 child_exit(pid, status); 464 } 465 466 for (i = 0; i < options.max_startups; i++) { 467 if (!children[i].have_status) 468 continue; 469 child_reap(&(children[i])); 470 } 471 } 472 473 static void 474 close_startup_pipes(void) 475 { 476 int i; 477 478 if (children == NULL) 479 return; 480 for (i = 0; i < options.max_startups; i++) { 481 if (children[i].pipefd != -1) 482 child_close(&(children[i]), 1, 1); 483 } 484 } 485 486 /* Called after SIGINFO */ 487 static void 488 show_info(void) 489 { 490 int i; 491 const char *child_status; 492 493 /* XXX print listening sockets here too */ 494 if (children == NULL) 495 return; 496 logit("%d active startups", children_active); 497 for (i = 0; i < options.max_startups; i++) { 498 if (children[i].pipefd == -1 && children[i].pid <= 0) 499 continue; 500 if (children[i].config) 501 child_status = " (sending config)"; 502 else if (children[i].keys) 503 child_status = " (sending keys)"; 504 else if (children[i].early) 505 child_status = " (early)"; 506 else 507 child_status = ""; 508 logit("child %d: fd=%d pid=%ld %s%s", i, children[i].pipefd, 509 (long)children[i].pid, children[i].id, child_status); 510 } 511 srclimit_penalty_info(); 512 } 513 514 /* 515 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP; 516 * the effect is to reread the configuration file (and to regenerate 517 * the server key). 518 */ 519 520 static void 521 sighup_handler(int sig) 522 { 523 received_sighup = 1; 524 } 525 526 /* 527 * Called from the main program after receiving SIGHUP. 528 * Restarts the server. 529 */ 530 static void 531 sighup_restart(void) 532 { 533 logit("Received SIGHUP; restarting."); 534 if (options.pid_file != NULL) 535 unlink(options.pid_file); 536 platform_pre_restart(); 537 close_listen_socks(); 538 close_startup_pipes(); 539 ssh_signal(SIGHUP, SIG_IGN); /* will be restored after exec */ 540 execv(saved_argv[0], saved_argv); 541 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], 542 strerror(errno)); 543 exit(1); 544 } 545 546 /* 547 * Generic signal handler for terminating signals in the master daemon. 548 */ 549 static void 550 sigterm_handler(int sig) 551 { 552 received_sigterm = sig; 553 } 554 555 #ifdef SIGINFO 556 static void 557 siginfo_handler(int sig) 558 { 559 received_siginfo = 1; 560 } 561 #endif 562 563 static void 564 main_sigchld_handler(int sig) 565 { 566 received_sigchld = 1; 567 } 568 569 /* 570 * returns 1 if connection should be dropped, 0 otherwise. 571 * dropping starts at connection #max_startups_begin with a probability 572 * of (max_startups_rate/100). the probability increases linearly until 573 * all connections are dropped for startups > max_startups 574 */ 575 static int 576 should_drop_connection(int startups) 577 { 578 int p, r; 579 580 if (startups < options.max_startups_begin) 581 return 0; 582 if (startups >= options.max_startups) 583 return 1; 584 if (options.max_startups_rate == 100) 585 return 1; 586 587 p = 100 - options.max_startups_rate; 588 p *= startups - options.max_startups_begin; 589 p /= options.max_startups - options.max_startups_begin; 590 p += options.max_startups_rate; 591 r = arc4random_uniform(100); 592 593 debug_f("p %d, r %d", p, r); 594 return (r < p) ? 1 : 0; 595 } 596 597 /* 598 * Check whether connection should be accepted by MaxStartups or for penalty. 599 * Returns 0 if the connection is accepted. If the connection is refused, 600 * returns 1 and attempts to send notification to client. 601 * Logs when the MaxStartups condition is entered or exited, and periodically 602 * while in that state. 603 */ 604 static int 605 drop_connection(int sock, int startups, int notify_pipe) 606 { 607 static struct log_ratelimit_ctx ratelimit_maxstartups; 608 static struct log_ratelimit_ctx ratelimit_penalty; 609 static int init_done; 610 char *laddr, *raddr; 611 const char *reason = NULL, *subreason = NULL; 612 const char msg[] = "Not allowed at this time\r\n"; 613 struct log_ratelimit_ctx *rl = NULL; 614 int ratelimited; 615 u_int ndropped; 616 617 if (!init_done) { 618 init_done = 1; 619 log_ratelimit_init(&ratelimit_maxstartups, 4, 60, 20, 5*60); 620 log_ratelimit_init(&ratelimit_penalty, 8, 60, 30, 2*60); 621 } 622 623 /* PerSourcePenalties */ 624 if (!srclimit_penalty_check_allow(sock, &subreason)) { 625 reason = "PerSourcePenalties"; 626 rl = &ratelimit_penalty; 627 } else { 628 /* MaxStartups */ 629 if (!should_drop_connection(startups) && 630 srclimit_check_allow(sock, notify_pipe) == 1) 631 return 0; 632 reason = "Maxstartups"; 633 rl = &ratelimit_maxstartups; 634 } 635 636 laddr = get_local_ipaddr(sock); 637 raddr = get_peer_ipaddr(sock); 638 ratelimited = log_ratelimit(rl, time(NULL), NULL, &ndropped); 639 do_log2(ratelimited ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO, 640 "drop connection #%d from [%s]:%d on [%s]:%d %s", 641 startups, 642 raddr, get_peer_port(sock), 643 laddr, get_local_port(sock), 644 subreason != NULL ? subreason : reason); 645 free(laddr); 646 free(raddr); 647 if (ndropped != 0) { 648 logit("%s logging rate-limited: additional %u connections " 649 "dropped", reason, ndropped); 650 } 651 652 /* best-effort notification to client */ 653 (void)write(sock, msg, sizeof(msg) - 1); 654 return 1; 655 } 656 657 static void 658 usage(void) 659 { 660 if (options.version_addendum != NULL && 661 *options.version_addendum != '\0') 662 fprintf(stderr, "%s %s, %s\n", 663 SSH_RELEASE, 664 options.version_addendum, SSH_OPENSSL_VERSION); 665 else 666 fprintf(stderr, "%s, %s\n", 667 SSH_RELEASE, SSH_OPENSSL_VERSION); 668 fprintf(stderr, 669 "usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n" 670 " [-E log_file] [-f config_file] [-g login_grace_time]\n" 671 " [-h host_key_file] [-o option] [-p port] [-u len]\n" 672 ); 673 exit(1); 674 } 675 676 static struct sshbuf * 677 pack_hostkeys(void) 678 { 679 struct sshbuf *m = NULL, *keybuf = NULL, *hostkeys = NULL; 680 int r; 681 u_int i; 682 size_t len; 683 684 if ((m = sshbuf_new()) == NULL || 685 (keybuf = sshbuf_new()) == NULL || 686 (hostkeys = sshbuf_new()) == NULL) 687 fatal_f("sshbuf_new failed"); 688 689 /* pack hostkeys into a string. Empty key slots get empty strings */ 690 for (i = 0; i < options.num_host_key_files; i++) { 691 /* private key */ 692 sshbuf_reset(keybuf); 693 if (sensitive_data.host_keys[i] != NULL && 694 (r = sshkey_private_serialize(sensitive_data.host_keys[i], 695 keybuf)) != 0) 696 fatal_fr(r, "serialize hostkey private"); 697 if ((r = sshbuf_put_stringb(hostkeys, keybuf)) != 0) 698 fatal_fr(r, "compose hostkey private"); 699 /* public key */ 700 if (sensitive_data.host_pubkeys[i] != NULL) { 701 if ((r = sshkey_puts(sensitive_data.host_pubkeys[i], 702 hostkeys)) != 0) 703 fatal_fr(r, "compose hostkey public"); 704 } else { 705 if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0) 706 fatal_fr(r, "compose hostkey empty public"); 707 } 708 /* cert */ 709 if (sensitive_data.host_certificates[i] != NULL) { 710 if ((r = sshkey_puts( 711 sensitive_data.host_certificates[i], 712 hostkeys)) != 0) 713 fatal_fr(r, "compose host cert"); 714 } else { 715 if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0) 716 fatal_fr(r, "compose host cert empty"); 717 } 718 } 719 720 if ((r = sshbuf_put_u32(m, 0)) != 0 || 721 (r = sshbuf_put_u8(m, 0)) != 0 || 722 (r = sshbuf_put_stringb(m, hostkeys)) != 0) 723 fatal_fr(r, "compose message"); 724 if ((len = sshbuf_len(m)) < 5 || len > 0xffffffff) 725 fatal_f("bad length %zu", len); 726 POKE_U32(sshbuf_mutable_ptr(m), len - 4); 727 728 sshbuf_free(keybuf); 729 sshbuf_free(hostkeys); 730 return m; 731 } 732 733 static struct sshbuf * 734 pack_config(struct sshbuf *conf) 735 { 736 struct sshbuf *m = NULL, *inc = NULL; 737 struct include_item *item = NULL; 738 size_t len; 739 int r; 740 741 debug3_f("d config len %zu", sshbuf_len(conf)); 742 743 if ((m = sshbuf_new()) == NULL || 744 (inc = sshbuf_new()) == NULL) 745 fatal_f("sshbuf_new failed"); 746 747 /* pack includes into a string */ 748 TAILQ_FOREACH(item, &includes, entry) { 749 if ((r = sshbuf_put_cstring(inc, item->selector)) != 0 || 750 (r = sshbuf_put_cstring(inc, item->filename)) != 0 || 751 (r = sshbuf_put_stringb(inc, item->contents)) != 0) 752 fatal_fr(r, "compose includes"); 753 } 754 755 if ((r = sshbuf_put_u32(m, 0)) != 0 || 756 (r = sshbuf_put_u8(m, 0)) != 0 || 757 (r = sshbuf_put_stringb(m, conf)) != 0 || 758 (r = sshbuf_put_u64(m, options.timing_secret)) != 0 || 759 (r = sshbuf_put_stringb(m, inc)) != 0) 760 fatal_fr(r, "compose config"); 761 762 if ((len = sshbuf_len(m)) < 5 || len > 0xffffffff) 763 fatal_f("bad length %zu", len); 764 POKE_U32(sshbuf_mutable_ptr(m), len - 4); 765 766 sshbuf_free(inc); 767 768 debug3_f("done"); 769 return m; 770 } 771 772 /* 773 * Protocol from reexec master to child: 774 * uint32 size 775 * uint8 type (ignored) 776 * string configuration 777 * uint64 timing_secret 778 * string included_files[] { 779 * string selector 780 * string filename 781 * string contents 782 * } 783 * Second message 784 * uint32 size 785 * uint8 type (ignored) 786 * string host_keys[] { 787 * string private_key 788 * string public_key 789 * string certificate 790 * } 791 */ 792 /* 793 * This function is used only if inet_flag or debug_flag is set, 794 * otherwise the data is sent from the main poll loop. 795 * It sends the config from a child process back to the parent. 796 * The parent will read the config after exec. 797 */ 798 static void 799 send_rexec_state(int fd) 800 { 801 struct sshbuf *keys; 802 u_int mlen; 803 pid_t pid; 804 805 if ((pid = fork()) == -1) 806 fatal_f("fork failed: %s", strerror(errno)); 807 if (pid != 0) 808 return; 809 810 debug3_f("entering fd = %d config len %zu", fd, 811 sshbuf_len(config)); 812 813 mlen = sshbuf_len(config); 814 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(config), mlen) != mlen) 815 error_f("write: %s", strerror(errno)); 816 817 keys = pack_hostkeys(); 818 mlen = sshbuf_len(keys); 819 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(keys), mlen) != mlen) 820 error_f("write: %s", strerror(errno)); 821 822 sshbuf_free(keys); 823 debug3_f("done"); 824 exit(0); 825 } 826 827 /* 828 * Listen for TCP connections 829 */ 830 static void 831 listen_on_addrs(struct listenaddr *la) 832 { 833 int ret, listen_sock; 834 struct addrinfo *ai; 835 char ntop[NI_MAXHOST], strport[NI_MAXSERV]; 836 837 for (ai = la->addrs; ai; ai = ai->ai_next) { 838 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) 839 continue; 840 if (num_listen_socks >= MAX_LISTEN_SOCKS) 841 fatal("Too many listen sockets. " 842 "Enlarge MAX_LISTEN_SOCKS"); 843 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen, 844 ntop, sizeof(ntop), strport, sizeof(strport), 845 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) { 846 error("getnameinfo failed: %.100s", 847 ssh_gai_strerror(ret)); 848 continue; 849 } 850 /* Create socket for listening. */ 851 listen_sock = socket(ai->ai_family, ai->ai_socktype, 852 ai->ai_protocol); 853 if (listen_sock == -1) { 854 /* kernel may not support ipv6 */ 855 verbose("socket: %.100s", strerror(errno)); 856 continue; 857 } 858 if (set_nonblock(listen_sock) == -1) { 859 close(listen_sock); 860 continue; 861 } 862 if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) { 863 verbose("socket: CLOEXEC: %s", strerror(errno)); 864 close(listen_sock); 865 continue; 866 } 867 /* Socket options */ 868 set_reuseaddr(listen_sock); 869 if (la->rdomain != NULL && 870 set_rdomain(listen_sock, la->rdomain) == -1) { 871 close(listen_sock); 872 continue; 873 } 874 875 /* Only communicate in IPv6 over AF_INET6 sockets. */ 876 if (ai->ai_family == AF_INET6) 877 sock_set_v6only(listen_sock); 878 879 debug("Bind to port %s on %s.", strport, ntop); 880 881 /* Bind the socket to the desired port. */ 882 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) { 883 error("Bind to port %s on %s failed: %.200s.", 884 strport, ntop, strerror(errno)); 885 close(listen_sock); 886 continue; 887 } 888 listen_socks[num_listen_socks] = listen_sock; 889 num_listen_socks++; 890 891 /* Start listening on the port. */ 892 if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1) 893 fatal("listen on [%s]:%s: %.100s", 894 ntop, strport, strerror(errno)); 895 logit("Server listening on %s port %s%s%s.", 896 ntop, strport, 897 la->rdomain == NULL ? "" : " rdomain ", 898 la->rdomain == NULL ? "" : la->rdomain); 899 } 900 } 901 902 static void 903 server_listen(void) 904 { 905 u_int i; 906 907 /* Initialise per-source limit tracking. */ 908 srclimit_init(options.max_startups, 909 options.per_source_max_startups, 910 options.per_source_masklen_ipv4, 911 options.per_source_masklen_ipv6, 912 &options.per_source_penalty, 913 options.per_source_penalty_exempt); 914 915 for (i = 0; i < options.num_listen_addrs; i++) { 916 listen_on_addrs(&options.listen_addrs[i]); 917 freeaddrinfo(options.listen_addrs[i].addrs); 918 free(options.listen_addrs[i].rdomain); 919 memset(&options.listen_addrs[i], 0, 920 sizeof(options.listen_addrs[i])); 921 } 922 free(options.listen_addrs); 923 options.listen_addrs = NULL; 924 options.num_listen_addrs = 0; 925 926 if (!num_listen_socks) 927 fatal("Cannot bind any address."); 928 } 929 930 /* 931 * The main TCP accept loop. Note that, for the non-debug case, returns 932 * from this function are in a forked subprocess. 933 */ 934 static void 935 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s, 936 int log_stderr) 937 { 938 struct pollfd *pfd = NULL; 939 int i, ret, npfd, r; 940 int oactive = -1, listening = 0, lameduck = 0; 941 int *startup_pollfd; 942 ssize_t len; 943 const u_char *ptr; 944 char c = 0; 945 struct sockaddr_storage from; 946 struct early_child *child; 947 struct sshbuf *buf; 948 socklen_t fromlen; 949 u_char rnd[256]; 950 sigset_t nsigset, osigset; 951 #ifdef LIBWRAP 952 struct request_info req; 953 954 request_init(&req, RQ_DAEMON, __progname, 0); 955 #endif 956 957 /* pipes connected to unauthenticated child sshd processes */ 958 child_alloc(); 959 startup_pollfd = xcalloc(options.max_startups, sizeof(int)); 960 961 /* 962 * Prepare signal mask that we use to block signals that might set 963 * received_sigterm/hup/chld/info, so that we are guaranteed 964 * to immediately wake up the ppoll if a signal is received after 965 * the flag is checked. 966 */ 967 sigemptyset(&nsigset); 968 sigaddset(&nsigset, SIGHUP); 969 sigaddset(&nsigset, SIGCHLD); 970 #ifdef SIGINFO 971 sigaddset(&nsigset, SIGINFO); 972 #endif 973 sigaddset(&nsigset, SIGTERM); 974 sigaddset(&nsigset, SIGQUIT); 975 976 /* sized for worst-case */ 977 pfd = xcalloc(num_listen_socks + options.max_startups, 978 sizeof(struct pollfd)); 979 980 /* 981 * Stay listening for connections until the system crashes or 982 * the daemon is killed with a signal. 983 */ 984 for (;;) { 985 sigprocmask(SIG_BLOCK, &nsigset, &osigset); 986 if (received_sigterm) { 987 logit("Received signal %d; terminating.", 988 (int) received_sigterm); 989 close_listen_socks(); 990 if (options.pid_file != NULL) 991 unlink(options.pid_file); 992 exit(received_sigterm == SIGTERM ? 0 : 255); 993 } 994 if (received_sigchld) { 995 child_reap_all_exited(); 996 received_sigchld = 0; 997 } 998 if (received_siginfo) { 999 show_info(); 1000 received_siginfo = 0; 1001 } 1002 if (oactive != children_active) { 1003 setproctitle("%s [listener] %d of %d-%d startups", 1004 listener_proctitle, children_active, 1005 options.max_startups_begin, options.max_startups); 1006 oactive = children_active; 1007 } 1008 if (received_sighup) { 1009 if (!lameduck) { 1010 debug("Received SIGHUP; waiting for children"); 1011 close_listen_socks(); 1012 lameduck = 1; 1013 } 1014 if (listening <= 0) { 1015 sigprocmask(SIG_SETMASK, &osigset, NULL); 1016 sighup_restart(); 1017 } 1018 } 1019 1020 for (i = 0; i < num_listen_socks; i++) { 1021 pfd[i].fd = listen_socks[i]; 1022 pfd[i].events = POLLIN; 1023 } 1024 npfd = num_listen_socks; 1025 for (i = 0; i < options.max_startups; i++) { 1026 startup_pollfd[i] = -1; 1027 if (children[i].pipefd != -1) { 1028 pfd[npfd].fd = children[i].pipefd; 1029 pfd[npfd].events = POLLIN; 1030 if (children[i].config != NULL || 1031 children[i].keys != NULL) 1032 pfd[npfd].events |= POLLOUT; 1033 startup_pollfd[i] = npfd++; 1034 } 1035 } 1036 1037 /* Wait until a connection arrives or a child exits. */ 1038 ret = ppoll(pfd, npfd, NULL, &osigset); 1039 if (ret == -1 && errno != EINTR) { 1040 error("ppoll: %.100s", strerror(errno)); 1041 if (errno == EINVAL) 1042 cleanup_exit(1); /* can't recover */ 1043 } 1044 sigprocmask(SIG_SETMASK, &osigset, NULL); 1045 if (ret == -1) 1046 continue; 1047 1048 for (i = 0; i < options.max_startups; i++) { 1049 if (children[i].pipefd == -1 || 1050 startup_pollfd[i] == -1 || 1051 !(pfd[startup_pollfd[i]].revents & POLLOUT)) 1052 continue; 1053 if (children[i].config) 1054 buf = children[i].config; 1055 else if (children[i].keys) 1056 buf = children[i].keys; 1057 else { 1058 error_f("no buffer to send"); 1059 continue; 1060 } 1061 ptr = sshbuf_ptr(buf); 1062 len = sshbuf_len(buf); 1063 ret = write(children[i].pipefd, ptr, len); 1064 if (ret == -1 && (errno == EINTR || errno == EAGAIN)) 1065 continue; 1066 if (ret <= 0) { 1067 if (children[i].early) 1068 listening--; 1069 srclimit_done(children[i].pipefd); 1070 child_close(&(children[i]), 0, 0); 1071 continue; 1072 } 1073 if (ret == len) { 1074 /* finished sending buffer */ 1075 sshbuf_free(buf); 1076 if (children[i].config == buf) { 1077 /* sent config, now send keys */ 1078 children[i].config = NULL; 1079 children[i].keys = pack_hostkeys(); 1080 } else if (children[i].keys == buf) { 1081 /* sent both config and keys */ 1082 children[i].keys = NULL; 1083 } else { 1084 fatal("config buf not set"); 1085 } 1086 1087 } else { 1088 if ((r = sshbuf_consume(buf, ret)) != 0) 1089 fatal_fr(r, "config buf inconsistent"); 1090 } 1091 } 1092 for (i = 0; i < options.max_startups; i++) { 1093 if (children[i].pipefd == -1 || 1094 startup_pollfd[i] == -1 || 1095 !(pfd[startup_pollfd[i]].revents & (POLLIN|POLLHUP))) 1096 continue; 1097 switch (read(children[i].pipefd, &c, sizeof(c))) { 1098 case -1: 1099 if (errno == EINTR || errno == EAGAIN) 1100 continue; 1101 if (errno != EPIPE) { 1102 error_f("startup pipe %d (fd=%d): " 1103 "read %s", i, children[i].pipefd, 1104 strerror(errno)); 1105 } 1106 /* FALLTHROUGH */ 1107 case 0: 1108 /* child exited preauth */ 1109 if (children[i].early) 1110 listening--; 1111 srclimit_done(children[i].pipefd); 1112 child_close(&(children[i]), 0, 0); 1113 break; 1114 case 1: 1115 if (children[i].config) { 1116 error_f("startup pipe %d (fd=%d)" 1117 " early read", i, children[i].pipefd); 1118 if (children[i].early) 1119 listening--; 1120 if (children[i].pid > 0) 1121 kill(children[i].pid, SIGTERM); 1122 srclimit_done(children[i].pipefd); 1123 child_close(&(children[i]), 0, 0); 1124 break; 1125 } 1126 if (children[i].early && c == '\0') { 1127 /* child has finished preliminaries */ 1128 listening--; 1129 children[i].early = 0; 1130 debug2_f("child %lu for %s received " 1131 "config", (long)children[i].pid, 1132 children[i].id); 1133 } else if (!children[i].early && c == '\001') { 1134 /* child has completed auth */ 1135 debug2_f("child %lu for %s auth done", 1136 (long)children[i].pid, 1137 children[i].id); 1138 child_close(&(children[i]), 1, 0); 1139 } else { 1140 error_f("unexpected message 0x%02x " 1141 "child %ld for %s in state %d", 1142 (int)c, (long)children[i].pid, 1143 children[i].id, children[i].early); 1144 } 1145 break; 1146 } 1147 } 1148 for (i = 0; i < num_listen_socks; i++) { 1149 if (!(pfd[i].revents & POLLIN)) 1150 continue; 1151 fromlen = sizeof(from); 1152 *newsock = accept(listen_socks[i], 1153 (struct sockaddr *)&from, &fromlen); 1154 if (*newsock == -1) { 1155 if (errno != EINTR && errno != EWOULDBLOCK && 1156 errno != ECONNABORTED && errno != EAGAIN) 1157 error("accept: %.100s", 1158 strerror(errno)); 1159 if (errno == EMFILE || errno == ENFILE) 1160 usleep(100 * 1000); 1161 continue; 1162 } 1163 #ifdef LIBWRAP 1164 /* Check whether logins are denied from this host. */ 1165 request_set(&req, RQ_FILE, *newsock, 1166 RQ_CLIENT_NAME, "", RQ_CLIENT_ADDR, "", 0); 1167 sock_host(&req); 1168 if (!hosts_access(&req)) { 1169 const struct linger l = { .l_onoff = 1, 1170 .l_linger = 0 }; 1171 1172 (void )setsockopt(*newsock, SOL_SOCKET, 1173 SO_LINGER, &l, sizeof(l)); 1174 (void )close(*newsock); 1175 /* 1176 * Mimic message from libwrap's refuse() as 1177 * precisely as we can afford. The authentic 1178 * message prints the IP address and the 1179 * hostname it resolves to in parentheses. If 1180 * the IP address cannot be resolved to a 1181 * hostname, the IP address will be repeated 1182 * in parentheses. As name resolution in the 1183 * main server loop could stall, and logging 1184 * resolved names adds little or no value to 1185 * incident investigation, this implementation 1186 * only repeats the IP address in parentheses. 1187 * This should resemble librwap's refuse() 1188 * closely enough not to break auditing 1189 * software like sshguard or custom scripts. 1190 */ 1191 syslog(LOG_WARNING, 1192 "refused connect from %s (%s)", 1193 eval_hostaddr(req.client), 1194 eval_hostaddr(req.client)); 1195 debug("Connection refused by tcp wrapper"); 1196 continue; 1197 } 1198 #endif /* LIBWRAP */ 1199 if (unset_nonblock(*newsock) == -1) { 1200 close(*newsock); 1201 continue; 1202 } 1203 if (socketpair(AF_UNIX, 1204 SOCK_STREAM, 0, config_s) == -1) { 1205 error("reexec socketpair: %s", 1206 strerror(errno)); 1207 close(*newsock); 1208 continue; 1209 } 1210 if (drop_connection(*newsock, 1211 children_active, config_s[0])) { 1212 close(*newsock); 1213 close(config_s[0]); 1214 close(config_s[1]); 1215 continue; 1216 } 1217 1218 /* 1219 * Got connection. Fork a child to handle it, unless 1220 * we are in debugging mode. 1221 */ 1222 if (debug_flag) { 1223 /* 1224 * In debugging mode. Close the listening 1225 * socket, and start processing the 1226 * connection without forking. 1227 */ 1228 debug("Server will not fork when running in debugging mode."); 1229 close_listen_socks(); 1230 *sock_in = *newsock; 1231 *sock_out = *newsock; 1232 send_rexec_state(config_s[0]); 1233 close(config_s[0]); 1234 free(pfd); 1235 return; 1236 } 1237 1238 /* 1239 * Normal production daemon. Fork, and have 1240 * the child process the connection. The 1241 * parent continues listening. 1242 */ 1243 platform_pre_fork(); 1244 set_nonblock(config_s[0]); 1245 listening++; 1246 child = child_register(config_s[0], *newsock); 1247 if ((child->pid = fork()) == 0) { 1248 /* 1249 * Child. Close the listening and 1250 * max_startup sockets. Start using 1251 * the accepted socket. Reinitialize 1252 * logging (since our pid has changed). 1253 * We return from this function to handle 1254 * the connection. 1255 */ 1256 platform_post_fork_child(); 1257 close_startup_pipes(); 1258 close_listen_socks(); 1259 *sock_in = *newsock; 1260 *sock_out = *newsock; 1261 log_init(__progname, 1262 options.log_level, 1263 options.log_facility, 1264 log_stderr); 1265 close(config_s[0]); 1266 free(pfd); 1267 return; 1268 } 1269 1270 /* Parent. Stay in the loop. */ 1271 platform_post_fork_parent(child->pid); 1272 if (child->pid == -1) 1273 error("fork: %.100s", strerror(errno)); 1274 else 1275 debug("Forked child %ld.", (long)child->pid); 1276 1277 close(config_s[1]); 1278 close(*newsock); 1279 1280 /* 1281 * Ensure that our random state differs 1282 * from that of the child 1283 */ 1284 arc4random_stir(); 1285 arc4random_buf(rnd, sizeof(rnd)); 1286 #ifdef WITH_OPENSSL 1287 RAND_seed(rnd, sizeof(rnd)); 1288 if ((RAND_bytes((u_char *)rnd, 1)) != 1) 1289 fatal("%s: RAND_bytes failed", __func__); 1290 #endif 1291 explicit_bzero(rnd, sizeof(rnd)); 1292 } 1293 } 1294 } 1295 1296 static void 1297 accumulate_host_timing_secret(struct sshbuf *server_cfg, 1298 struct sshkey *key) 1299 { 1300 static struct ssh_digest_ctx *ctx; 1301 u_char *hash; 1302 size_t len; 1303 struct sshbuf *buf; 1304 int r; 1305 1306 if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL) 1307 fatal_f("ssh_digest_start"); 1308 if (key == NULL) { /* finalize */ 1309 /* add server config in case we are using agent for host keys */ 1310 if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg), 1311 sshbuf_len(server_cfg)) != 0) 1312 fatal_f("ssh_digest_update"); 1313 len = ssh_digest_bytes(SSH_DIGEST_SHA512); 1314 hash = xmalloc(len); 1315 if (ssh_digest_final(ctx, hash, len) != 0) 1316 fatal_f("ssh_digest_final"); 1317 options.timing_secret = PEEK_U64(hash); 1318 freezero(hash, len); 1319 ssh_digest_free(ctx); 1320 ctx = NULL; 1321 return; 1322 } 1323 if ((buf = sshbuf_new()) == NULL) 1324 fatal_f("could not allocate buffer"); 1325 if ((r = sshkey_private_serialize(key, buf)) != 0) 1326 fatal_fr(r, "encode %s key", sshkey_ssh_name(key)); 1327 if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0) 1328 fatal_f("ssh_digest_update"); 1329 sshbuf_reset(buf); 1330 sshbuf_free(buf); 1331 } 1332 1333 static char * 1334 prepare_proctitle(int ac, char **av) 1335 { 1336 char *ret = NULL; 1337 int i; 1338 1339 for (i = 0; i < ac; i++) 1340 xextendf(&ret, " ", "%s", av[i]); 1341 return ret; 1342 } 1343 1344 static void 1345 print_config(struct connection_info *connection_info) 1346 { 1347 connection_info->test = 1; 1348 parse_server_match_config(&options, &includes, connection_info); 1349 dump_config(&options); 1350 exit(0); 1351 } 1352 1353 /* 1354 * Main program for the daemon. 1355 */ 1356 int 1357 main(int ac, char **av) 1358 { 1359 extern char *optarg; 1360 extern int optind; 1361 int log_stderr = 0, inetd_flag = 0, test_flag = 0, no_daemon_flag = 0; 1362 char *config_file_name = _PATH_SERVER_CONFIG_FILE; 1363 int r, opt, do_dump_cfg = 0, keytype, already_daemon, have_agent = 0; 1364 int sock_in = -1, sock_out = -1, newsock = -1, rexec_argc = 0; 1365 int devnull, config_s[2] = { -1 , -1 }, have_connection_info = 0; 1366 int need_chroot = 1; 1367 char *args, *fp, *line, *logfile = NULL, **rexec_argv = NULL; 1368 struct stat sb; 1369 u_int i, j; 1370 mode_t new_umask; 1371 struct sshkey *key; 1372 struct sshkey *pubkey; 1373 struct connection_info connection_info; 1374 struct utsname utsname; 1375 sigset_t sigmask; 1376 1377 memset(&connection_info, 0, sizeof(connection_info)); 1378 #ifdef HAVE_SECUREWARE 1379 (void)set_auth_parameters(ac, av); 1380 #endif 1381 __progname = ssh_get_progname(av[0]); 1382 1383 sigemptyset(&sigmask); 1384 sigprocmask(SIG_SETMASK, &sigmask, NULL); 1385 1386 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */ 1387 saved_argc = ac; 1388 rexec_argc = ac; 1389 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv)); 1390 for (i = 0; (int)i < ac; i++) 1391 saved_argv[i] = xstrdup(av[i]); 1392 saved_argv[i] = NULL; 1393 1394 #ifndef HAVE_SETPROCTITLE 1395 /* Prepare for later setproctitle emulation */ 1396 compat_init_setproctitle(ac, av); 1397 av = saved_argv; 1398 #endif 1399 1400 if (geteuid() == 0 && setgroups(0, NULL) == -1) 1401 debug("setgroups(): %.200s", strerror(errno)); 1402 1403 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 1404 sanitise_stdfd(); 1405 1406 /* Initialize configuration options to their default values. */ 1407 initialize_server_options(&options); 1408 1409 /* Parse command-line arguments. */ 1410 args = argv_assemble(ac, av); /* logged later */ 1411 while ((opt = getopt(ac, av, 1412 "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) { 1413 switch (opt) { 1414 case '4': 1415 options.address_family = AF_INET; 1416 break; 1417 case '6': 1418 options.address_family = AF_INET6; 1419 break; 1420 case 'f': 1421 config_file_name = optarg; 1422 break; 1423 case 'c': 1424 servconf_add_hostcert("[command-line]", 0, 1425 &options, optarg); 1426 break; 1427 case 'd': 1428 if (debug_flag == 0) { 1429 debug_flag = 1; 1430 options.log_level = SYSLOG_LEVEL_DEBUG1; 1431 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) 1432 options.log_level++; 1433 break; 1434 case 'D': 1435 no_daemon_flag = 1; 1436 break; 1437 case 'G': 1438 do_dump_cfg = 1; 1439 break; 1440 case 'E': 1441 logfile = optarg; 1442 /* FALLTHROUGH */ 1443 case 'e': 1444 log_stderr = 1; 1445 break; 1446 case 'i': 1447 inetd_flag = 1; 1448 break; 1449 case 'r': 1450 logit("-r option is deprecated"); 1451 break; 1452 case 'R': 1453 fatal("-R not supported here"); 1454 break; 1455 case 'Q': 1456 /* ignored */ 1457 break; 1458 case 'q': 1459 options.log_level = SYSLOG_LEVEL_QUIET; 1460 break; 1461 case 'b': 1462 /* protocol 1, ignored */ 1463 break; 1464 case 'p': 1465 options.ports_from_cmdline = 1; 1466 if (options.num_ports >= MAX_PORTS) { 1467 fprintf(stderr, "too many ports.\n"); 1468 exit(1); 1469 } 1470 options.ports[options.num_ports++] = a2port(optarg); 1471 if (options.ports[options.num_ports-1] <= 0) { 1472 fprintf(stderr, "Bad port number.\n"); 1473 exit(1); 1474 } 1475 break; 1476 case 'g': 1477 if ((options.login_grace_time = convtime(optarg)) == -1) { 1478 fprintf(stderr, "Invalid login grace time.\n"); 1479 exit(1); 1480 } 1481 break; 1482 case 'k': 1483 /* protocol 1, ignored */ 1484 break; 1485 case 'h': 1486 servconf_add_hostkey("[command-line]", 0, 1487 &options, optarg, 1); 1488 break; 1489 case 't': 1490 test_flag = 1; 1491 break; 1492 case 'T': 1493 test_flag = 2; 1494 break; 1495 case 'C': 1496 if (parse_server_match_testspec(&connection_info, 1497 optarg) == -1) 1498 exit(1); 1499 have_connection_info = 1; 1500 break; 1501 case 'u': 1502 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL); 1503 if (utmp_len > HOST_NAME_MAX+1) { 1504 fprintf(stderr, "Invalid utmp length.\n"); 1505 exit(1); 1506 } 1507 break; 1508 case 'o': 1509 line = xstrdup(optarg); 1510 if (process_server_config_line(&options, line, 1511 "command-line", 0, NULL, NULL, &includes) != 0) 1512 exit(1); 1513 free(line); 1514 break; 1515 case 'V': 1516 fprintf(stderr, "%s, %s\n", 1517 SSH_RELEASE, SSH_OPENSSL_VERSION); 1518 exit(0); 1519 default: 1520 usage(); 1521 break; 1522 } 1523 } 1524 if (!test_flag && !inetd_flag && !do_dump_cfg && !path_absolute(av[0])) 1525 fatal("sshd requires execution with an absolute path"); 1526 1527 closefrom(STDERR_FILENO + 1); 1528 1529 /* Reserve fds we'll need later for reexec things */ 1530 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) 1531 fatal("open %s: %s", _PATH_DEVNULL, strerror(errno)); 1532 while (devnull < REEXEC_MIN_FREE_FD) { 1533 if ((devnull = dup(devnull)) == -1) 1534 fatal("dup %s: %s", _PATH_DEVNULL, strerror(errno)); 1535 } 1536 1537 seed_rng(); 1538 1539 /* If requested, redirect the logs to the specified logfile. */ 1540 if (logfile != NULL) { 1541 char *cp, pid_s[32]; 1542 1543 snprintf(pid_s, sizeof(pid_s), "%ld", (unsigned long)getpid()); 1544 cp = percent_expand(logfile, 1545 "p", pid_s, 1546 "P", "sshd", 1547 (char *)NULL); 1548 log_redirect_stderr_to(cp); 1549 free(cp); 1550 } 1551 1552 /* 1553 * Force logging to stderr until we have loaded the private host 1554 * key (unless started from inetd) 1555 */ 1556 log_init(__progname, 1557 options.log_level == SYSLOG_LEVEL_NOT_SET ? 1558 SYSLOG_LEVEL_INFO : options.log_level, 1559 options.log_facility == SYSLOG_FACILITY_NOT_SET ? 1560 SYSLOG_FACILITY_AUTH : options.log_facility, 1561 log_stderr || !inetd_flag || debug_flag); 1562 1563 /* 1564 * Unset KRB5CCNAME, otherwise the user's session may inherit it from 1565 * root's environment 1566 */ 1567 if (getenv("KRB5CCNAME") != NULL) 1568 (void) unsetenv("KRB5CCNAME"); 1569 1570 sensitive_data.have_ssh2_key = 0; 1571 1572 /* 1573 * If we're not doing an extended test do not silently ignore connection 1574 * test params. 1575 */ 1576 if (test_flag < 2 && have_connection_info) 1577 fatal("Config test connection parameter (-C) provided without " 1578 "test mode (-T)"); 1579 1580 debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION); 1581 if (uname(&utsname) != 0) { 1582 memset(&utsname, 0, sizeof(utsname)); 1583 strlcpy(utsname.sysname, "UNKNOWN", sizeof(utsname.sysname)); 1584 } 1585 debug3("Running on %s %s %s %s", utsname.sysname, utsname.release, 1586 utsname.version, utsname.machine); 1587 debug3("Started with: %s", args); 1588 free(args); 1589 1590 /* Fetch our configuration */ 1591 if ((cfg = sshbuf_new()) == NULL) 1592 fatal("sshbuf_new config failed"); 1593 if (strcasecmp(config_file_name, "none") != 0) 1594 load_server_config(config_file_name, cfg); 1595 1596 parse_server_config(&options, config_file_name, cfg, 1597 &includes, NULL, 0); 1598 1599 /* Fill in default values for those options not explicitly set. */ 1600 fill_default_server_options(&options); 1601 1602 /* Check that options are sensible */ 1603 if (options.authorized_keys_command_user == NULL && 1604 (options.authorized_keys_command != NULL && 1605 strcasecmp(options.authorized_keys_command, "none") != 0)) 1606 fatal("AuthorizedKeysCommand set without " 1607 "AuthorizedKeysCommandUser"); 1608 if (options.authorized_principals_command_user == NULL && 1609 (options.authorized_principals_command != NULL && 1610 strcasecmp(options.authorized_principals_command, "none") != 0)) 1611 fatal("AuthorizedPrincipalsCommand set without " 1612 "AuthorizedPrincipalsCommandUser"); 1613 1614 /* 1615 * Check whether there is any path through configured auth methods. 1616 * Unfortunately it is not possible to verify this generally before 1617 * daemonisation in the presence of Match blocks, but this catches 1618 * and warns for trivial misconfigurations that could break login. 1619 */ 1620 if (options.num_auth_methods != 0) { 1621 for (i = 0; i < options.num_auth_methods; i++) { 1622 if (auth2_methods_valid(options.auth_methods[i], 1623 1) == 0) 1624 break; 1625 } 1626 if (i >= options.num_auth_methods) 1627 fatal("AuthenticationMethods cannot be satisfied by " 1628 "enabled authentication methods"); 1629 } 1630 1631 /* Check that there are no remaining arguments. */ 1632 if (optind < ac) { 1633 fprintf(stderr, "Extra argument %s.\n", av[optind]); 1634 exit(1); 1635 } 1636 1637 if (do_dump_cfg) 1638 print_config(&connection_info); 1639 1640 /* load host keys */ 1641 sensitive_data.host_keys = xcalloc(options.num_host_key_files, 1642 sizeof(struct sshkey *)); 1643 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files, 1644 sizeof(struct sshkey *)); 1645 1646 if (options.host_key_agent) { 1647 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME)) 1648 setenv(SSH_AUTHSOCKET_ENV_NAME, 1649 options.host_key_agent, 1); 1650 if ((r = ssh_get_authentication_socket(NULL)) == 0) 1651 have_agent = 1; 1652 else 1653 error_r(r, "Could not connect to agent \"%s\"", 1654 options.host_key_agent); 1655 } 1656 1657 for (i = 0; i < options.num_host_key_files; i++) { 1658 int ll = options.host_key_file_userprovided[i] ? 1659 SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1; 1660 1661 if (options.host_key_files[i] == NULL) 1662 continue; 1663 if ((r = sshkey_load_private(options.host_key_files[i], "", 1664 &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR) 1665 do_log2_r(r, ll, "Unable to load host key \"%s\"", 1666 options.host_key_files[i]); 1667 if (sshkey_is_sk(key) && 1668 key->sk_flags & SSH_SK_USER_PRESENCE_REQD) { 1669 debug("host key %s requires user presence, ignoring", 1670 options.host_key_files[i]); 1671 key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD; 1672 } 1673 if (r == 0 && key != NULL && 1674 (r = sshkey_shield_private(key)) != 0) { 1675 do_log2_r(r, ll, "Unable to shield host key \"%s\"", 1676 options.host_key_files[i]); 1677 sshkey_free(key); 1678 key = NULL; 1679 } 1680 if ((r = sshkey_load_public(options.host_key_files[i], 1681 &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR) 1682 do_log2_r(r, ll, "Unable to load host key \"%s\"", 1683 options.host_key_files[i]); 1684 if (pubkey != NULL && key != NULL) { 1685 if (!sshkey_equal(pubkey, key)) { 1686 error("Public key for %s does not match " 1687 "private key", options.host_key_files[i]); 1688 sshkey_free(pubkey); 1689 pubkey = NULL; 1690 } 1691 } 1692 if (pubkey == NULL && key != NULL) { 1693 if ((r = sshkey_from_private(key, &pubkey)) != 0) 1694 fatal_r(r, "Could not demote key: \"%s\"", 1695 options.host_key_files[i]); 1696 } 1697 if (pubkey != NULL && (r = sshkey_check_rsa_length(pubkey, 1698 options.required_rsa_size)) != 0) { 1699 error_fr(r, "Host key %s", options.host_key_files[i]); 1700 sshkey_free(pubkey); 1701 sshkey_free(key); 1702 continue; 1703 } 1704 sensitive_data.host_keys[i] = key; 1705 sensitive_data.host_pubkeys[i] = pubkey; 1706 1707 if (key == NULL && pubkey != NULL && have_agent) { 1708 debug("will rely on agent for hostkey %s", 1709 options.host_key_files[i]); 1710 keytype = pubkey->type; 1711 } else if (key != NULL) { 1712 keytype = key->type; 1713 accumulate_host_timing_secret(cfg, key); 1714 } else { 1715 do_log2(ll, "Unable to load host key: %s", 1716 options.host_key_files[i]); 1717 sensitive_data.host_keys[i] = NULL; 1718 sensitive_data.host_pubkeys[i] = NULL; 1719 continue; 1720 } 1721 1722 switch (keytype) { 1723 case KEY_RSA: 1724 case KEY_DSA: 1725 case KEY_ECDSA: 1726 case KEY_ED25519: 1727 case KEY_ECDSA_SK: 1728 case KEY_ED25519_SK: 1729 case KEY_XMSS: 1730 if (have_agent || key != NULL) 1731 sensitive_data.have_ssh2_key = 1; 1732 break; 1733 } 1734 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash, 1735 SSH_FP_DEFAULT)) == NULL) 1736 fatal("sshkey_fingerprint failed"); 1737 debug("%s host key #%d: %s %s", 1738 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp); 1739 free(fp); 1740 } 1741 accumulate_host_timing_secret(cfg, NULL); 1742 if (!sensitive_data.have_ssh2_key) { 1743 logit("sshd: no hostkeys available -- exiting."); 1744 exit(1); 1745 } 1746 1747 /* 1748 * Load certificates. They are stored in an array at identical 1749 * indices to the public keys that they relate to. 1750 */ 1751 sensitive_data.host_certificates = xcalloc(options.num_host_key_files, 1752 sizeof(struct sshkey *)); 1753 for (i = 0; i < options.num_host_key_files; i++) 1754 sensitive_data.host_certificates[i] = NULL; 1755 1756 for (i = 0; i < options.num_host_cert_files; i++) { 1757 if (options.host_cert_files[i] == NULL) 1758 continue; 1759 if ((r = sshkey_load_public(options.host_cert_files[i], 1760 &key, NULL)) != 0) { 1761 error_r(r, "Could not load host certificate \"%s\"", 1762 options.host_cert_files[i]); 1763 continue; 1764 } 1765 if (!sshkey_is_cert(key)) { 1766 error("Certificate file is not a certificate: %s", 1767 options.host_cert_files[i]); 1768 sshkey_free(key); 1769 continue; 1770 } 1771 /* Find matching private key */ 1772 for (j = 0; j < options.num_host_key_files; j++) { 1773 if (sshkey_equal_public(key, 1774 sensitive_data.host_pubkeys[j])) { 1775 sensitive_data.host_certificates[j] = key; 1776 break; 1777 } 1778 } 1779 if (j >= options.num_host_key_files) { 1780 error("No matching private key for certificate: %s", 1781 options.host_cert_files[i]); 1782 sshkey_free(key); 1783 continue; 1784 } 1785 sensitive_data.host_certificates[j] = key; 1786 debug("host certificate: #%u type %d %s", j, key->type, 1787 sshkey_type(key)); 1788 } 1789 1790 /* Ensure privsep directory is correctly configured. */ 1791 need_chroot = ((getuid() == 0 || geteuid() == 0) || 1792 options.kerberos_authentication); 1793 if ((getpwnam(SSH_PRIVSEP_USER)) == NULL && need_chroot) { 1794 fatal("Privilege separation user %s does not exist", 1795 SSH_PRIVSEP_USER); 1796 } 1797 endpwent(); 1798 1799 if (need_chroot) { 1800 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &sb) == -1) || 1801 (S_ISDIR(sb.st_mode) == 0)) 1802 fatal("Missing privilege separation directory: %s", 1803 _PATH_PRIVSEP_CHROOT_DIR); 1804 #ifdef HAVE_CYGWIN 1805 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) && 1806 (sb.st_uid != getuid () || 1807 (sb.st_mode & (S_IWGRP|S_IWOTH)) != 0)) 1808 #else 1809 if (sb.st_uid != 0 || (sb.st_mode & (S_IWGRP|S_IWOTH)) != 0) 1810 #endif 1811 fatal("%s must be owned by root and not group or " 1812 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR); 1813 } 1814 1815 if (test_flag > 1) 1816 print_config(&connection_info); 1817 1818 /* Configuration looks good, so exit if in test mode. */ 1819 if (test_flag) 1820 exit(0); 1821 1822 /* 1823 * Clear out any supplemental groups we may have inherited. This 1824 * prevents inadvertent creation of files with bad modes (in the 1825 * portable version at least, it's certainly possible for PAM 1826 * to create a file, and we can't control the code in every 1827 * module which might be used). 1828 */ 1829 if (setgroups(0, NULL) < 0) 1830 debug("setgroups() failed: %.200s", strerror(errno)); 1831 1832 /* Prepare arguments for sshd-session */ 1833 if (rexec_argc < 0) 1834 fatal("rexec_argc %d < 0", rexec_argc); 1835 rexec_argv = xcalloc(rexec_argc + 3, sizeof(char *)); 1836 /* Point to the sshd-session binary instead of sshd */ 1837 rexec_argv[0] = options.sshd_session_path; 1838 for (i = 1; i < (u_int)rexec_argc; i++) { 1839 debug("rexec_argv[%d]='%s'", i, saved_argv[i]); 1840 rexec_argv[i] = saved_argv[i]; 1841 } 1842 rexec_argv[rexec_argc++] = "-R"; 1843 rexec_argv[rexec_argc] = NULL; 1844 if (stat(rexec_argv[0], &sb) != 0 || !(sb.st_mode & (S_IXOTH|S_IXUSR))) 1845 fatal("%s does not exist or is not executable", rexec_argv[0]); 1846 debug3("using %s for re-exec", rexec_argv[0]); 1847 1848 /* Ensure that the privsep binary exists now too. */ 1849 if (stat(options.sshd_auth_path, &sb) != 0 || 1850 !(sb.st_mode & (S_IXOTH|S_IXUSR))) { 1851 fatal("%s does not exist or is not executable", 1852 options.sshd_auth_path); 1853 } 1854 1855 listener_proctitle = prepare_proctitle(ac, av); 1856 1857 /* Ensure that umask disallows at least group and world write */ 1858 new_umask = umask(0077) | 0022; 1859 (void) umask(new_umask); 1860 1861 /* Initialize the log (it is reinitialized below in case we forked). */ 1862 if (debug_flag && !inetd_flag) 1863 log_stderr = 1; 1864 log_init(__progname, options.log_level, 1865 options.log_facility, log_stderr); 1866 for (i = 0; i < options.num_log_verbose; i++) 1867 log_verbose_add(options.log_verbose[i]); 1868 1869 /* 1870 * If not in debugging mode, not started from inetd and not already 1871 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling 1872 * terminal, and fork. The original process exits. 1873 */ 1874 already_daemon = daemonized(); 1875 if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) { 1876 1877 if (daemon(0, 0) == -1) 1878 fatal("daemon() failed: %.200s", strerror(errno)); 1879 1880 disconnect_controlling_tty(); 1881 } 1882 /* Reinitialize the log (because of the fork above). */ 1883 log_init(__progname, options.log_level, options.log_facility, log_stderr); 1884 1885 /* Avoid killing the process in high-pressure swapping environments. */ 1886 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0) 1887 debug("madvise(): %.200s", strerror(errno)); 1888 1889 /* 1890 * Chdir to the root directory so that the current disk can be 1891 * unmounted if desired. 1892 */ 1893 if (chdir("/") == -1) 1894 error("chdir(\"/\"): %s", strerror(errno)); 1895 1896 /* ignore SIGPIPE */ 1897 ssh_signal(SIGPIPE, SIG_IGN); 1898 1899 config = pack_config(cfg); 1900 1901 /* Get a connection, either from inetd or a listening TCP socket */ 1902 if (inetd_flag) { 1903 /* Send configuration to ancestor sshd-session process */ 1904 if (socketpair(AF_UNIX, SOCK_STREAM, 0, config_s) == -1) 1905 fatal("socketpair: %s", strerror(errno)); 1906 send_rexec_state(config_s[0]); 1907 close(config_s[0]); 1908 } else { 1909 platform_pre_listen(); 1910 server_listen(); 1911 1912 ssh_signal(SIGHUP, sighup_handler); 1913 ssh_signal(SIGCHLD, main_sigchld_handler); 1914 ssh_signal(SIGTERM, sigterm_handler); 1915 ssh_signal(SIGQUIT, sigterm_handler); 1916 #ifdef SIGINFO 1917 ssh_signal(SIGINFO, siginfo_handler); 1918 #endif 1919 1920 platform_post_listen(); 1921 1922 /* 1923 * Write out the pid file after the sigterm handler 1924 * is setup and the listen sockets are bound 1925 */ 1926 if (options.pid_file != NULL && !debug_flag) { 1927 FILE *f = fopen(options.pid_file, "w"); 1928 1929 if (f == NULL) { 1930 error("Couldn't create pid file \"%s\": %s", 1931 options.pid_file, strerror(errno)); 1932 } else { 1933 fprintf(f, "%ld\n", (long) getpid()); 1934 fclose(f); 1935 } 1936 } 1937 1938 /* Accept a connection and return in a forked child */ 1939 server_accept_loop(&sock_in, &sock_out, 1940 &newsock, config_s, log_stderr); 1941 } 1942 1943 /* This is the child processing a new connection. */ 1944 setproctitle("%s", "[accepted]"); 1945 1946 /* 1947 * Create a new session and process group since the 4.4BSD 1948 * setlogin() affects the entire process group. We don't 1949 * want the child to be able to affect the parent. 1950 */ 1951 if (!debug_flag && !inetd_flag && setsid() == -1) 1952 error("setsid: %.100s", strerror(errno)); 1953 1954 debug("rexec start in %d out %d newsock %d config_s %d/%d", 1955 sock_in, sock_out, newsock, config_s[0], config_s[1]); 1956 if (!inetd_flag) { 1957 if (dup2(newsock, STDIN_FILENO) == -1) 1958 fatal("dup2 stdin: %s", strerror(errno)); 1959 if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1) 1960 fatal("dup2 stdout: %s", strerror(errno)); 1961 if (newsock > STDOUT_FILENO) 1962 close(newsock); 1963 } 1964 if (config_s[1] != REEXEC_CONFIG_PASS_FD) { 1965 if (dup2(config_s[1], REEXEC_CONFIG_PASS_FD) == -1) 1966 fatal("dup2 config_s: %s", strerror(errno)); 1967 close(config_s[1]); 1968 } 1969 log_redirect_stderr_to(NULL); 1970 closefrom(REEXEC_MIN_FREE_FD); 1971 1972 ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */ 1973 execv(rexec_argv[0], rexec_argv); 1974 1975 fatal("rexec of %s failed: %s", rexec_argv[0], strerror(errno)); 1976 #ifdef __FreeBSD__ 1977 /* 1978 * Initialize the resolver. This may not happen automatically 1979 * before privsep chroot(). 1980 */ 1981 if ((_res.options & RES_INIT) == 0) { 1982 debug("res_init()"); 1983 res_init(); 1984 } 1985 #ifdef GSSAPI 1986 /* 1987 * Force GSS-API to parse its configuration and load any 1988 * mechanism plugins. 1989 */ 1990 { 1991 gss_OID_set mechs; 1992 OM_uint32 minor_status; 1993 gss_indicate_mechs(&minor_status, &mechs); 1994 gss_release_oid_set(&minor_status, &mechs); 1995 } 1996 #endif 1997 #endif 1998 } 1999 2000 /* server specific fatal cleanup */ 2001 void 2002 cleanup_exit(int i) 2003 { 2004 _exit(i); 2005 } 2006