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