1 /* $OpenBSD: sshd.c,v 1.585 2022/03/18 04:04:11 djm Exp $ */ 2 /* 3 * Author: Tatu Ylonen <ylo@cs.hut.fi> 4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 5 * All rights reserved 6 * This program is the ssh daemon. It listens for connections from clients, 7 * and performs authentication, executes use commands or shell, and forwards 8 * information to/from the application to the user client over an encrypted 9 * connection. This can also handle forwarding of X11, TCP/IP, and 10 * authentication agent connections. 11 * 12 * As far as I am concerned, the code I have written for this software 13 * can be used freely for any purpose. Any derived versions of this 14 * software must be clearly marked as such, and if the derived work is 15 * incompatible with the protocol description in the RFC file, it must be 16 * called by a name other than "ssh" or "Secure Shell". 17 * 18 * SSH2 implementation: 19 * Privilege Separation: 20 * 21 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved. 22 * Copyright (c) 2002 Niels Provos. All rights reserved. 23 * 24 * Redistribution and use in source and binary forms, with or without 25 * modification, are permitted provided that the following conditions 26 * are met: 27 * 1. Redistributions of source code must retain the above copyright 28 * notice, this list of conditions and the following disclaimer. 29 * 2. Redistributions in binary form must reproduce the above copyright 30 * notice, this list of conditions and the following disclaimer in the 31 * documentation and/or other materials provided with the distribution. 32 * 33 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 34 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 35 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 36 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 37 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 38 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 39 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 40 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 41 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 42 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 43 */ 44 45 #include "includes.h" 46 47 #include <sys/types.h> 48 #include <sys/ioctl.h> 49 #include <sys/mman.h> 50 #include <sys/socket.h> 51 #ifdef HAVE_SYS_STAT_H 52 # include <sys/stat.h> 53 #endif 54 #ifdef HAVE_SYS_TIME_H 55 # include <sys/time.h> 56 #endif 57 #include "openbsd-compat/sys-tree.h" 58 #include "openbsd-compat/sys-queue.h" 59 #include <sys/wait.h> 60 61 #include <errno.h> 62 #include <fcntl.h> 63 #include <netdb.h> 64 #ifdef HAVE_PATHS_H 65 #include <paths.h> 66 #endif 67 #include <grp.h> 68 #ifdef HAVE_POLL_H 69 #include <poll.h> 70 #endif 71 #include <pwd.h> 72 #include <signal.h> 73 #include <stdarg.h> 74 #include <stdio.h> 75 #include <stdlib.h> 76 #include <string.h> 77 #include <unistd.h> 78 #include <limits.h> 79 80 #ifdef WITH_OPENSSL 81 #include <openssl/dh.h> 82 #include <openssl/bn.h> 83 #include <openssl/rand.h> 84 #include "openbsd-compat/openssl-compat.h" 85 #endif 86 87 #ifdef HAVE_SECUREWARE 88 #include <sys/security.h> 89 #include <prot.h> 90 #endif 91 92 #ifdef __FreeBSD__ 93 #include <resolv.h> 94 #if defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H) 95 #include <gssapi/gssapi.h> 96 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_H) 97 #include <gssapi.h> 98 #endif 99 #endif 100 101 #include "xmalloc.h" 102 #include "ssh.h" 103 #include "ssh2.h" 104 #include "sshpty.h" 105 #include "packet.h" 106 #include "log.h" 107 #include "sshbuf.h" 108 #include "misc.h" 109 #include "match.h" 110 #include "servconf.h" 111 #include "uidswap.h" 112 #include "compat.h" 113 #include "cipher.h" 114 #include "digest.h" 115 #include "sshkey.h" 116 #include "kex.h" 117 #include "myproposal.h" 118 #include "authfile.h" 119 #include "pathnames.h" 120 #include "atomicio.h" 121 #include "canohost.h" 122 #include "hostfile.h" 123 #include "auth.h" 124 #include "authfd.h" 125 #include "msg.h" 126 #include "dispatch.h" 127 #include "channels.h" 128 #include "session.h" 129 #include "monitor.h" 130 #ifdef GSSAPI 131 #include "ssh-gss.h" 132 #endif 133 #include "monitor_wrap.h" 134 #include "ssh-sandbox.h" 135 #include "auth-options.h" 136 #include "version.h" 137 #include "ssherr.h" 138 #include "sk-api.h" 139 #include "srclimit.h" 140 #include "dh.h" 141 #include "blacklist_client.h" 142 143 #ifdef LIBWRAP 144 #include <tcpd.h> 145 #include <syslog.h> 146 extern int allow_severity; 147 extern int deny_severity; 148 #endif /* LIBWRAP */ 149 150 /* Re-exec fds */ 151 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1) 152 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2) 153 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3) 154 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4) 155 156 extern char *__progname; 157 158 /* Server configuration options. */ 159 ServerOptions options; 160 161 /* Name of the server configuration file. */ 162 char *config_file_name = _PATH_SERVER_CONFIG_FILE; 163 164 /* 165 * Debug mode flag. This can be set on the command line. If debug 166 * mode is enabled, extra debugging output will be sent to the system 167 * log, the daemon will not go to background, and will exit after processing 168 * the first connection. 169 */ 170 int debug_flag = 0; 171 172 /* 173 * Indicating that the daemon should only test the configuration and keys. 174 * If test_flag > 1 ("-T" flag), then sshd will also dump the effective 175 * configuration, optionally using connection information provided by the 176 * "-C" flag. 177 */ 178 static int test_flag = 0; 179 180 /* Flag indicating that the daemon is being started from inetd. */ 181 static int inetd_flag = 0; 182 183 /* Flag indicating that sshd should not detach and become a daemon. */ 184 static int no_daemon_flag = 0; 185 186 /* debug goes to stderr unless inetd_flag is set */ 187 static int log_stderr = 0; 188 189 /* Saved arguments to main(). */ 190 static char **saved_argv; 191 static int saved_argc; 192 193 /* re-exec */ 194 static int rexeced_flag = 0; 195 static int rexec_flag = 1; 196 static int rexec_argc = 0; 197 static char **rexec_argv; 198 199 /* 200 * The sockets that the server is listening; this is used in the SIGHUP 201 * signal handler. 202 */ 203 #define MAX_LISTEN_SOCKS 16 204 static int listen_socks[MAX_LISTEN_SOCKS]; 205 static int num_listen_socks = 0; 206 207 /* Daemon's agent connection */ 208 int auth_sock = -1; 209 static int have_agent = 0; 210 211 /* 212 * Any really sensitive data in the application is contained in this 213 * structure. The idea is that this structure could be locked into memory so 214 * that the pages do not get written into swap. However, there are some 215 * problems. The private key contains BIGNUMs, and we do not (in principle) 216 * have access to the internals of them, and locking just the structure is 217 * not very useful. Currently, memory locking is not implemented. 218 */ 219 struct { 220 struct sshkey **host_keys; /* all private host keys */ 221 struct sshkey **host_pubkeys; /* all public host keys */ 222 struct sshkey **host_certificates; /* all public host certificates */ 223 int have_ssh2_key; 224 } sensitive_data; 225 226 /* This is set to true when a signal is received. */ 227 static volatile sig_atomic_t received_sighup = 0; 228 static volatile sig_atomic_t received_sigterm = 0; 229 230 /* record remote hostname or ip */ 231 u_int utmp_len = HOST_NAME_MAX+1; 232 233 /* 234 * startup_pipes/flags are used for tracking children of the listening sshd 235 * process early in their lifespans. This tracking is needed for three things: 236 * 237 * 1) Implementing the MaxStartups limit of concurrent unauthenticated 238 * connections. 239 * 2) Avoiding a race condition for SIGHUP processing, where child processes 240 * may have listen_socks open that could collide with main listener process 241 * after it restarts. 242 * 3) Ensuring that rexec'd sshd processes have received their initial state 243 * from the parent listen process before handling SIGHUP. 244 * 245 * Child processes signal that they have completed closure of the listen_socks 246 * and (if applicable) received their rexec state by sending a char over their 247 * sock. Child processes signal that authentication has completed by closing 248 * the sock (or by exiting). 249 */ 250 static int *startup_pipes = NULL; 251 static int *startup_flags = NULL; /* Indicates child closed listener */ 252 static int startup_pipe = -1; /* in child */ 253 254 /* variables used for privilege separation */ 255 int use_privsep = -1; 256 struct monitor *pmonitor = NULL; 257 int privsep_is_preauth = 1; 258 static int privsep_chroot = 1; 259 260 /* global connection state and authentication contexts */ 261 Authctxt *the_authctxt = NULL; 262 struct ssh *the_active_state; 263 264 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */ 265 struct sshauthopt *auth_opts = NULL; 266 267 /* sshd_config buffer */ 268 struct sshbuf *cfg; 269 270 /* Included files from the configuration file */ 271 struct include_list includes = TAILQ_HEAD_INITIALIZER(includes); 272 273 /* message to be displayed after login */ 274 struct sshbuf *loginmsg; 275 276 /* Unprivileged user */ 277 struct passwd *privsep_pw = NULL; 278 279 /* Prototypes for various functions defined later in this file. */ 280 void destroy_sensitive_data(void); 281 void demote_sensitive_data(void); 282 static void do_ssh2_kex(struct ssh *); 283 284 static char *listener_proctitle; 285 286 /* 287 * Close all listening sockets 288 */ 289 static void 290 close_listen_socks(void) 291 { 292 int i; 293 294 for (i = 0; i < num_listen_socks; i++) 295 close(listen_socks[i]); 296 num_listen_socks = 0; 297 } 298 299 static void 300 close_startup_pipes(void) 301 { 302 int i; 303 304 if (startup_pipes) 305 for (i = 0; i < options.max_startups; i++) 306 if (startup_pipes[i] != -1) 307 close(startup_pipes[i]); 308 } 309 310 /* 311 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP; 312 * the effect is to reread the configuration file (and to regenerate 313 * the server key). 314 */ 315 316 /*ARGSUSED*/ 317 static void 318 sighup_handler(int sig) 319 { 320 received_sighup = 1; 321 } 322 323 /* 324 * Called from the main program after receiving SIGHUP. 325 * Restarts the server. 326 */ 327 static void 328 sighup_restart(void) 329 { 330 logit("Received SIGHUP; restarting."); 331 if (options.pid_file != NULL) 332 unlink(options.pid_file); 333 platform_pre_restart(); 334 close_listen_socks(); 335 close_startup_pipes(); 336 ssh_signal(SIGHUP, SIG_IGN); /* will be restored after exec */ 337 execv(saved_argv[0], saved_argv); 338 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], 339 strerror(errno)); 340 exit(1); 341 } 342 343 /* 344 * Generic signal handler for terminating signals in the master daemon. 345 */ 346 /*ARGSUSED*/ 347 static void 348 sigterm_handler(int sig) 349 { 350 received_sigterm = sig; 351 } 352 353 /* 354 * SIGCHLD handler. This is called whenever a child dies. This will then 355 * reap any zombies left by exited children. 356 */ 357 /*ARGSUSED*/ 358 static void 359 main_sigchld_handler(int sig) 360 { 361 int save_errno = errno; 362 pid_t pid; 363 int status; 364 365 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 366 (pid == -1 && errno == EINTR)) 367 ; 368 errno = save_errno; 369 } 370 371 /* 372 * Signal handler for the alarm after the login grace period has expired. 373 */ 374 /*ARGSUSED*/ 375 static void 376 grace_alarm_handler(int sig) 377 { 378 /* 379 * Try to kill any processes that we have spawned, E.g. authorized 380 * keys command helpers or privsep children. 381 */ 382 if (getpgid(0) == getpid()) { 383 ssh_signal(SIGTERM, SIG_IGN); 384 kill(0, SIGTERM); 385 } 386 387 BLACKLIST_NOTIFY(the_active_state, BLACKLIST_AUTH_FAIL, "ssh"); 388 389 /* Log error and exit. */ 390 sigdie("Timeout before authentication for %s port %d", 391 ssh_remote_ipaddr(the_active_state), 392 ssh_remote_port(the_active_state)); 393 } 394 395 /* Destroy the host and server keys. They will no longer be needed. */ 396 void 397 destroy_sensitive_data(void) 398 { 399 u_int i; 400 401 for (i = 0; i < options.num_host_key_files; i++) { 402 if (sensitive_data.host_keys[i]) { 403 sshkey_free(sensitive_data.host_keys[i]); 404 sensitive_data.host_keys[i] = NULL; 405 } 406 if (sensitive_data.host_certificates[i]) { 407 sshkey_free(sensitive_data.host_certificates[i]); 408 sensitive_data.host_certificates[i] = NULL; 409 } 410 } 411 } 412 413 /* Demote private to public keys for network child */ 414 void 415 demote_sensitive_data(void) 416 { 417 struct sshkey *tmp; 418 u_int i; 419 int r; 420 421 for (i = 0; i < options.num_host_key_files; i++) { 422 if (sensitive_data.host_keys[i]) { 423 if ((r = sshkey_from_private( 424 sensitive_data.host_keys[i], &tmp)) != 0) 425 fatal_r(r, "could not demote host %s key", 426 sshkey_type(sensitive_data.host_keys[i])); 427 sshkey_free(sensitive_data.host_keys[i]); 428 sensitive_data.host_keys[i] = tmp; 429 } 430 /* Certs do not need demotion */ 431 } 432 } 433 434 static void 435 reseed_prngs(void) 436 { 437 u_int32_t rnd[256]; 438 439 #ifdef WITH_OPENSSL 440 RAND_poll(); 441 #endif 442 arc4random_stir(); /* noop on recent arc4random() implementations */ 443 arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */ 444 445 #ifdef WITH_OPENSSL 446 RAND_seed(rnd, sizeof(rnd)); 447 /* give libcrypto a chance to notice the PID change */ 448 if ((RAND_bytes((u_char *)rnd, 1)) != 1) 449 fatal("%s: RAND_bytes failed", __func__); 450 #endif 451 452 explicit_bzero(rnd, sizeof(rnd)); 453 } 454 455 static void 456 privsep_preauth_child(void) 457 { 458 gid_t gidset[1]; 459 460 /* Enable challenge-response authentication for privilege separation */ 461 privsep_challenge_enable(); 462 463 #ifdef GSSAPI 464 /* Cache supported mechanism OIDs for later use */ 465 ssh_gssapi_prepare_supported_oids(); 466 #endif 467 468 reseed_prngs(); 469 470 /* Demote the private keys to public keys. */ 471 demote_sensitive_data(); 472 473 /* Demote the child */ 474 if (privsep_chroot) { 475 /* Change our root directory */ 476 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1) 477 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR, 478 strerror(errno)); 479 if (chdir("/") == -1) 480 fatal("chdir(\"/\"): %s", strerror(errno)); 481 482 /* Drop our privileges */ 483 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid, 484 (u_int)privsep_pw->pw_gid); 485 gidset[0] = privsep_pw->pw_gid; 486 if (setgroups(1, gidset) == -1) 487 fatal("setgroups: %.100s", strerror(errno)); 488 permanently_set_uid(privsep_pw); 489 } 490 } 491 492 static int 493 privsep_preauth(struct ssh *ssh) 494 { 495 int status, r; 496 pid_t pid; 497 struct ssh_sandbox *box = NULL; 498 499 /* Set up unprivileged child process to deal with network data */ 500 pmonitor = monitor_init(); 501 /* Store a pointer to the kex for later rekeying */ 502 pmonitor->m_pkex = &ssh->kex; 503 504 if (use_privsep == PRIVSEP_ON) 505 box = ssh_sandbox_init(pmonitor); 506 pid = fork(); 507 if (pid == -1) { 508 fatal("fork of unprivileged child failed"); 509 } else if (pid != 0) { 510 debug2("Network child is on pid %ld", (long)pid); 511 512 pmonitor->m_pid = pid; 513 if (have_agent) { 514 r = ssh_get_authentication_socket(&auth_sock); 515 if (r != 0) { 516 error_r(r, "Could not get agent socket"); 517 have_agent = 0; 518 } 519 } 520 if (box != NULL) 521 ssh_sandbox_parent_preauth(box, pid); 522 monitor_child_preauth(ssh, pmonitor); 523 524 /* Wait for the child's exit status */ 525 while (waitpid(pid, &status, 0) == -1) { 526 if (errno == EINTR) 527 continue; 528 pmonitor->m_pid = -1; 529 fatal_f("waitpid: %s", strerror(errno)); 530 } 531 privsep_is_preauth = 0; 532 pmonitor->m_pid = -1; 533 if (WIFEXITED(status)) { 534 if (WEXITSTATUS(status) != 0) 535 fatal_f("preauth child exited with status %d", 536 WEXITSTATUS(status)); 537 } else if (WIFSIGNALED(status)) 538 fatal_f("preauth child terminated by signal %d", 539 WTERMSIG(status)); 540 if (box != NULL) 541 ssh_sandbox_parent_finish(box); 542 return 1; 543 } else { 544 /* child */ 545 close(pmonitor->m_sendfd); 546 close(pmonitor->m_log_recvfd); 547 548 /* Arrange for logging to be sent to the monitor */ 549 set_log_handler(mm_log_handler, pmonitor); 550 551 privsep_preauth_child(); 552 setproctitle("%s", "[net]"); 553 if (box != NULL) 554 ssh_sandbox_child(box); 555 556 return 0; 557 } 558 } 559 560 static void 561 privsep_postauth(struct ssh *ssh, Authctxt *authctxt) 562 { 563 #ifdef DISABLE_FD_PASSING 564 if (1) { 565 #else 566 if (authctxt->pw->pw_uid == 0) { 567 #endif 568 /* File descriptor passing is broken or root login */ 569 use_privsep = 0; 570 goto skip; 571 } 572 573 /* New socket pair */ 574 monitor_reinit(pmonitor); 575 576 pmonitor->m_pid = fork(); 577 if (pmonitor->m_pid == -1) 578 fatal("fork of unprivileged child failed"); 579 else if (pmonitor->m_pid != 0) { 580 verbose("User child is on pid %ld", (long)pmonitor->m_pid); 581 sshbuf_reset(loginmsg); 582 monitor_clear_keystate(ssh, pmonitor); 583 monitor_child_postauth(ssh, pmonitor); 584 585 /* NEVERREACHED */ 586 exit(0); 587 } 588 589 /* child */ 590 591 close(pmonitor->m_sendfd); 592 pmonitor->m_sendfd = -1; 593 594 /* Demote the private keys to public keys. */ 595 demote_sensitive_data(); 596 597 reseed_prngs(); 598 599 /* Drop privileges */ 600 do_setusercontext(authctxt->pw); 601 602 skip: 603 /* It is safe now to apply the key state */ 604 monitor_apply_keystate(ssh, pmonitor); 605 606 /* 607 * Tell the packet layer that authentication was successful, since 608 * this information is not part of the key state. 609 */ 610 ssh_packet_set_authenticated(ssh); 611 } 612 613 static void 614 append_hostkey_type(struct sshbuf *b, const char *s) 615 { 616 int r; 617 618 if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) { 619 debug3_f("%s key not permitted by HostkeyAlgorithms", s); 620 return; 621 } 622 if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0) 623 fatal_fr(r, "sshbuf_putf"); 624 } 625 626 static char * 627 list_hostkey_types(void) 628 { 629 struct sshbuf *b; 630 struct sshkey *key; 631 char *ret; 632 u_int i; 633 634 if ((b = sshbuf_new()) == NULL) 635 fatal_f("sshbuf_new failed"); 636 for (i = 0; i < options.num_host_key_files; i++) { 637 key = sensitive_data.host_keys[i]; 638 if (key == NULL) 639 key = sensitive_data.host_pubkeys[i]; 640 if (key == NULL) 641 continue; 642 switch (key->type) { 643 case KEY_RSA: 644 /* for RSA we also support SHA2 signatures */ 645 append_hostkey_type(b, "rsa-sha2-512"); 646 append_hostkey_type(b, "rsa-sha2-256"); 647 /* FALLTHROUGH */ 648 case KEY_DSA: 649 case KEY_ECDSA: 650 case KEY_ED25519: 651 case KEY_ECDSA_SK: 652 case KEY_ED25519_SK: 653 case KEY_XMSS: 654 append_hostkey_type(b, sshkey_ssh_name(key)); 655 break; 656 } 657 /* If the private key has a cert peer, then list that too */ 658 key = sensitive_data.host_certificates[i]; 659 if (key == NULL) 660 continue; 661 switch (key->type) { 662 case KEY_RSA_CERT: 663 /* for RSA we also support SHA2 signatures */ 664 append_hostkey_type(b, 665 "rsa-sha2-512-cert-v01@openssh.com"); 666 append_hostkey_type(b, 667 "rsa-sha2-256-cert-v01@openssh.com"); 668 /* FALLTHROUGH */ 669 case KEY_DSA_CERT: 670 case KEY_ECDSA_CERT: 671 case KEY_ED25519_CERT: 672 case KEY_ECDSA_SK_CERT: 673 case KEY_ED25519_SK_CERT: 674 case KEY_XMSS_CERT: 675 append_hostkey_type(b, sshkey_ssh_name(key)); 676 break; 677 } 678 } 679 if ((ret = sshbuf_dup_string(b)) == NULL) 680 fatal_f("sshbuf_dup_string failed"); 681 sshbuf_free(b); 682 debug_f("%s", ret); 683 return ret; 684 } 685 686 static struct sshkey * 687 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh) 688 { 689 u_int i; 690 struct sshkey *key; 691 692 for (i = 0; i < options.num_host_key_files; i++) { 693 switch (type) { 694 case KEY_RSA_CERT: 695 case KEY_DSA_CERT: 696 case KEY_ECDSA_CERT: 697 case KEY_ED25519_CERT: 698 case KEY_ECDSA_SK_CERT: 699 case KEY_ED25519_SK_CERT: 700 case KEY_XMSS_CERT: 701 key = sensitive_data.host_certificates[i]; 702 break; 703 default: 704 key = sensitive_data.host_keys[i]; 705 if (key == NULL && !need_private) 706 key = sensitive_data.host_pubkeys[i]; 707 break; 708 } 709 if (key == NULL || key->type != type) 710 continue; 711 switch (type) { 712 case KEY_ECDSA: 713 case KEY_ECDSA_SK: 714 case KEY_ECDSA_CERT: 715 case KEY_ECDSA_SK_CERT: 716 if (key->ecdsa_nid != nid) 717 continue; 718 /* FALLTHROUGH */ 719 default: 720 return need_private ? 721 sensitive_data.host_keys[i] : key; 722 } 723 } 724 return NULL; 725 } 726 727 struct sshkey * 728 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh) 729 { 730 return get_hostkey_by_type(type, nid, 0, ssh); 731 } 732 733 struct sshkey * 734 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh) 735 { 736 return get_hostkey_by_type(type, nid, 1, ssh); 737 } 738 739 struct sshkey * 740 get_hostkey_by_index(int ind) 741 { 742 if (ind < 0 || (u_int)ind >= options.num_host_key_files) 743 return (NULL); 744 return (sensitive_data.host_keys[ind]); 745 } 746 747 struct sshkey * 748 get_hostkey_public_by_index(int ind, struct ssh *ssh) 749 { 750 if (ind < 0 || (u_int)ind >= options.num_host_key_files) 751 return (NULL); 752 return (sensitive_data.host_pubkeys[ind]); 753 } 754 755 int 756 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh) 757 { 758 u_int i; 759 760 for (i = 0; i < options.num_host_key_files; i++) { 761 if (sshkey_is_cert(key)) { 762 if (key == sensitive_data.host_certificates[i] || 763 (compare && sensitive_data.host_certificates[i] && 764 sshkey_equal(key, 765 sensitive_data.host_certificates[i]))) 766 return (i); 767 } else { 768 if (key == sensitive_data.host_keys[i] || 769 (compare && sensitive_data.host_keys[i] && 770 sshkey_equal(key, sensitive_data.host_keys[i]))) 771 return (i); 772 if (key == sensitive_data.host_pubkeys[i] || 773 (compare && sensitive_data.host_pubkeys[i] && 774 sshkey_equal(key, sensitive_data.host_pubkeys[i]))) 775 return (i); 776 } 777 } 778 return (-1); 779 } 780 781 /* Inform the client of all hostkeys */ 782 static void 783 notify_hostkeys(struct ssh *ssh) 784 { 785 struct sshbuf *buf; 786 struct sshkey *key; 787 u_int i, nkeys; 788 int r; 789 char *fp; 790 791 /* Some clients cannot cope with the hostkeys message, skip those. */ 792 if (ssh->compat & SSH_BUG_HOSTKEYS) 793 return; 794 795 if ((buf = sshbuf_new()) == NULL) 796 fatal_f("sshbuf_new"); 797 for (i = nkeys = 0; i < options.num_host_key_files; i++) { 798 key = get_hostkey_public_by_index(i, ssh); 799 if (key == NULL || key->type == KEY_UNSPEC || 800 sshkey_is_cert(key)) 801 continue; 802 fp = sshkey_fingerprint(key, options.fingerprint_hash, 803 SSH_FP_DEFAULT); 804 debug3_f("key %d: %s %s", i, sshkey_ssh_name(key), fp); 805 free(fp); 806 if (nkeys == 0) { 807 /* 808 * Start building the request when we find the 809 * first usable key. 810 */ 811 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 812 (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 || 813 (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */ 814 sshpkt_fatal(ssh, r, "%s: start request", __func__); 815 } 816 /* Append the key to the request */ 817 sshbuf_reset(buf); 818 if ((r = sshkey_putb(key, buf)) != 0) 819 fatal_fr(r, "couldn't put hostkey %d", i); 820 if ((r = sshpkt_put_stringb(ssh, buf)) != 0) 821 sshpkt_fatal(ssh, r, "%s: append key", __func__); 822 nkeys++; 823 } 824 debug3_f("sent %u hostkeys", nkeys); 825 if (nkeys == 0) 826 fatal_f("no hostkeys"); 827 if ((r = sshpkt_send(ssh)) != 0) 828 sshpkt_fatal(ssh, r, "%s: send", __func__); 829 sshbuf_free(buf); 830 } 831 832 /* 833 * returns 1 if connection should be dropped, 0 otherwise. 834 * dropping starts at connection #max_startups_begin with a probability 835 * of (max_startups_rate/100). the probability increases linearly until 836 * all connections are dropped for startups > max_startups 837 */ 838 static int 839 should_drop_connection(int startups) 840 { 841 int p, r; 842 843 if (startups < options.max_startups_begin) 844 return 0; 845 if (startups >= options.max_startups) 846 return 1; 847 if (options.max_startups_rate == 100) 848 return 1; 849 850 p = 100 - options.max_startups_rate; 851 p *= startups - options.max_startups_begin; 852 p /= options.max_startups - options.max_startups_begin; 853 p += options.max_startups_rate; 854 r = arc4random_uniform(100); 855 856 debug_f("p %d, r %d", p, r); 857 return (r < p) ? 1 : 0; 858 } 859 860 /* 861 * Check whether connection should be accepted by MaxStartups. 862 * Returns 0 if the connection is accepted. If the connection is refused, 863 * returns 1 and attempts to send notification to client. 864 * Logs when the MaxStartups condition is entered or exited, and periodically 865 * while in that state. 866 */ 867 static int 868 drop_connection(int sock, int startups, int notify_pipe) 869 { 870 char *laddr, *raddr; 871 const char msg[] = "Exceeded MaxStartups\r\n"; 872 static time_t last_drop, first_drop; 873 static u_int ndropped; 874 LogLevel drop_level = SYSLOG_LEVEL_VERBOSE; 875 time_t now; 876 877 now = monotime(); 878 if (!should_drop_connection(startups) && 879 srclimit_check_allow(sock, notify_pipe) == 1) { 880 if (last_drop != 0 && 881 startups < options.max_startups_begin - 1) { 882 /* XXX maybe need better hysteresis here */ 883 logit("exited MaxStartups throttling after %s, " 884 "%u connections dropped", 885 fmt_timeframe(now - first_drop), ndropped); 886 last_drop = 0; 887 } 888 return 0; 889 } 890 891 #define SSHD_MAXSTARTUPS_LOG_INTERVAL (5 * 60) 892 if (last_drop == 0) { 893 error("beginning MaxStartups throttling"); 894 drop_level = SYSLOG_LEVEL_INFO; 895 first_drop = now; 896 ndropped = 0; 897 } else if (last_drop + SSHD_MAXSTARTUPS_LOG_INTERVAL < now) { 898 /* Periodic logs */ 899 error("in MaxStartups throttling for %s, " 900 "%u connections dropped", 901 fmt_timeframe(now - first_drop), ndropped + 1); 902 drop_level = SYSLOG_LEVEL_INFO; 903 } 904 last_drop = now; 905 ndropped++; 906 907 laddr = get_local_ipaddr(sock); 908 raddr = get_peer_ipaddr(sock); 909 do_log2(drop_level, "drop connection #%d from [%s]:%d on [%s]:%d " 910 "past MaxStartups", startups, raddr, get_peer_port(sock), 911 laddr, get_local_port(sock)); 912 free(laddr); 913 free(raddr); 914 /* best-effort notification to client */ 915 (void)write(sock, msg, sizeof(msg) - 1); 916 return 1; 917 } 918 919 static void 920 usage(void) 921 { 922 if (options.version_addendum != NULL && 923 *options.version_addendum != '\0') 924 fprintf(stderr, "%s %s, %s\n", 925 SSH_RELEASE, 926 options.version_addendum, SSH_OPENSSL_VERSION); 927 else 928 fprintf(stderr, "%s, %s\n", 929 SSH_RELEASE, SSH_OPENSSL_VERSION); 930 fprintf(stderr, 931 "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n" 932 " [-E log_file] [-f config_file] [-g login_grace_time]\n" 933 " [-h host_key_file] [-o option] [-p port] [-u len]\n" 934 ); 935 exit(1); 936 } 937 938 static void 939 send_rexec_state(int fd, struct sshbuf *conf) 940 { 941 struct sshbuf *m = NULL, *inc = NULL; 942 struct include_item *item = NULL; 943 int r; 944 945 debug3_f("entering fd = %d config len %zu", fd, 946 sshbuf_len(conf)); 947 948 if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL) 949 fatal_f("sshbuf_new failed"); 950 951 /* pack includes into a string */ 952 TAILQ_FOREACH(item, &includes, entry) { 953 if ((r = sshbuf_put_cstring(inc, item->selector)) != 0 || 954 (r = sshbuf_put_cstring(inc, item->filename)) != 0 || 955 (r = sshbuf_put_stringb(inc, item->contents)) != 0) 956 fatal_fr(r, "compose includes"); 957 } 958 959 /* 960 * Protocol from reexec master to child: 961 * string configuration 962 * string included_files[] { 963 * string selector 964 * string filename 965 * string contents 966 * } 967 * string rng_seed (if required) 968 */ 969 if ((r = sshbuf_put_stringb(m, conf)) != 0 || 970 (r = sshbuf_put_stringb(m, inc)) != 0) 971 fatal_fr(r, "compose config"); 972 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY) 973 rexec_send_rng_seed(m); 974 #endif 975 if (ssh_msg_send(fd, 0, m) == -1) 976 error_f("ssh_msg_send failed"); 977 978 sshbuf_free(m); 979 sshbuf_free(inc); 980 981 debug3_f("done"); 982 } 983 984 static void 985 recv_rexec_state(int fd, struct sshbuf *conf) 986 { 987 struct sshbuf *m, *inc; 988 u_char *cp, ver; 989 size_t len; 990 int r; 991 struct include_item *item; 992 993 debug3_f("entering fd = %d", fd); 994 995 if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL) 996 fatal_f("sshbuf_new failed"); 997 if (ssh_msg_recv(fd, m) == -1) 998 fatal_f("ssh_msg_recv failed"); 999 if ((r = sshbuf_get_u8(m, &ver)) != 0) 1000 fatal_fr(r, "parse version"); 1001 if (ver != 0) 1002 fatal_f("rexec version mismatch"); 1003 if ((r = sshbuf_get_string(m, &cp, &len)) != 0 || 1004 (r = sshbuf_get_stringb(m, inc)) != 0) 1005 fatal_fr(r, "parse config"); 1006 1007 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY) 1008 rexec_recv_rng_seed(m); 1009 #endif 1010 1011 if (conf != NULL && (r = sshbuf_put(conf, cp, len))) 1012 fatal_fr(r, "sshbuf_put"); 1013 1014 while (sshbuf_len(inc) != 0) { 1015 item = xcalloc(1, sizeof(*item)); 1016 if ((item->contents = sshbuf_new()) == NULL) 1017 fatal_f("sshbuf_new failed"); 1018 if ((r = sshbuf_get_cstring(inc, &item->selector, NULL)) != 0 || 1019 (r = sshbuf_get_cstring(inc, &item->filename, NULL)) != 0 || 1020 (r = sshbuf_get_stringb(inc, item->contents)) != 0) 1021 fatal_fr(r, "parse includes"); 1022 TAILQ_INSERT_TAIL(&includes, item, entry); 1023 } 1024 1025 free(cp); 1026 sshbuf_free(m); 1027 1028 debug3_f("done"); 1029 } 1030 1031 /* Accept a connection from inetd */ 1032 static void 1033 server_accept_inetd(int *sock_in, int *sock_out) 1034 { 1035 if (rexeced_flag) { 1036 close(REEXEC_CONFIG_PASS_FD); 1037 *sock_in = *sock_out = dup(STDIN_FILENO); 1038 } else { 1039 *sock_in = dup(STDIN_FILENO); 1040 *sock_out = dup(STDOUT_FILENO); 1041 } 1042 /* 1043 * We intentionally do not close the descriptors 0, 1, and 2 1044 * as our code for setting the descriptors won't work if 1045 * ttyfd happens to be one of those. 1046 */ 1047 if (stdfd_devnull(1, 1, !log_stderr) == -1) 1048 error_f("stdfd_devnull failed"); 1049 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out); 1050 } 1051 1052 /* 1053 * Listen for TCP connections 1054 */ 1055 static void 1056 listen_on_addrs(struct listenaddr *la) 1057 { 1058 int ret, listen_sock; 1059 struct addrinfo *ai; 1060 char ntop[NI_MAXHOST], strport[NI_MAXSERV]; 1061 1062 for (ai = la->addrs; ai; ai = ai->ai_next) { 1063 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) 1064 continue; 1065 if (num_listen_socks >= MAX_LISTEN_SOCKS) 1066 fatal("Too many listen sockets. " 1067 "Enlarge MAX_LISTEN_SOCKS"); 1068 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen, 1069 ntop, sizeof(ntop), strport, sizeof(strport), 1070 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) { 1071 error("getnameinfo failed: %.100s", 1072 ssh_gai_strerror(ret)); 1073 continue; 1074 } 1075 /* Create socket for listening. */ 1076 listen_sock = socket(ai->ai_family, ai->ai_socktype, 1077 ai->ai_protocol); 1078 if (listen_sock == -1) { 1079 /* kernel may not support ipv6 */ 1080 verbose("socket: %.100s", strerror(errno)); 1081 continue; 1082 } 1083 if (set_nonblock(listen_sock) == -1) { 1084 close(listen_sock); 1085 continue; 1086 } 1087 if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) { 1088 verbose("socket: CLOEXEC: %s", strerror(errno)); 1089 close(listen_sock); 1090 continue; 1091 } 1092 /* Socket options */ 1093 set_reuseaddr(listen_sock); 1094 if (la->rdomain != NULL && 1095 set_rdomain(listen_sock, la->rdomain) == -1) { 1096 close(listen_sock); 1097 continue; 1098 } 1099 1100 /* Only communicate in IPv6 over AF_INET6 sockets. */ 1101 if (ai->ai_family == AF_INET6) 1102 sock_set_v6only(listen_sock); 1103 1104 debug("Bind to port %s on %s.", strport, ntop); 1105 1106 /* Bind the socket to the desired port. */ 1107 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) { 1108 error("Bind to port %s on %s failed: %.200s.", 1109 strport, ntop, strerror(errno)); 1110 close(listen_sock); 1111 continue; 1112 } 1113 listen_socks[num_listen_socks] = listen_sock; 1114 num_listen_socks++; 1115 1116 /* Start listening on the port. */ 1117 if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1) 1118 fatal("listen on [%s]:%s: %.100s", 1119 ntop, strport, strerror(errno)); 1120 logit("Server listening on %s port %s%s%s.", 1121 ntop, strport, 1122 la->rdomain == NULL ? "" : " rdomain ", 1123 la->rdomain == NULL ? "" : la->rdomain); 1124 } 1125 } 1126 1127 static void 1128 server_listen(void) 1129 { 1130 u_int i; 1131 1132 /* Initialise per-source limit tracking. */ 1133 srclimit_init(options.max_startups, options.per_source_max_startups, 1134 options.per_source_masklen_ipv4, options.per_source_masklen_ipv6); 1135 1136 for (i = 0; i < options.num_listen_addrs; i++) { 1137 listen_on_addrs(&options.listen_addrs[i]); 1138 freeaddrinfo(options.listen_addrs[i].addrs); 1139 free(options.listen_addrs[i].rdomain); 1140 memset(&options.listen_addrs[i], 0, 1141 sizeof(options.listen_addrs[i])); 1142 } 1143 free(options.listen_addrs); 1144 options.listen_addrs = NULL; 1145 options.num_listen_addrs = 0; 1146 1147 if (!num_listen_socks) 1148 fatal("Cannot bind any address."); 1149 } 1150 1151 /* 1152 * The main TCP accept loop. Note that, for the non-debug case, returns 1153 * from this function are in a forked subprocess. 1154 */ 1155 static void 1156 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s) 1157 { 1158 struct pollfd *pfd = NULL; 1159 int i, j, ret, npfd; 1160 int ostartups = -1, startups = 0, listening = 0, lameduck = 0; 1161 int startup_p[2] = { -1 , -1 }, *startup_pollfd; 1162 char c = 0; 1163 struct sockaddr_storage from; 1164 socklen_t fromlen; 1165 pid_t pid; 1166 u_char rnd[256]; 1167 sigset_t nsigset, osigset; 1168 #ifdef LIBWRAP 1169 struct request_info req; 1170 1171 request_init(&req, RQ_DAEMON, __progname, 0); 1172 #endif 1173 1174 /* pipes connected to unauthenticated child sshd processes */ 1175 startup_pipes = xcalloc(options.max_startups, sizeof(int)); 1176 startup_flags = xcalloc(options.max_startups, sizeof(int)); 1177 startup_pollfd = xcalloc(options.max_startups, sizeof(int)); 1178 for (i = 0; i < options.max_startups; i++) 1179 startup_pipes[i] = -1; 1180 1181 /* 1182 * Prepare signal mask that we use to block signals that might set 1183 * received_sigterm or received_sighup, so that we are guaranteed 1184 * to immediately wake up the ppoll if a signal is received after 1185 * the flag is checked. 1186 */ 1187 sigemptyset(&nsigset); 1188 sigaddset(&nsigset, SIGHUP); 1189 sigaddset(&nsigset, SIGCHLD); 1190 sigaddset(&nsigset, SIGTERM); 1191 sigaddset(&nsigset, SIGQUIT); 1192 1193 /* sized for worst-case */ 1194 pfd = xcalloc(num_listen_socks + options.max_startups, 1195 sizeof(struct pollfd)); 1196 1197 /* 1198 * Stay listening for connections until the system crashes or 1199 * the daemon is killed with a signal. 1200 */ 1201 for (;;) { 1202 sigprocmask(SIG_BLOCK, &nsigset, &osigset); 1203 if (received_sigterm) { 1204 logit("Received signal %d; terminating.", 1205 (int) received_sigterm); 1206 close_listen_socks(); 1207 if (options.pid_file != NULL) 1208 unlink(options.pid_file); 1209 exit(received_sigterm == SIGTERM ? 0 : 255); 1210 } 1211 if (ostartups != startups) { 1212 setproctitle("%s [listener] %d of %d-%d startups", 1213 listener_proctitle, startups, 1214 options.max_startups_begin, options.max_startups); 1215 ostartups = startups; 1216 } 1217 if (received_sighup) { 1218 if (!lameduck) { 1219 debug("Received SIGHUP; waiting for children"); 1220 close_listen_socks(); 1221 lameduck = 1; 1222 } 1223 if (listening <= 0) { 1224 sigprocmask(SIG_SETMASK, &osigset, NULL); 1225 sighup_restart(); 1226 } 1227 } 1228 1229 for (i = 0; i < num_listen_socks; i++) { 1230 pfd[i].fd = listen_socks[i]; 1231 pfd[i].events = POLLIN; 1232 } 1233 npfd = num_listen_socks; 1234 for (i = 0; i < options.max_startups; i++) { 1235 startup_pollfd[i] = -1; 1236 if (startup_pipes[i] != -1) { 1237 pfd[npfd].fd = startup_pipes[i]; 1238 pfd[npfd].events = POLLIN; 1239 startup_pollfd[i] = npfd++; 1240 } 1241 } 1242 1243 /* Wait until a connection arrives or a child exits. */ 1244 ret = ppoll(pfd, npfd, NULL, &osigset); 1245 if (ret == -1 && errno != EINTR) { 1246 error("ppoll: %.100s", strerror(errno)); 1247 if (errno == EINVAL) 1248 cleanup_exit(1); /* can't recover */ 1249 } 1250 sigprocmask(SIG_SETMASK, &osigset, NULL); 1251 if (ret == -1) 1252 continue; 1253 1254 for (i = 0; i < options.max_startups; i++) { 1255 if (startup_pipes[i] == -1 || 1256 startup_pollfd[i] == -1 || 1257 !(pfd[startup_pollfd[i]].revents & (POLLIN|POLLHUP))) 1258 continue; 1259 switch (read(startup_pipes[i], &c, sizeof(c))) { 1260 case -1: 1261 if (errno == EINTR || errno == EAGAIN) 1262 continue; 1263 if (errno != EPIPE) { 1264 error_f("startup pipe %d (fd=%d): " 1265 "read %s", i, startup_pipes[i], 1266 strerror(errno)); 1267 } 1268 /* FALLTHROUGH */ 1269 case 0: 1270 /* child exited or completed auth */ 1271 close(startup_pipes[i]); 1272 srclimit_done(startup_pipes[i]); 1273 startup_pipes[i] = -1; 1274 startups--; 1275 if (startup_flags[i]) 1276 listening--; 1277 break; 1278 case 1: 1279 /* child has finished preliminaries */ 1280 if (startup_flags[i]) { 1281 listening--; 1282 startup_flags[i] = 0; 1283 } 1284 break; 1285 } 1286 } 1287 for (i = 0; i < num_listen_socks; i++) { 1288 if (!(pfd[i].revents & POLLIN)) 1289 continue; 1290 fromlen = sizeof(from); 1291 *newsock = accept(listen_socks[i], 1292 (struct sockaddr *)&from, &fromlen); 1293 if (*newsock == -1) { 1294 if (errno != EINTR && errno != EWOULDBLOCK && 1295 errno != ECONNABORTED && errno != EAGAIN) 1296 error("accept: %.100s", 1297 strerror(errno)); 1298 if (errno == EMFILE || errno == ENFILE) 1299 usleep(100 * 1000); 1300 continue; 1301 } 1302 #ifdef LIBWRAP 1303 /* Check whether logins are denied from this host. */ 1304 request_set(&req, RQ_FILE, *newsock, 1305 RQ_CLIENT_NAME, "", RQ_CLIENT_ADDR, "", 0); 1306 sock_host(&req); 1307 if (!hosts_access(&req)) { 1308 const struct linger l = { .l_onoff = 1, 1309 .l_linger = 0 }; 1310 1311 (void )setsockopt(*newsock, SOL_SOCKET, 1312 SO_LINGER, &l, sizeof(l)); 1313 (void )close(*newsock); 1314 /* 1315 * Mimic message from libwrap's refuse() 1316 * exactly. sshguard, and supposedly lots 1317 * of custom made scripts rely on it. 1318 */ 1319 syslog(deny_severity, 1320 "refused connect from %s (%s)", 1321 eval_client(&req), 1322 eval_hostaddr(req.client)); 1323 debug("Connection refused by tcp wrapper"); 1324 continue; 1325 } 1326 #endif /* LIBWRAP */ 1327 if (unset_nonblock(*newsock) == -1 || 1328 pipe(startup_p) == -1) { 1329 close(*newsock); 1330 continue; 1331 } 1332 if (drop_connection(*newsock, startups, startup_p[0])) { 1333 close(*newsock); 1334 close(startup_p[0]); 1335 close(startup_p[1]); 1336 continue; 1337 } 1338 1339 if (rexec_flag && socketpair(AF_UNIX, 1340 SOCK_STREAM, 0, config_s) == -1) { 1341 error("reexec socketpair: %s", 1342 strerror(errno)); 1343 close(*newsock); 1344 close(startup_p[0]); 1345 close(startup_p[1]); 1346 continue; 1347 } 1348 1349 for (j = 0; j < options.max_startups; j++) 1350 if (startup_pipes[j] == -1) { 1351 startup_pipes[j] = startup_p[0]; 1352 startups++; 1353 startup_flags[j] = 1; 1354 break; 1355 } 1356 1357 /* 1358 * Got connection. Fork a child to handle it, unless 1359 * we are in debugging mode. 1360 */ 1361 if (debug_flag) { 1362 /* 1363 * In debugging mode. Close the listening 1364 * socket, and start processing the 1365 * connection without forking. 1366 */ 1367 debug("Server will not fork when running in debugging mode."); 1368 close_listen_socks(); 1369 *sock_in = *newsock; 1370 *sock_out = *newsock; 1371 close(startup_p[0]); 1372 close(startup_p[1]); 1373 startup_pipe = -1; 1374 pid = getpid(); 1375 if (rexec_flag) { 1376 send_rexec_state(config_s[0], cfg); 1377 close(config_s[0]); 1378 } 1379 free(pfd); 1380 return; 1381 } 1382 1383 /* 1384 * Normal production daemon. Fork, and have 1385 * the child process the connection. The 1386 * parent continues listening. 1387 */ 1388 platform_pre_fork(); 1389 listening++; 1390 if ((pid = fork()) == 0) { 1391 /* 1392 * Child. Close the listening and 1393 * max_startup sockets. Start using 1394 * the accepted socket. Reinitialize 1395 * logging (since our pid has changed). 1396 * We return from this function to handle 1397 * the connection. 1398 */ 1399 platform_post_fork_child(); 1400 startup_pipe = startup_p[1]; 1401 close_startup_pipes(); 1402 close_listen_socks(); 1403 *sock_in = *newsock; 1404 *sock_out = *newsock; 1405 log_init(__progname, 1406 options.log_level, 1407 options.log_facility, 1408 log_stderr); 1409 if (rexec_flag) 1410 close(config_s[0]); 1411 else { 1412 /* 1413 * Signal parent that the preliminaries 1414 * for this child are complete. For the 1415 * re-exec case, this happens after the 1416 * child has received the rexec state 1417 * from the server. 1418 */ 1419 (void)atomicio(vwrite, startup_pipe, 1420 "\0", 1); 1421 } 1422 free(pfd); 1423 return; 1424 } 1425 1426 /* Parent. Stay in the loop. */ 1427 platform_post_fork_parent(pid); 1428 if (pid == -1) 1429 error("fork: %.100s", strerror(errno)); 1430 else 1431 debug("Forked child %ld.", (long)pid); 1432 1433 close(startup_p[1]); 1434 1435 if (rexec_flag) { 1436 close(config_s[1]); 1437 send_rexec_state(config_s[0], cfg); 1438 close(config_s[0]); 1439 } 1440 close(*newsock); 1441 1442 /* 1443 * Ensure that our random state differs 1444 * from that of the child 1445 */ 1446 arc4random_stir(); 1447 arc4random_buf(rnd, sizeof(rnd)); 1448 #ifdef WITH_OPENSSL 1449 RAND_seed(rnd, sizeof(rnd)); 1450 if ((RAND_bytes((u_char *)rnd, 1)) != 1) 1451 fatal("%s: RAND_bytes failed", __func__); 1452 #endif 1453 explicit_bzero(rnd, sizeof(rnd)); 1454 } 1455 } 1456 } 1457 1458 /* 1459 * If IP options are supported, make sure there are none (log and 1460 * return an error if any are found). Basically we are worried about 1461 * source routing; it can be used to pretend you are somebody 1462 * (ip-address) you are not. That itself may be "almost acceptable" 1463 * under certain circumstances, but rhosts authentication is useless 1464 * if source routing is accepted. Notice also that if we just dropped 1465 * source routing here, the other side could use IP spoofing to do 1466 * rest of the interaction and could still bypass security. So we 1467 * exit here if we detect any IP options. 1468 */ 1469 static void 1470 check_ip_options(struct ssh *ssh) 1471 { 1472 #ifdef IP_OPTIONS 1473 int sock_in = ssh_packet_get_connection_in(ssh); 1474 struct sockaddr_storage from; 1475 u_char opts[200]; 1476 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from); 1477 char text[sizeof(opts) * 3 + 1]; 1478 1479 memset(&from, 0, sizeof(from)); 1480 if (getpeername(sock_in, (struct sockaddr *)&from, 1481 &fromlen) == -1) 1482 return; 1483 if (from.ss_family != AF_INET) 1484 return; 1485 /* XXX IPv6 options? */ 1486 1487 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts, 1488 &option_size) >= 0 && option_size != 0) { 1489 text[0] = '\0'; 1490 for (i = 0; i < option_size; i++) 1491 snprintf(text + i*3, sizeof(text) - i*3, 1492 " %2.2x", opts[i]); 1493 fatal("Connection from %.100s port %d with IP opts: %.800s", 1494 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text); 1495 } 1496 return; 1497 #endif /* IP_OPTIONS */ 1498 } 1499 1500 /* Set the routing domain for this process */ 1501 static void 1502 set_process_rdomain(struct ssh *ssh, const char *name) 1503 { 1504 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN) 1505 if (name == NULL) 1506 return; /* default */ 1507 1508 if (strcmp(name, "%D") == 0) { 1509 /* "expands" to routing domain of connection */ 1510 if ((name = ssh_packet_rdomain_in(ssh)) == NULL) 1511 return; 1512 } 1513 /* NB. We don't pass 'ssh' to sys_set_process_rdomain() */ 1514 return sys_set_process_rdomain(name); 1515 #elif defined(__OpenBSD__) 1516 int rtable, ortable = getrtable(); 1517 const char *errstr; 1518 1519 if (name == NULL) 1520 return; /* default */ 1521 1522 if (strcmp(name, "%D") == 0) { 1523 /* "expands" to routing domain of connection */ 1524 if ((name = ssh_packet_rdomain_in(ssh)) == NULL) 1525 return; 1526 } 1527 1528 rtable = (int)strtonum(name, 0, 255, &errstr); 1529 if (errstr != NULL) /* Shouldn't happen */ 1530 fatal("Invalid routing domain \"%s\": %s", name, errstr); 1531 if (rtable != ortable && setrtable(rtable) != 0) 1532 fatal("Unable to set routing domain %d: %s", 1533 rtable, strerror(errno)); 1534 debug_f("set routing domain %d (was %d)", rtable, ortable); 1535 #else /* defined(__OpenBSD__) */ 1536 fatal("Unable to set routing domain: not supported in this platform"); 1537 #endif 1538 } 1539 1540 static void 1541 accumulate_host_timing_secret(struct sshbuf *server_cfg, 1542 struct sshkey *key) 1543 { 1544 static struct ssh_digest_ctx *ctx; 1545 u_char *hash; 1546 size_t len; 1547 struct sshbuf *buf; 1548 int r; 1549 1550 if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL) 1551 fatal_f("ssh_digest_start"); 1552 if (key == NULL) { /* finalize */ 1553 /* add server config in case we are using agent for host keys */ 1554 if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg), 1555 sshbuf_len(server_cfg)) != 0) 1556 fatal_f("ssh_digest_update"); 1557 len = ssh_digest_bytes(SSH_DIGEST_SHA512); 1558 hash = xmalloc(len); 1559 if (ssh_digest_final(ctx, hash, len) != 0) 1560 fatal_f("ssh_digest_final"); 1561 options.timing_secret = PEEK_U64(hash); 1562 freezero(hash, len); 1563 ssh_digest_free(ctx); 1564 ctx = NULL; 1565 return; 1566 } 1567 if ((buf = sshbuf_new()) == NULL) 1568 fatal_f("could not allocate buffer"); 1569 if ((r = sshkey_private_serialize(key, buf)) != 0) 1570 fatal_fr(r, "decode key"); 1571 if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0) 1572 fatal_f("ssh_digest_update"); 1573 sshbuf_reset(buf); 1574 sshbuf_free(buf); 1575 } 1576 1577 static char * 1578 prepare_proctitle(int ac, char **av) 1579 { 1580 char *ret = NULL; 1581 int i; 1582 1583 for (i = 0; i < ac; i++) 1584 xextendf(&ret, " ", "%s", av[i]); 1585 return ret; 1586 } 1587 1588 /* 1589 * Main program for the daemon. 1590 */ 1591 int 1592 main(int ac, char **av) 1593 { 1594 struct ssh *ssh = NULL; 1595 extern char *optarg; 1596 extern int optind; 1597 int r, opt, on = 1, already_daemon, remote_port; 1598 int sock_in = -1, sock_out = -1, newsock = -1; 1599 const char *remote_ip, *rdomain; 1600 char *fp, *line, *laddr, *logfile = NULL; 1601 int config_s[2] = { -1 , -1 }; 1602 u_int i, j; 1603 u_int64_t ibytes, obytes; 1604 mode_t new_umask; 1605 struct sshkey *key; 1606 struct sshkey *pubkey; 1607 int keytype; 1608 Authctxt *authctxt; 1609 struct connection_info *connection_info = NULL; 1610 1611 #ifdef HAVE_SECUREWARE 1612 (void)set_auth_parameters(ac, av); 1613 #endif 1614 __progname = ssh_get_progname(av[0]); 1615 1616 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */ 1617 saved_argc = ac; 1618 rexec_argc = ac; 1619 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv)); 1620 for (i = 0; (int)i < ac; i++) 1621 saved_argv[i] = xstrdup(av[i]); 1622 saved_argv[i] = NULL; 1623 1624 #ifndef HAVE_SETPROCTITLE 1625 /* Prepare for later setproctitle emulation */ 1626 compat_init_setproctitle(ac, av); 1627 av = saved_argv; 1628 #endif 1629 1630 if (geteuid() == 0 && setgroups(0, NULL) == -1) 1631 debug("setgroups(): %.200s", strerror(errno)); 1632 1633 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 1634 sanitise_stdfd(); 1635 1636 seed_rng(); 1637 1638 /* Initialize configuration options to their default values. */ 1639 initialize_server_options(&options); 1640 1641 /* Parse command-line arguments. */ 1642 while ((opt = getopt(ac, av, 1643 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) { 1644 switch (opt) { 1645 case '4': 1646 options.address_family = AF_INET; 1647 break; 1648 case '6': 1649 options.address_family = AF_INET6; 1650 break; 1651 case 'f': 1652 config_file_name = optarg; 1653 break; 1654 case 'c': 1655 servconf_add_hostcert("[command-line]", 0, 1656 &options, optarg); 1657 break; 1658 case 'd': 1659 if (debug_flag == 0) { 1660 debug_flag = 1; 1661 options.log_level = SYSLOG_LEVEL_DEBUG1; 1662 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) 1663 options.log_level++; 1664 break; 1665 case 'D': 1666 no_daemon_flag = 1; 1667 break; 1668 case 'E': 1669 logfile = optarg; 1670 /* FALLTHROUGH */ 1671 case 'e': 1672 log_stderr = 1; 1673 break; 1674 case 'i': 1675 inetd_flag = 1; 1676 break; 1677 case 'r': 1678 rexec_flag = 0; 1679 break; 1680 case 'R': 1681 rexeced_flag = 1; 1682 inetd_flag = 1; 1683 break; 1684 case 'Q': 1685 /* ignored */ 1686 break; 1687 case 'q': 1688 options.log_level = SYSLOG_LEVEL_QUIET; 1689 break; 1690 case 'b': 1691 /* protocol 1, ignored */ 1692 break; 1693 case 'p': 1694 options.ports_from_cmdline = 1; 1695 if (options.num_ports >= MAX_PORTS) { 1696 fprintf(stderr, "too many ports.\n"); 1697 exit(1); 1698 } 1699 options.ports[options.num_ports++] = a2port(optarg); 1700 if (options.ports[options.num_ports-1] <= 0) { 1701 fprintf(stderr, "Bad port number.\n"); 1702 exit(1); 1703 } 1704 break; 1705 case 'g': 1706 if ((options.login_grace_time = convtime(optarg)) == -1) { 1707 fprintf(stderr, "Invalid login grace time.\n"); 1708 exit(1); 1709 } 1710 break; 1711 case 'k': 1712 /* protocol 1, ignored */ 1713 break; 1714 case 'h': 1715 servconf_add_hostkey("[command-line]", 0, 1716 &options, optarg, 1); 1717 break; 1718 case 't': 1719 test_flag = 1; 1720 break; 1721 case 'T': 1722 test_flag = 2; 1723 break; 1724 case 'C': 1725 connection_info = get_connection_info(ssh, 0, 0); 1726 if (parse_server_match_testspec(connection_info, 1727 optarg) == -1) 1728 exit(1); 1729 break; 1730 case 'u': 1731 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL); 1732 if (utmp_len > HOST_NAME_MAX+1) { 1733 fprintf(stderr, "Invalid utmp length.\n"); 1734 exit(1); 1735 } 1736 break; 1737 case 'o': 1738 line = xstrdup(optarg); 1739 if (process_server_config_line(&options, line, 1740 "command-line", 0, NULL, NULL, &includes) != 0) 1741 exit(1); 1742 free(line); 1743 break; 1744 case '?': 1745 default: 1746 usage(); 1747 break; 1748 } 1749 } 1750 if (rexeced_flag || inetd_flag) 1751 rexec_flag = 0; 1752 if (!test_flag && rexec_flag && !path_absolute(av[0])) 1753 fatal("sshd re-exec requires execution with an absolute path"); 1754 if (rexeced_flag) 1755 closefrom(REEXEC_MIN_FREE_FD); 1756 else 1757 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD); 1758 1759 /* If requested, redirect the logs to the specified logfile. */ 1760 if (logfile != NULL) 1761 log_redirect_stderr_to(logfile); 1762 /* 1763 * Force logging to stderr until we have loaded the private host 1764 * key (unless started from inetd) 1765 */ 1766 log_init(__progname, 1767 options.log_level == SYSLOG_LEVEL_NOT_SET ? 1768 SYSLOG_LEVEL_INFO : options.log_level, 1769 options.log_facility == SYSLOG_FACILITY_NOT_SET ? 1770 SYSLOG_FACILITY_AUTH : options.log_facility, 1771 log_stderr || !inetd_flag || debug_flag); 1772 1773 /* 1774 * Unset KRB5CCNAME, otherwise the user's session may inherit it from 1775 * root's environment 1776 */ 1777 if (getenv("KRB5CCNAME") != NULL) 1778 (void) unsetenv("KRB5CCNAME"); 1779 1780 sensitive_data.have_ssh2_key = 0; 1781 1782 /* 1783 * If we're not doing an extended test do not silently ignore connection 1784 * test params. 1785 */ 1786 if (test_flag < 2 && connection_info != NULL) 1787 fatal("Config test connection parameter (-C) provided without " 1788 "test mode (-T)"); 1789 1790 /* Fetch our configuration */ 1791 if ((cfg = sshbuf_new()) == NULL) 1792 fatal_f("sshbuf_new failed"); 1793 if (rexeced_flag) { 1794 setproctitle("%s", "[rexeced]"); 1795 recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg); 1796 if (!debug_flag) { 1797 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD); 1798 close(REEXEC_STARTUP_PIPE_FD); 1799 /* 1800 * Signal parent that this child is at a point where 1801 * they can go away if they have a SIGHUP pending. 1802 */ 1803 (void)atomicio(vwrite, startup_pipe, "\0", 1); 1804 } 1805 } else if (strcasecmp(config_file_name, "none") != 0) 1806 load_server_config(config_file_name, cfg); 1807 1808 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name, 1809 cfg, &includes, NULL, rexeced_flag); 1810 1811 #ifdef WITH_OPENSSL 1812 if (options.moduli_file != NULL) 1813 dh_set_moduli_file(options.moduli_file); 1814 #endif 1815 1816 /* Fill in default values for those options not explicitly set. */ 1817 fill_default_server_options(&options); 1818 1819 /* Check that options are sensible */ 1820 if (options.authorized_keys_command_user == NULL && 1821 (options.authorized_keys_command != NULL && 1822 strcasecmp(options.authorized_keys_command, "none") != 0)) 1823 fatal("AuthorizedKeysCommand set without " 1824 "AuthorizedKeysCommandUser"); 1825 if (options.authorized_principals_command_user == NULL && 1826 (options.authorized_principals_command != NULL && 1827 strcasecmp(options.authorized_principals_command, "none") != 0)) 1828 fatal("AuthorizedPrincipalsCommand set without " 1829 "AuthorizedPrincipalsCommandUser"); 1830 1831 /* 1832 * Check whether there is any path through configured auth methods. 1833 * Unfortunately it is not possible to verify this generally before 1834 * daemonisation in the presence of Match block, but this catches 1835 * and warns for trivial misconfigurations that could break login. 1836 */ 1837 if (options.num_auth_methods != 0) { 1838 for (i = 0; i < options.num_auth_methods; i++) { 1839 if (auth2_methods_valid(options.auth_methods[i], 1840 1) == 0) 1841 break; 1842 } 1843 if (i >= options.num_auth_methods) 1844 fatal("AuthenticationMethods cannot be satisfied by " 1845 "enabled authentication methods"); 1846 } 1847 1848 /* Check that there are no remaining arguments. */ 1849 if (optind < ac) { 1850 fprintf(stderr, "Extra argument %s.\n", av[optind]); 1851 exit(1); 1852 } 1853 1854 debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION); 1855 1856 /* Store privilege separation user for later use if required. */ 1857 privsep_chroot = use_privsep && (getuid() == 0 || geteuid() == 0); 1858 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) { 1859 if (privsep_chroot || options.kerberos_authentication) 1860 fatal("Privilege separation user %s does not exist", 1861 SSH_PRIVSEP_USER); 1862 } else { 1863 privsep_pw = pwcopy(privsep_pw); 1864 freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd)); 1865 privsep_pw->pw_passwd = xstrdup("*"); 1866 } 1867 endpwent(); 1868 1869 /* load host keys */ 1870 sensitive_data.host_keys = xcalloc(options.num_host_key_files, 1871 sizeof(struct sshkey *)); 1872 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files, 1873 sizeof(struct sshkey *)); 1874 1875 if (options.host_key_agent) { 1876 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME)) 1877 setenv(SSH_AUTHSOCKET_ENV_NAME, 1878 options.host_key_agent, 1); 1879 if ((r = ssh_get_authentication_socket(NULL)) == 0) 1880 have_agent = 1; 1881 else 1882 error_r(r, "Could not connect to agent \"%s\"", 1883 options.host_key_agent); 1884 } 1885 1886 for (i = 0; i < options.num_host_key_files; i++) { 1887 int ll = options.host_key_file_userprovided[i] ? 1888 SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1; 1889 1890 if (options.host_key_files[i] == NULL) 1891 continue; 1892 if ((r = sshkey_load_private(options.host_key_files[i], "", 1893 &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR) 1894 do_log2_r(r, ll, "Unable to load host key \"%s\"", 1895 options.host_key_files[i]); 1896 if (sshkey_is_sk(key) && 1897 key->sk_flags & SSH_SK_USER_PRESENCE_REQD) { 1898 debug("host key %s requires user presence, ignoring", 1899 options.host_key_files[i]); 1900 key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD; 1901 } 1902 if (r == 0 && key != NULL && 1903 (r = sshkey_shield_private(key)) != 0) { 1904 do_log2_r(r, ll, "Unable to shield host key \"%s\"", 1905 options.host_key_files[i]); 1906 sshkey_free(key); 1907 key = NULL; 1908 } 1909 if ((r = sshkey_load_public(options.host_key_files[i], 1910 &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR) 1911 do_log2_r(r, ll, "Unable to load host key \"%s\"", 1912 options.host_key_files[i]); 1913 if (pubkey != NULL && key != NULL) { 1914 if (!sshkey_equal(pubkey, key)) { 1915 error("Public key for %s does not match " 1916 "private key", options.host_key_files[i]); 1917 sshkey_free(pubkey); 1918 pubkey = NULL; 1919 } 1920 } 1921 if (pubkey == NULL && key != NULL) { 1922 if ((r = sshkey_from_private(key, &pubkey)) != 0) 1923 fatal_r(r, "Could not demote key: \"%s\"", 1924 options.host_key_files[i]); 1925 } 1926 sensitive_data.host_keys[i] = key; 1927 sensitive_data.host_pubkeys[i] = pubkey; 1928 1929 if (key == NULL && pubkey != NULL && have_agent) { 1930 debug("will rely on agent for hostkey %s", 1931 options.host_key_files[i]); 1932 keytype = pubkey->type; 1933 } else if (key != NULL) { 1934 keytype = key->type; 1935 accumulate_host_timing_secret(cfg, key); 1936 } else { 1937 do_log2(ll, "Unable to load host key: %s", 1938 options.host_key_files[i]); 1939 sensitive_data.host_keys[i] = NULL; 1940 sensitive_data.host_pubkeys[i] = NULL; 1941 continue; 1942 } 1943 1944 switch (keytype) { 1945 case KEY_RSA: 1946 case KEY_DSA: 1947 case KEY_ECDSA: 1948 case KEY_ED25519: 1949 case KEY_ECDSA_SK: 1950 case KEY_ED25519_SK: 1951 case KEY_XMSS: 1952 if (have_agent || key != NULL) 1953 sensitive_data.have_ssh2_key = 1; 1954 break; 1955 } 1956 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash, 1957 SSH_FP_DEFAULT)) == NULL) 1958 fatal("sshkey_fingerprint failed"); 1959 debug("%s host key #%d: %s %s", 1960 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp); 1961 free(fp); 1962 } 1963 accumulate_host_timing_secret(cfg, NULL); 1964 if (!sensitive_data.have_ssh2_key) { 1965 logit("sshd: no hostkeys available -- exiting."); 1966 exit(1); 1967 } 1968 1969 /* 1970 * Load certificates. They are stored in an array at identical 1971 * indices to the public keys that they relate to. 1972 */ 1973 sensitive_data.host_certificates = xcalloc(options.num_host_key_files, 1974 sizeof(struct sshkey *)); 1975 for (i = 0; i < options.num_host_key_files; i++) 1976 sensitive_data.host_certificates[i] = NULL; 1977 1978 for (i = 0; i < options.num_host_cert_files; i++) { 1979 if (options.host_cert_files[i] == NULL) 1980 continue; 1981 if ((r = sshkey_load_public(options.host_cert_files[i], 1982 &key, NULL)) != 0) { 1983 error_r(r, "Could not load host certificate \"%s\"", 1984 options.host_cert_files[i]); 1985 continue; 1986 } 1987 if (!sshkey_is_cert(key)) { 1988 error("Certificate file is not a certificate: %s", 1989 options.host_cert_files[i]); 1990 sshkey_free(key); 1991 continue; 1992 } 1993 /* Find matching private key */ 1994 for (j = 0; j < options.num_host_key_files; j++) { 1995 if (sshkey_equal_public(key, 1996 sensitive_data.host_pubkeys[j])) { 1997 sensitive_data.host_certificates[j] = key; 1998 break; 1999 } 2000 } 2001 if (j >= options.num_host_key_files) { 2002 error("No matching private key for certificate: %s", 2003 options.host_cert_files[i]); 2004 sshkey_free(key); 2005 continue; 2006 } 2007 sensitive_data.host_certificates[j] = key; 2008 debug("host certificate: #%u type %d %s", j, key->type, 2009 sshkey_type(key)); 2010 } 2011 2012 if (privsep_chroot) { 2013 struct stat st; 2014 2015 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) || 2016 (S_ISDIR(st.st_mode) == 0)) 2017 fatal("Missing privilege separation directory: %s", 2018 _PATH_PRIVSEP_CHROOT_DIR); 2019 2020 #ifdef HAVE_CYGWIN 2021 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) && 2022 (st.st_uid != getuid () || 2023 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)) 2024 #else 2025 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0) 2026 #endif 2027 fatal("%s must be owned by root and not group or " 2028 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR); 2029 } 2030 2031 if (test_flag > 1) { 2032 /* 2033 * If no connection info was provided by -C then use 2034 * use a blank one that will cause no predicate to match. 2035 */ 2036 if (connection_info == NULL) 2037 connection_info = get_connection_info(ssh, 0, 0); 2038 connection_info->test = 1; 2039 parse_server_match_config(&options, &includes, connection_info); 2040 dump_config(&options); 2041 } 2042 2043 /* Configuration looks good, so exit if in test mode. */ 2044 if (test_flag) 2045 exit(0); 2046 2047 /* 2048 * Clear out any supplemental groups we may have inherited. This 2049 * prevents inadvertent creation of files with bad modes (in the 2050 * portable version at least, it's certainly possible for PAM 2051 * to create a file, and we can't control the code in every 2052 * module which might be used). 2053 */ 2054 if (setgroups(0, NULL) < 0) 2055 debug("setgroups() failed: %.200s", strerror(errno)); 2056 2057 if (rexec_flag) { 2058 if (rexec_argc < 0) 2059 fatal("rexec_argc %d < 0", rexec_argc); 2060 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *)); 2061 for (i = 0; i < (u_int)rexec_argc; i++) { 2062 debug("rexec_argv[%d]='%s'", i, saved_argv[i]); 2063 rexec_argv[i] = saved_argv[i]; 2064 } 2065 rexec_argv[rexec_argc] = "-R"; 2066 rexec_argv[rexec_argc + 1] = NULL; 2067 } 2068 listener_proctitle = prepare_proctitle(ac, av); 2069 2070 /* Ensure that umask disallows at least group and world write */ 2071 new_umask = umask(0077) | 0022; 2072 (void) umask(new_umask); 2073 2074 /* Initialize the log (it is reinitialized below in case we forked). */ 2075 if (debug_flag && (!inetd_flag || rexeced_flag)) 2076 log_stderr = 1; 2077 log_init(__progname, options.log_level, 2078 options.log_facility, log_stderr); 2079 for (i = 0; i < options.num_log_verbose; i++) 2080 log_verbose_add(options.log_verbose[i]); 2081 2082 /* 2083 * If not in debugging mode, not started from inetd and not already 2084 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling 2085 * terminal, and fork. The original process exits. 2086 */ 2087 already_daemon = daemonized(); 2088 if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) { 2089 2090 if (daemon(0, 0) == -1) 2091 fatal("daemon() failed: %.200s", strerror(errno)); 2092 2093 disconnect_controlling_tty(); 2094 } 2095 /* Reinitialize the log (because of the fork above). */ 2096 log_init(__progname, options.log_level, options.log_facility, log_stderr); 2097 2098 #ifdef LIBWRAP 2099 /* 2100 * We log refusals ourselves. However, libwrap will report 2101 * syntax errors in hosts.allow via syslog(3). 2102 */ 2103 allow_severity = options.log_facility|LOG_INFO; 2104 deny_severity = options.log_facility|LOG_WARNING; 2105 #endif 2106 /* Avoid killing the process in high-pressure swapping environments. */ 2107 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0) 2108 debug("madvise(): %.200s", strerror(errno)); 2109 2110 /* 2111 * Chdir to the root directory so that the current disk can be 2112 * unmounted if desired. 2113 */ 2114 if (chdir("/") == -1) 2115 error("chdir(\"/\"): %s", strerror(errno)); 2116 2117 /* ignore SIGPIPE */ 2118 ssh_signal(SIGPIPE, SIG_IGN); 2119 2120 /* Get a connection, either from inetd or a listening TCP socket */ 2121 if (inetd_flag) { 2122 server_accept_inetd(&sock_in, &sock_out); 2123 } else { 2124 platform_pre_listen(); 2125 server_listen(); 2126 2127 ssh_signal(SIGHUP, sighup_handler); 2128 ssh_signal(SIGCHLD, main_sigchld_handler); 2129 ssh_signal(SIGTERM, sigterm_handler); 2130 ssh_signal(SIGQUIT, sigterm_handler); 2131 2132 /* 2133 * Write out the pid file after the sigterm handler 2134 * is setup and the listen sockets are bound 2135 */ 2136 if (options.pid_file != NULL && !debug_flag) { 2137 FILE *f = fopen(options.pid_file, "w"); 2138 2139 if (f == NULL) { 2140 error("Couldn't create pid file \"%s\": %s", 2141 options.pid_file, strerror(errno)); 2142 } else { 2143 fprintf(f, "%ld\n", (long) getpid()); 2144 fclose(f); 2145 } 2146 } 2147 2148 /* Accept a connection and return in a forked child */ 2149 server_accept_loop(&sock_in, &sock_out, 2150 &newsock, config_s); 2151 } 2152 2153 /* This is the child processing a new connection. */ 2154 setproctitle("%s", "[accepted]"); 2155 2156 /* 2157 * Create a new session and process group since the 4.4BSD 2158 * setlogin() affects the entire process group. We don't 2159 * want the child to be able to affect the parent. 2160 */ 2161 if (!debug_flag && !inetd_flag && setsid() == -1) 2162 error("setsid: %.100s", strerror(errno)); 2163 2164 if (rexec_flag) { 2165 debug("rexec start in %d out %d newsock %d pipe %d sock %d", 2166 sock_in, sock_out, newsock, startup_pipe, config_s[0]); 2167 dup2(newsock, STDIN_FILENO); 2168 dup2(STDIN_FILENO, STDOUT_FILENO); 2169 if (startup_pipe == -1) 2170 close(REEXEC_STARTUP_PIPE_FD); 2171 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) { 2172 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD); 2173 close(startup_pipe); 2174 startup_pipe = REEXEC_STARTUP_PIPE_FD; 2175 } 2176 2177 dup2(config_s[1], REEXEC_CONFIG_PASS_FD); 2178 close(config_s[1]); 2179 2180 ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */ 2181 execv(rexec_argv[0], rexec_argv); 2182 2183 /* Reexec has failed, fall back and continue */ 2184 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno)); 2185 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL); 2186 log_init(__progname, options.log_level, 2187 options.log_facility, log_stderr); 2188 2189 /* Clean up fds */ 2190 close(REEXEC_CONFIG_PASS_FD); 2191 newsock = sock_out = sock_in = dup(STDIN_FILENO); 2192 if (stdfd_devnull(1, 1, 0) == -1) 2193 error_f("stdfd_devnull failed"); 2194 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d", 2195 sock_in, sock_out, newsock, startup_pipe, config_s[0]); 2196 } 2197 2198 /* Executed child processes don't need these. */ 2199 fcntl(sock_out, F_SETFD, FD_CLOEXEC); 2200 fcntl(sock_in, F_SETFD, FD_CLOEXEC); 2201 2202 /* We will not restart on SIGHUP since it no longer makes sense. */ 2203 ssh_signal(SIGALRM, SIG_DFL); 2204 ssh_signal(SIGHUP, SIG_DFL); 2205 ssh_signal(SIGTERM, SIG_DFL); 2206 ssh_signal(SIGQUIT, SIG_DFL); 2207 ssh_signal(SIGCHLD, SIG_DFL); 2208 ssh_signal(SIGINT, SIG_DFL); 2209 2210 #ifdef __FreeBSD__ 2211 /* 2212 * Initialize the resolver. This may not happen automatically 2213 * before privsep chroot(). 2214 */ 2215 if ((_res.options & RES_INIT) == 0) { 2216 debug("res_init()"); 2217 res_init(); 2218 } 2219 #ifdef GSSAPI 2220 /* 2221 * Force GSS-API to parse its configuration and load any 2222 * mechanism plugins. 2223 */ 2224 { 2225 gss_OID_set mechs; 2226 OM_uint32 minor_status; 2227 gss_indicate_mechs(&minor_status, &mechs); 2228 gss_release_oid_set(&minor_status, &mechs); 2229 } 2230 #endif 2231 #endif 2232 2233 /* 2234 * Register our connection. This turns encryption off because we do 2235 * not have a key. 2236 */ 2237 if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL) 2238 fatal("Unable to create connection"); 2239 the_active_state = ssh; 2240 ssh_packet_set_server(ssh); 2241 2242 check_ip_options(ssh); 2243 2244 /* Prepare the channels layer */ 2245 channel_init_channels(ssh); 2246 channel_set_af(ssh, options.address_family); 2247 process_permitopen(ssh, &options); 2248 2249 /* Set SO_KEEPALIVE if requested. */ 2250 if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) && 2251 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1) 2252 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno)); 2253 2254 if ((remote_port = ssh_remote_port(ssh)) < 0) { 2255 debug("ssh_remote_port failed"); 2256 cleanup_exit(255); 2257 } 2258 2259 if (options.routing_domain != NULL) 2260 set_process_rdomain(ssh, options.routing_domain); 2261 2262 /* 2263 * The rest of the code depends on the fact that 2264 * ssh_remote_ipaddr() caches the remote ip, even if 2265 * the socket goes away. 2266 */ 2267 remote_ip = ssh_remote_ipaddr(ssh); 2268 2269 #ifdef HAVE_LOGIN_CAP 2270 /* Also caches remote hostname for sandboxed child. */ 2271 auth_get_canonical_hostname(ssh, options.use_dns); 2272 #endif 2273 2274 #ifdef SSH_AUDIT_EVENTS 2275 audit_connection_from(remote_ip, remote_port); 2276 #endif 2277 2278 rdomain = ssh_packet_rdomain_in(ssh); 2279 2280 /* Log the connection. */ 2281 laddr = get_local_ipaddr(sock_in); 2282 verbose("Connection from %s port %d on %s port %d%s%s%s", 2283 remote_ip, remote_port, laddr, ssh_local_port(ssh), 2284 rdomain == NULL ? "" : " rdomain \"", 2285 rdomain == NULL ? "" : rdomain, 2286 rdomain == NULL ? "" : "\""); 2287 free(laddr); 2288 2289 /* 2290 * We don't want to listen forever unless the other side 2291 * successfully authenticates itself. So we set up an alarm which is 2292 * cleared after successful authentication. A limit of zero 2293 * indicates no limit. Note that we don't set the alarm in debugging 2294 * mode; it is just annoying to have the server exit just when you 2295 * are about to discover the bug. 2296 */ 2297 ssh_signal(SIGALRM, grace_alarm_handler); 2298 if (!debug_flag) 2299 alarm(options.login_grace_time); 2300 2301 if ((r = kex_exchange_identification(ssh, -1, 2302 options.version_addendum)) != 0) 2303 sshpkt_fatal(ssh, r, "banner exchange"); 2304 2305 ssh_packet_set_nonblocking(ssh); 2306 2307 /* allocate authentication context */ 2308 authctxt = xcalloc(1, sizeof(*authctxt)); 2309 ssh->authctxt = authctxt; 2310 2311 authctxt->loginmsg = loginmsg; 2312 2313 /* XXX global for cleanup, access from other modules */ 2314 the_authctxt = authctxt; 2315 2316 /* Set default key authentication options */ 2317 if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL) 2318 fatal("allocation failed"); 2319 2320 /* prepare buffer to collect messages to display to user after login */ 2321 if ((loginmsg = sshbuf_new()) == NULL) 2322 fatal_f("sshbuf_new failed"); 2323 auth_debug_reset(); 2324 2325 BLACKLIST_INIT(); 2326 2327 if (use_privsep) { 2328 if (privsep_preauth(ssh) == 1) 2329 goto authenticated; 2330 } else if (have_agent) { 2331 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) { 2332 error_r(r, "Unable to get agent socket"); 2333 have_agent = 0; 2334 } 2335 } 2336 2337 /* perform the key exchange */ 2338 /* authenticate user and start session */ 2339 do_ssh2_kex(ssh); 2340 do_authentication2(ssh); 2341 2342 /* 2343 * If we use privilege separation, the unprivileged child transfers 2344 * the current keystate and exits 2345 */ 2346 if (use_privsep) { 2347 mm_send_keystate(ssh, pmonitor); 2348 ssh_packet_clear_keys(ssh); 2349 exit(0); 2350 } 2351 2352 authenticated: 2353 /* 2354 * Cancel the alarm we set to limit the time taken for 2355 * authentication. 2356 */ 2357 alarm(0); 2358 ssh_signal(SIGALRM, SIG_DFL); 2359 authctxt->authenticated = 1; 2360 if (startup_pipe != -1) { 2361 close(startup_pipe); 2362 startup_pipe = -1; 2363 } 2364 2365 #ifdef SSH_AUDIT_EVENTS 2366 audit_event(ssh, SSH_AUTH_SUCCESS); 2367 #endif 2368 2369 #ifdef GSSAPI 2370 if (options.gss_authentication) { 2371 temporarily_use_uid(authctxt->pw); 2372 ssh_gssapi_storecreds(); 2373 restore_uid(); 2374 } 2375 #endif 2376 #ifdef USE_PAM 2377 if (options.use_pam) { 2378 do_pam_setcred(1); 2379 do_pam_session(ssh); 2380 } 2381 #endif 2382 2383 /* 2384 * In privilege separation, we fork another child and prepare 2385 * file descriptor passing. 2386 */ 2387 if (use_privsep) { 2388 privsep_postauth(ssh, authctxt); 2389 /* the monitor process [priv] will not return */ 2390 } 2391 2392 ssh_packet_set_timeout(ssh, options.client_alive_interval, 2393 options.client_alive_count_max); 2394 2395 /* Try to send all our hostkeys to the client */ 2396 notify_hostkeys(ssh); 2397 2398 /* Start session. */ 2399 do_authenticated(ssh, authctxt); 2400 2401 /* The connection has been terminated. */ 2402 ssh_packet_get_bytes(ssh, &ibytes, &obytes); 2403 verbose("Transferred: sent %llu, received %llu bytes", 2404 (unsigned long long)obytes, (unsigned long long)ibytes); 2405 2406 verbose("Closing connection to %.500s port %d", remote_ip, remote_port); 2407 2408 #ifdef USE_PAM 2409 if (options.use_pam) 2410 finish_pam(); 2411 #endif /* USE_PAM */ 2412 2413 #ifdef SSH_AUDIT_EVENTS 2414 PRIVSEP(audit_event(ssh, SSH_CONNECTION_CLOSE)); 2415 #endif 2416 2417 ssh_packet_close(ssh); 2418 2419 if (use_privsep) 2420 mm_terminate(); 2421 2422 exit(0); 2423 } 2424 2425 int 2426 sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey, 2427 struct sshkey *pubkey, u_char **signature, size_t *slenp, 2428 const u_char *data, size_t dlen, const char *alg) 2429 { 2430 int r; 2431 2432 if (use_privsep) { 2433 if (privkey) { 2434 if (mm_sshkey_sign(ssh, privkey, signature, slenp, 2435 data, dlen, alg, options.sk_provider, NULL, 2436 ssh->compat) < 0) 2437 fatal_f("privkey sign failed"); 2438 } else { 2439 if (mm_sshkey_sign(ssh, pubkey, signature, slenp, 2440 data, dlen, alg, options.sk_provider, NULL, 2441 ssh->compat) < 0) 2442 fatal_f("pubkey sign failed"); 2443 } 2444 } else { 2445 if (privkey) { 2446 if (sshkey_sign(privkey, signature, slenp, data, dlen, 2447 alg, options.sk_provider, NULL, ssh->compat) < 0) 2448 fatal_f("privkey sign failed"); 2449 } else { 2450 if ((r = ssh_agent_sign(auth_sock, pubkey, 2451 signature, slenp, data, dlen, alg, 2452 ssh->compat)) != 0) { 2453 fatal_fr(r, "agent sign failed"); 2454 } 2455 } 2456 } 2457 return 0; 2458 } 2459 2460 /* SSH2 key exchange */ 2461 static void 2462 do_ssh2_kex(struct ssh *ssh) 2463 { 2464 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER }; 2465 struct kex *kex; 2466 int r; 2467 2468 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(ssh, 2469 options.kex_algorithms); 2470 myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(ssh, 2471 options.ciphers); 2472 myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(ssh, 2473 options.ciphers); 2474 myproposal[PROPOSAL_MAC_ALGS_CTOS] = 2475 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs; 2476 2477 if (options.compression == COMP_NONE) { 2478 myproposal[PROPOSAL_COMP_ALGS_CTOS] = 2479 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none"; 2480 } 2481 2482 if (options.rekey_limit || options.rekey_interval) 2483 ssh_packet_set_rekey_limits(ssh, options.rekey_limit, 2484 options.rekey_interval); 2485 2486 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal( 2487 ssh, list_hostkey_types()); 2488 2489 /* start key exchange */ 2490 if ((r = kex_setup(ssh, myproposal)) != 0) 2491 fatal_r(r, "kex_setup"); 2492 kex = ssh->kex; 2493 #ifdef WITH_OPENSSL 2494 kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server; 2495 kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server; 2496 kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server; 2497 kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server; 2498 kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server; 2499 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server; 2500 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server; 2501 # ifdef OPENSSL_HAS_ECC 2502 kex->kex[KEX_ECDH_SHA2] = kex_gen_server; 2503 # endif 2504 #endif 2505 kex->kex[KEX_C25519_SHA256] = kex_gen_server; 2506 kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server; 2507 kex->load_host_public_key=&get_hostkey_public_by_type; 2508 kex->load_host_private_key=&get_hostkey_private_by_type; 2509 kex->host_key_index=&get_hostkey_index; 2510 kex->sign = sshd_hostkey_sign; 2511 2512 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done); 2513 2514 #ifdef DEBUG_KEXDH 2515 /* send 1st encrypted/maced/compressed message */ 2516 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 || 2517 (r = sshpkt_put_cstring(ssh, "markus")) != 0 || 2518 (r = sshpkt_send(ssh)) != 0 || 2519 (r = ssh_packet_write_wait(ssh)) != 0) 2520 fatal_fr(r, "send test"); 2521 #endif 2522 debug("KEX done"); 2523 } 2524 2525 /* server specific fatal cleanup */ 2526 void 2527 cleanup_exit(int i) 2528 { 2529 if (the_active_state != NULL && the_authctxt != NULL) { 2530 do_cleanup(the_active_state, the_authctxt); 2531 if (use_privsep && privsep_is_preauth && 2532 pmonitor != NULL && pmonitor->m_pid > 1) { 2533 debug("Killing privsep child %d", pmonitor->m_pid); 2534 if (kill(pmonitor->m_pid, SIGKILL) != 0 && 2535 errno != ESRCH) { 2536 error_f("kill(%d): %s", pmonitor->m_pid, 2537 strerror(errno)); 2538 } 2539 } 2540 } 2541 #ifdef SSH_AUDIT_EVENTS 2542 /* done after do_cleanup so it can cancel the PAM auth 'thread' */ 2543 if (the_active_state != NULL && (!use_privsep || mm_is_monitor())) 2544 audit_event(the_active_state, SSH_CONNECTION_ABANDON); 2545 #endif 2546 _exit(i); 2547 } 2548