1 /* $OpenBSD: sshd.c,v 1.591 2022/09/17 10:34:29 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 close(*newsock); 1329 continue; 1330 } 1331 if (pipe(startup_p) == -1) { 1332 error_f("pipe(startup_p): %s", strerror(errno)); 1333 close(*newsock); 1334 continue; 1335 } 1336 if (drop_connection(*newsock, startups, startup_p[0])) { 1337 close(*newsock); 1338 close(startup_p[0]); 1339 close(startup_p[1]); 1340 continue; 1341 } 1342 1343 if (rexec_flag && socketpair(AF_UNIX, 1344 SOCK_STREAM, 0, config_s) == -1) { 1345 error("reexec socketpair: %s", 1346 strerror(errno)); 1347 close(*newsock); 1348 close(startup_p[0]); 1349 close(startup_p[1]); 1350 continue; 1351 } 1352 1353 for (j = 0; j < options.max_startups; j++) 1354 if (startup_pipes[j] == -1) { 1355 startup_pipes[j] = startup_p[0]; 1356 startups++; 1357 startup_flags[j] = 1; 1358 break; 1359 } 1360 1361 /* 1362 * Got connection. Fork a child to handle it, unless 1363 * we are in debugging mode. 1364 */ 1365 if (debug_flag) { 1366 /* 1367 * In debugging mode. Close the listening 1368 * socket, and start processing the 1369 * connection without forking. 1370 */ 1371 debug("Server will not fork when running in debugging mode."); 1372 close_listen_socks(); 1373 *sock_in = *newsock; 1374 *sock_out = *newsock; 1375 close(startup_p[0]); 1376 close(startup_p[1]); 1377 startup_pipe = -1; 1378 pid = getpid(); 1379 if (rexec_flag) { 1380 send_rexec_state(config_s[0], cfg); 1381 close(config_s[0]); 1382 } 1383 free(pfd); 1384 return; 1385 } 1386 1387 /* 1388 * Normal production daemon. Fork, and have 1389 * the child process the connection. The 1390 * parent continues listening. 1391 */ 1392 platform_pre_fork(); 1393 listening++; 1394 if ((pid = fork()) == 0) { 1395 /* 1396 * Child. Close the listening and 1397 * max_startup sockets. Start using 1398 * the accepted socket. Reinitialize 1399 * logging (since our pid has changed). 1400 * We return from this function to handle 1401 * the connection. 1402 */ 1403 platform_post_fork_child(); 1404 startup_pipe = startup_p[1]; 1405 close_startup_pipes(); 1406 close_listen_socks(); 1407 *sock_in = *newsock; 1408 *sock_out = *newsock; 1409 log_init(__progname, 1410 options.log_level, 1411 options.log_facility, 1412 log_stderr); 1413 if (rexec_flag) 1414 close(config_s[0]); 1415 else { 1416 /* 1417 * Signal parent that the preliminaries 1418 * for this child are complete. For the 1419 * re-exec case, this happens after the 1420 * child has received the rexec state 1421 * from the server. 1422 */ 1423 (void)atomicio(vwrite, startup_pipe, 1424 "\0", 1); 1425 } 1426 free(pfd); 1427 return; 1428 } 1429 1430 /* Parent. Stay in the loop. */ 1431 platform_post_fork_parent(pid); 1432 if (pid == -1) 1433 error("fork: %.100s", strerror(errno)); 1434 else 1435 debug("Forked child %ld.", (long)pid); 1436 1437 close(startup_p[1]); 1438 1439 if (rexec_flag) { 1440 close(config_s[1]); 1441 send_rexec_state(config_s[0], cfg); 1442 close(config_s[0]); 1443 } 1444 close(*newsock); 1445 1446 /* 1447 * Ensure that our random state differs 1448 * from that of the child 1449 */ 1450 arc4random_stir(); 1451 arc4random_buf(rnd, sizeof(rnd)); 1452 #ifdef WITH_OPENSSL 1453 RAND_seed(rnd, sizeof(rnd)); 1454 if ((RAND_bytes((u_char *)rnd, 1)) != 1) 1455 fatal("%s: RAND_bytes failed", __func__); 1456 #endif 1457 explicit_bzero(rnd, sizeof(rnd)); 1458 } 1459 } 1460 } 1461 1462 /* 1463 * If IP options are supported, make sure there are none (log and 1464 * return an error if any are found). Basically we are worried about 1465 * source routing; it can be used to pretend you are somebody 1466 * (ip-address) you are not. That itself may be "almost acceptable" 1467 * under certain circumstances, but rhosts authentication is useless 1468 * if source routing is accepted. Notice also that if we just dropped 1469 * source routing here, the other side could use IP spoofing to do 1470 * rest of the interaction and could still bypass security. So we 1471 * exit here if we detect any IP options. 1472 */ 1473 static void 1474 check_ip_options(struct ssh *ssh) 1475 { 1476 #ifdef IP_OPTIONS 1477 int sock_in = ssh_packet_get_connection_in(ssh); 1478 struct sockaddr_storage from; 1479 u_char opts[200]; 1480 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from); 1481 char text[sizeof(opts) * 3 + 1]; 1482 1483 memset(&from, 0, sizeof(from)); 1484 if (getpeername(sock_in, (struct sockaddr *)&from, 1485 &fromlen) == -1) 1486 return; 1487 if (from.ss_family != AF_INET) 1488 return; 1489 /* XXX IPv6 options? */ 1490 1491 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts, 1492 &option_size) >= 0 && option_size != 0) { 1493 text[0] = '\0'; 1494 for (i = 0; i < option_size; i++) 1495 snprintf(text + i*3, sizeof(text) - i*3, 1496 " %2.2x", opts[i]); 1497 fatal("Connection from %.100s port %d with IP opts: %.800s", 1498 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text); 1499 } 1500 return; 1501 #endif /* IP_OPTIONS */ 1502 } 1503 1504 /* Set the routing domain for this process */ 1505 static void 1506 set_process_rdomain(struct ssh *ssh, const char *name) 1507 { 1508 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN) 1509 if (name == NULL) 1510 return; /* default */ 1511 1512 if (strcmp(name, "%D") == 0) { 1513 /* "expands" to routing domain of connection */ 1514 if ((name = ssh_packet_rdomain_in(ssh)) == NULL) 1515 return; 1516 } 1517 /* NB. We don't pass 'ssh' to sys_set_process_rdomain() */ 1518 return sys_set_process_rdomain(name); 1519 #elif defined(__OpenBSD__) 1520 int rtable, ortable = getrtable(); 1521 const char *errstr; 1522 1523 if (name == NULL) 1524 return; /* default */ 1525 1526 if (strcmp(name, "%D") == 0) { 1527 /* "expands" to routing domain of connection */ 1528 if ((name = ssh_packet_rdomain_in(ssh)) == NULL) 1529 return; 1530 } 1531 1532 rtable = (int)strtonum(name, 0, 255, &errstr); 1533 if (errstr != NULL) /* Shouldn't happen */ 1534 fatal("Invalid routing domain \"%s\": %s", name, errstr); 1535 if (rtable != ortable && setrtable(rtable) != 0) 1536 fatal("Unable to set routing domain %d: %s", 1537 rtable, strerror(errno)); 1538 debug_f("set routing domain %d (was %d)", rtable, ortable); 1539 #else /* defined(__OpenBSD__) */ 1540 fatal("Unable to set routing domain: not supported in this platform"); 1541 #endif 1542 } 1543 1544 static void 1545 accumulate_host_timing_secret(struct sshbuf *server_cfg, 1546 struct sshkey *key) 1547 { 1548 static struct ssh_digest_ctx *ctx; 1549 u_char *hash; 1550 size_t len; 1551 struct sshbuf *buf; 1552 int r; 1553 1554 if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL) 1555 fatal_f("ssh_digest_start"); 1556 if (key == NULL) { /* finalize */ 1557 /* add server config in case we are using agent for host keys */ 1558 if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg), 1559 sshbuf_len(server_cfg)) != 0) 1560 fatal_f("ssh_digest_update"); 1561 len = ssh_digest_bytes(SSH_DIGEST_SHA512); 1562 hash = xmalloc(len); 1563 if (ssh_digest_final(ctx, hash, len) != 0) 1564 fatal_f("ssh_digest_final"); 1565 options.timing_secret = PEEK_U64(hash); 1566 freezero(hash, len); 1567 ssh_digest_free(ctx); 1568 ctx = NULL; 1569 return; 1570 } 1571 if ((buf = sshbuf_new()) == NULL) 1572 fatal_f("could not allocate buffer"); 1573 if ((r = sshkey_private_serialize(key, buf)) != 0) 1574 fatal_fr(r, "decode key"); 1575 if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0) 1576 fatal_f("ssh_digest_update"); 1577 sshbuf_reset(buf); 1578 sshbuf_free(buf); 1579 } 1580 1581 static char * 1582 prepare_proctitle(int ac, char **av) 1583 { 1584 char *ret = NULL; 1585 int i; 1586 1587 for (i = 0; i < ac; i++) 1588 xextendf(&ret, " ", "%s", av[i]); 1589 return ret; 1590 } 1591 1592 /* 1593 * Main program for the daemon. 1594 */ 1595 int 1596 main(int ac, char **av) 1597 { 1598 struct ssh *ssh = NULL; 1599 extern char *optarg; 1600 extern int optind; 1601 int r, opt, on = 1, already_daemon, remote_port; 1602 int sock_in = -1, sock_out = -1, newsock = -1; 1603 const char *remote_ip, *rdomain; 1604 char *fp, *line, *laddr, *logfile = NULL; 1605 int config_s[2] = { -1 , -1 }; 1606 u_int i, j; 1607 u_int64_t ibytes, obytes; 1608 mode_t new_umask; 1609 struct sshkey *key; 1610 struct sshkey *pubkey; 1611 int keytype; 1612 Authctxt *authctxt; 1613 struct connection_info *connection_info = NULL; 1614 1615 #ifdef HAVE_SECUREWARE 1616 (void)set_auth_parameters(ac, av); 1617 #endif 1618 __progname = ssh_get_progname(av[0]); 1619 1620 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */ 1621 saved_argc = ac; 1622 rexec_argc = ac; 1623 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv)); 1624 for (i = 0; (int)i < ac; i++) 1625 saved_argv[i] = xstrdup(av[i]); 1626 saved_argv[i] = NULL; 1627 1628 #ifndef HAVE_SETPROCTITLE 1629 /* Prepare for later setproctitle emulation */ 1630 compat_init_setproctitle(ac, av); 1631 av = saved_argv; 1632 #endif 1633 1634 if (geteuid() == 0 && setgroups(0, NULL) == -1) 1635 debug("setgroups(): %.200s", strerror(errno)); 1636 1637 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 1638 sanitise_stdfd(); 1639 1640 seed_rng(); 1641 1642 /* Initialize configuration options to their default values. */ 1643 initialize_server_options(&options); 1644 1645 /* Parse command-line arguments. */ 1646 while ((opt = getopt(ac, av, 1647 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) { 1648 switch (opt) { 1649 case '4': 1650 options.address_family = AF_INET; 1651 break; 1652 case '6': 1653 options.address_family = AF_INET6; 1654 break; 1655 case 'f': 1656 config_file_name = optarg; 1657 break; 1658 case 'c': 1659 servconf_add_hostcert("[command-line]", 0, 1660 &options, optarg); 1661 break; 1662 case 'd': 1663 if (debug_flag == 0) { 1664 debug_flag = 1; 1665 options.log_level = SYSLOG_LEVEL_DEBUG1; 1666 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) 1667 options.log_level++; 1668 break; 1669 case 'D': 1670 no_daemon_flag = 1; 1671 break; 1672 case 'E': 1673 logfile = optarg; 1674 /* FALLTHROUGH */ 1675 case 'e': 1676 log_stderr = 1; 1677 break; 1678 case 'i': 1679 inetd_flag = 1; 1680 break; 1681 case 'r': 1682 rexec_flag = 0; 1683 break; 1684 case 'R': 1685 rexeced_flag = 1; 1686 inetd_flag = 1; 1687 break; 1688 case 'Q': 1689 /* ignored */ 1690 break; 1691 case 'q': 1692 options.log_level = SYSLOG_LEVEL_QUIET; 1693 break; 1694 case 'b': 1695 /* protocol 1, ignored */ 1696 break; 1697 case 'p': 1698 options.ports_from_cmdline = 1; 1699 if (options.num_ports >= MAX_PORTS) { 1700 fprintf(stderr, "too many ports.\n"); 1701 exit(1); 1702 } 1703 options.ports[options.num_ports++] = a2port(optarg); 1704 if (options.ports[options.num_ports-1] <= 0) { 1705 fprintf(stderr, "Bad port number.\n"); 1706 exit(1); 1707 } 1708 break; 1709 case 'g': 1710 if ((options.login_grace_time = convtime(optarg)) == -1) { 1711 fprintf(stderr, "Invalid login grace time.\n"); 1712 exit(1); 1713 } 1714 break; 1715 case 'k': 1716 /* protocol 1, ignored */ 1717 break; 1718 case 'h': 1719 servconf_add_hostkey("[command-line]", 0, 1720 &options, optarg, 1); 1721 break; 1722 case 't': 1723 test_flag = 1; 1724 break; 1725 case 'T': 1726 test_flag = 2; 1727 break; 1728 case 'C': 1729 connection_info = get_connection_info(ssh, 0, 0); 1730 if (parse_server_match_testspec(connection_info, 1731 optarg) == -1) 1732 exit(1); 1733 break; 1734 case 'u': 1735 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL); 1736 if (utmp_len > HOST_NAME_MAX+1) { 1737 fprintf(stderr, "Invalid utmp length.\n"); 1738 exit(1); 1739 } 1740 break; 1741 case 'o': 1742 line = xstrdup(optarg); 1743 if (process_server_config_line(&options, line, 1744 "command-line", 0, NULL, NULL, &includes) != 0) 1745 exit(1); 1746 free(line); 1747 break; 1748 case '?': 1749 default: 1750 usage(); 1751 break; 1752 } 1753 } 1754 if (rexeced_flag || inetd_flag) 1755 rexec_flag = 0; 1756 if (!test_flag && rexec_flag && !path_absolute(av[0])) 1757 fatal("sshd re-exec requires execution with an absolute path"); 1758 if (rexeced_flag) 1759 closefrom(REEXEC_MIN_FREE_FD); 1760 else 1761 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD); 1762 1763 /* If requested, redirect the logs to the specified logfile. */ 1764 if (logfile != NULL) 1765 log_redirect_stderr_to(logfile); 1766 /* 1767 * Force logging to stderr until we have loaded the private host 1768 * key (unless started from inetd) 1769 */ 1770 log_init(__progname, 1771 options.log_level == SYSLOG_LEVEL_NOT_SET ? 1772 SYSLOG_LEVEL_INFO : options.log_level, 1773 options.log_facility == SYSLOG_FACILITY_NOT_SET ? 1774 SYSLOG_FACILITY_AUTH : options.log_facility, 1775 log_stderr || !inetd_flag || debug_flag); 1776 1777 /* 1778 * Unset KRB5CCNAME, otherwise the user's session may inherit it from 1779 * root's environment 1780 */ 1781 if (getenv("KRB5CCNAME") != NULL) 1782 (void) unsetenv("KRB5CCNAME"); 1783 1784 sensitive_data.have_ssh2_key = 0; 1785 1786 /* 1787 * If we're not doing an extended test do not silently ignore connection 1788 * test params. 1789 */ 1790 if (test_flag < 2 && connection_info != NULL) 1791 fatal("Config test connection parameter (-C) provided without " 1792 "test mode (-T)"); 1793 1794 /* Fetch our configuration */ 1795 if ((cfg = sshbuf_new()) == NULL) 1796 fatal_f("sshbuf_new failed"); 1797 if (rexeced_flag) { 1798 setproctitle("%s", "[rexeced]"); 1799 recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg); 1800 if (!debug_flag) { 1801 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD); 1802 close(REEXEC_STARTUP_PIPE_FD); 1803 /* 1804 * Signal parent that this child is at a point where 1805 * they can go away if they have a SIGHUP pending. 1806 */ 1807 (void)atomicio(vwrite, startup_pipe, "\0", 1); 1808 } 1809 } else if (strcasecmp(config_file_name, "none") != 0) 1810 load_server_config(config_file_name, cfg); 1811 1812 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name, 1813 cfg, &includes, NULL, rexeced_flag); 1814 1815 #ifdef WITH_OPENSSL 1816 if (options.moduli_file != NULL) 1817 dh_set_moduli_file(options.moduli_file); 1818 #endif 1819 1820 /* Fill in default values for those options not explicitly set. */ 1821 fill_default_server_options(&options); 1822 1823 /* Check that options are sensible */ 1824 if (options.authorized_keys_command_user == NULL && 1825 (options.authorized_keys_command != NULL && 1826 strcasecmp(options.authorized_keys_command, "none") != 0)) 1827 fatal("AuthorizedKeysCommand set without " 1828 "AuthorizedKeysCommandUser"); 1829 if (options.authorized_principals_command_user == NULL && 1830 (options.authorized_principals_command != NULL && 1831 strcasecmp(options.authorized_principals_command, "none") != 0)) 1832 fatal("AuthorizedPrincipalsCommand set without " 1833 "AuthorizedPrincipalsCommandUser"); 1834 1835 /* 1836 * Check whether there is any path through configured auth methods. 1837 * Unfortunately it is not possible to verify this generally before 1838 * daemonisation in the presence of Match block, but this catches 1839 * and warns for trivial misconfigurations that could break login. 1840 */ 1841 if (options.num_auth_methods != 0) { 1842 for (i = 0; i < options.num_auth_methods; i++) { 1843 if (auth2_methods_valid(options.auth_methods[i], 1844 1) == 0) 1845 break; 1846 } 1847 if (i >= options.num_auth_methods) 1848 fatal("AuthenticationMethods cannot be satisfied by " 1849 "enabled authentication methods"); 1850 } 1851 1852 /* Check that there are no remaining arguments. */ 1853 if (optind < ac) { 1854 fprintf(stderr, "Extra argument %s.\n", av[optind]); 1855 exit(1); 1856 } 1857 1858 debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION); 1859 1860 /* Store privilege separation user for later use if required. */ 1861 privsep_chroot = use_privsep && (getuid() == 0 || geteuid() == 0); 1862 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) { 1863 if (privsep_chroot || options.kerberos_authentication) 1864 fatal("Privilege separation user %s does not exist", 1865 SSH_PRIVSEP_USER); 1866 } else { 1867 privsep_pw = pwcopy(privsep_pw); 1868 freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd)); 1869 privsep_pw->pw_passwd = xstrdup("*"); 1870 } 1871 endpwent(); 1872 1873 /* load host keys */ 1874 sensitive_data.host_keys = xcalloc(options.num_host_key_files, 1875 sizeof(struct sshkey *)); 1876 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files, 1877 sizeof(struct sshkey *)); 1878 1879 if (options.host_key_agent) { 1880 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME)) 1881 setenv(SSH_AUTHSOCKET_ENV_NAME, 1882 options.host_key_agent, 1); 1883 if ((r = ssh_get_authentication_socket(NULL)) == 0) 1884 have_agent = 1; 1885 else 1886 error_r(r, "Could not connect to agent \"%s\"", 1887 options.host_key_agent); 1888 } 1889 1890 for (i = 0; i < options.num_host_key_files; i++) { 1891 int ll = options.host_key_file_userprovided[i] ? 1892 SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1; 1893 1894 if (options.host_key_files[i] == NULL) 1895 continue; 1896 if ((r = sshkey_load_private(options.host_key_files[i], "", 1897 &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR) 1898 do_log2_r(r, ll, "Unable to load host key \"%s\"", 1899 options.host_key_files[i]); 1900 if (sshkey_is_sk(key) && 1901 key->sk_flags & SSH_SK_USER_PRESENCE_REQD) { 1902 debug("host key %s requires user presence, ignoring", 1903 options.host_key_files[i]); 1904 key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD; 1905 } 1906 if (r == 0 && key != NULL && 1907 (r = sshkey_shield_private(key)) != 0) { 1908 do_log2_r(r, ll, "Unable to shield host key \"%s\"", 1909 options.host_key_files[i]); 1910 sshkey_free(key); 1911 key = NULL; 1912 } 1913 if ((r = sshkey_load_public(options.host_key_files[i], 1914 &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR) 1915 do_log2_r(r, ll, "Unable to load host key \"%s\"", 1916 options.host_key_files[i]); 1917 if (pubkey != NULL && key != NULL) { 1918 if (!sshkey_equal(pubkey, key)) { 1919 error("Public key for %s does not match " 1920 "private key", options.host_key_files[i]); 1921 sshkey_free(pubkey); 1922 pubkey = NULL; 1923 } 1924 } 1925 if (pubkey == NULL && key != NULL) { 1926 if ((r = sshkey_from_private(key, &pubkey)) != 0) 1927 fatal_r(r, "Could not demote key: \"%s\"", 1928 options.host_key_files[i]); 1929 } 1930 if (pubkey != NULL && (r = sshkey_check_rsa_length(pubkey, 1931 options.required_rsa_size)) != 0) { 1932 error_fr(r, "Host key %s", options.host_key_files[i]); 1933 sshkey_free(pubkey); 1934 sshkey_free(key); 1935 continue; 1936 } 1937 sensitive_data.host_keys[i] = key; 1938 sensitive_data.host_pubkeys[i] = pubkey; 1939 1940 if (key == NULL && pubkey != NULL && have_agent) { 1941 debug("will rely on agent for hostkey %s", 1942 options.host_key_files[i]); 1943 keytype = pubkey->type; 1944 } else if (key != NULL) { 1945 keytype = key->type; 1946 accumulate_host_timing_secret(cfg, key); 1947 } else { 1948 do_log2(ll, "Unable to load host key: %s", 1949 options.host_key_files[i]); 1950 sensitive_data.host_keys[i] = NULL; 1951 sensitive_data.host_pubkeys[i] = NULL; 1952 continue; 1953 } 1954 1955 switch (keytype) { 1956 case KEY_RSA: 1957 case KEY_DSA: 1958 case KEY_ECDSA: 1959 case KEY_ED25519: 1960 case KEY_ECDSA_SK: 1961 case KEY_ED25519_SK: 1962 case KEY_XMSS: 1963 if (have_agent || key != NULL) 1964 sensitive_data.have_ssh2_key = 1; 1965 break; 1966 } 1967 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash, 1968 SSH_FP_DEFAULT)) == NULL) 1969 fatal("sshkey_fingerprint failed"); 1970 debug("%s host key #%d: %s %s", 1971 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp); 1972 free(fp); 1973 } 1974 accumulate_host_timing_secret(cfg, NULL); 1975 if (!sensitive_data.have_ssh2_key) { 1976 logit("sshd: no hostkeys available -- exiting."); 1977 exit(1); 1978 } 1979 1980 /* 1981 * Load certificates. They are stored in an array at identical 1982 * indices to the public keys that they relate to. 1983 */ 1984 sensitive_data.host_certificates = xcalloc(options.num_host_key_files, 1985 sizeof(struct sshkey *)); 1986 for (i = 0; i < options.num_host_key_files; i++) 1987 sensitive_data.host_certificates[i] = NULL; 1988 1989 for (i = 0; i < options.num_host_cert_files; i++) { 1990 if (options.host_cert_files[i] == NULL) 1991 continue; 1992 if ((r = sshkey_load_public(options.host_cert_files[i], 1993 &key, NULL)) != 0) { 1994 error_r(r, "Could not load host certificate \"%s\"", 1995 options.host_cert_files[i]); 1996 continue; 1997 } 1998 if (!sshkey_is_cert(key)) { 1999 error("Certificate file is not a certificate: %s", 2000 options.host_cert_files[i]); 2001 sshkey_free(key); 2002 continue; 2003 } 2004 /* Find matching private key */ 2005 for (j = 0; j < options.num_host_key_files; j++) { 2006 if (sshkey_equal_public(key, 2007 sensitive_data.host_pubkeys[j])) { 2008 sensitive_data.host_certificates[j] = key; 2009 break; 2010 } 2011 } 2012 if (j >= options.num_host_key_files) { 2013 error("No matching private key for certificate: %s", 2014 options.host_cert_files[i]); 2015 sshkey_free(key); 2016 continue; 2017 } 2018 sensitive_data.host_certificates[j] = key; 2019 debug("host certificate: #%u type %d %s", j, key->type, 2020 sshkey_type(key)); 2021 } 2022 2023 if (privsep_chroot) { 2024 struct stat st; 2025 2026 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) || 2027 (S_ISDIR(st.st_mode) == 0)) 2028 fatal("Missing privilege separation directory: %s", 2029 _PATH_PRIVSEP_CHROOT_DIR); 2030 2031 #ifdef HAVE_CYGWIN 2032 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) && 2033 (st.st_uid != getuid () || 2034 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)) 2035 #else 2036 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0) 2037 #endif 2038 fatal("%s must be owned by root and not group or " 2039 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR); 2040 } 2041 2042 if (test_flag > 1) { 2043 /* 2044 * If no connection info was provided by -C then use 2045 * use a blank one that will cause no predicate to match. 2046 */ 2047 if (connection_info == NULL) 2048 connection_info = get_connection_info(ssh, 0, 0); 2049 connection_info->test = 1; 2050 parse_server_match_config(&options, &includes, connection_info); 2051 dump_config(&options); 2052 } 2053 2054 /* Configuration looks good, so exit if in test mode. */ 2055 if (test_flag) 2056 exit(0); 2057 2058 /* 2059 * Clear out any supplemental groups we may have inherited. This 2060 * prevents inadvertent creation of files with bad modes (in the 2061 * portable version at least, it's certainly possible for PAM 2062 * to create a file, and we can't control the code in every 2063 * module which might be used). 2064 */ 2065 if (setgroups(0, NULL) < 0) 2066 debug("setgroups() failed: %.200s", strerror(errno)); 2067 2068 if (rexec_flag) { 2069 if (rexec_argc < 0) 2070 fatal("rexec_argc %d < 0", rexec_argc); 2071 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *)); 2072 for (i = 0; i < (u_int)rexec_argc; i++) { 2073 debug("rexec_argv[%d]='%s'", i, saved_argv[i]); 2074 rexec_argv[i] = saved_argv[i]; 2075 } 2076 rexec_argv[rexec_argc] = "-R"; 2077 rexec_argv[rexec_argc + 1] = NULL; 2078 } 2079 listener_proctitle = prepare_proctitle(ac, av); 2080 2081 /* Ensure that umask disallows at least group and world write */ 2082 new_umask = umask(0077) | 0022; 2083 (void) umask(new_umask); 2084 2085 /* Initialize the log (it is reinitialized below in case we forked). */ 2086 if (debug_flag && (!inetd_flag || rexeced_flag)) 2087 log_stderr = 1; 2088 log_init(__progname, options.log_level, 2089 options.log_facility, log_stderr); 2090 for (i = 0; i < options.num_log_verbose; i++) 2091 log_verbose_add(options.log_verbose[i]); 2092 2093 /* 2094 * If not in debugging mode, not started from inetd and not already 2095 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling 2096 * terminal, and fork. The original process exits. 2097 */ 2098 already_daemon = daemonized(); 2099 if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) { 2100 2101 if (daemon(0, 0) == -1) 2102 fatal("daemon() failed: %.200s", strerror(errno)); 2103 2104 disconnect_controlling_tty(); 2105 } 2106 /* Reinitialize the log (because of the fork above). */ 2107 log_init(__progname, options.log_level, options.log_facility, log_stderr); 2108 2109 #ifdef LIBWRAP 2110 /* 2111 * We log refusals ourselves. However, libwrap will report 2112 * syntax errors in hosts.allow via syslog(3). 2113 */ 2114 allow_severity = options.log_facility|LOG_INFO; 2115 deny_severity = options.log_facility|LOG_WARNING; 2116 #endif 2117 /* Avoid killing the process in high-pressure swapping environments. */ 2118 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0) 2119 debug("madvise(): %.200s", strerror(errno)); 2120 2121 /* 2122 * Chdir to the root directory so that the current disk can be 2123 * unmounted if desired. 2124 */ 2125 if (chdir("/") == -1) 2126 error("chdir(\"/\"): %s", strerror(errno)); 2127 2128 /* ignore SIGPIPE */ 2129 ssh_signal(SIGPIPE, SIG_IGN); 2130 2131 /* Get a connection, either from inetd or a listening TCP socket */ 2132 if (inetd_flag) { 2133 server_accept_inetd(&sock_in, &sock_out); 2134 } else { 2135 platform_pre_listen(); 2136 server_listen(); 2137 2138 ssh_signal(SIGHUP, sighup_handler); 2139 ssh_signal(SIGCHLD, main_sigchld_handler); 2140 ssh_signal(SIGTERM, sigterm_handler); 2141 ssh_signal(SIGQUIT, sigterm_handler); 2142 2143 /* 2144 * Write out the pid file after the sigterm handler 2145 * is setup and the listen sockets are bound 2146 */ 2147 if (options.pid_file != NULL && !debug_flag) { 2148 FILE *f = fopen(options.pid_file, "w"); 2149 2150 if (f == NULL) { 2151 error("Couldn't create pid file \"%s\": %s", 2152 options.pid_file, strerror(errno)); 2153 } else { 2154 fprintf(f, "%ld\n", (long) getpid()); 2155 fclose(f); 2156 } 2157 } 2158 2159 /* Accept a connection and return in a forked child */ 2160 server_accept_loop(&sock_in, &sock_out, 2161 &newsock, config_s); 2162 } 2163 2164 /* This is the child processing a new connection. */ 2165 setproctitle("%s", "[accepted]"); 2166 2167 /* 2168 * Create a new session and process group since the 4.4BSD 2169 * setlogin() affects the entire process group. We don't 2170 * want the child to be able to affect the parent. 2171 */ 2172 if (!debug_flag && !inetd_flag && setsid() == -1) 2173 error("setsid: %.100s", strerror(errno)); 2174 2175 if (rexec_flag) { 2176 debug("rexec start in %d out %d newsock %d pipe %d sock %d", 2177 sock_in, sock_out, newsock, startup_pipe, config_s[0]); 2178 dup2(newsock, STDIN_FILENO); 2179 dup2(STDIN_FILENO, STDOUT_FILENO); 2180 if (startup_pipe == -1) 2181 close(REEXEC_STARTUP_PIPE_FD); 2182 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) { 2183 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD); 2184 close(startup_pipe); 2185 startup_pipe = REEXEC_STARTUP_PIPE_FD; 2186 } 2187 2188 dup2(config_s[1], REEXEC_CONFIG_PASS_FD); 2189 close(config_s[1]); 2190 2191 ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */ 2192 execv(rexec_argv[0], rexec_argv); 2193 2194 /* Reexec has failed, fall back and continue */ 2195 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno)); 2196 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL); 2197 log_init(__progname, options.log_level, 2198 options.log_facility, log_stderr); 2199 2200 /* Clean up fds */ 2201 close(REEXEC_CONFIG_PASS_FD); 2202 newsock = sock_out = sock_in = dup(STDIN_FILENO); 2203 if (stdfd_devnull(1, 1, 0) == -1) 2204 error_f("stdfd_devnull failed"); 2205 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d", 2206 sock_in, sock_out, newsock, startup_pipe, config_s[0]); 2207 } 2208 2209 /* Executed child processes don't need these. */ 2210 fcntl(sock_out, F_SETFD, FD_CLOEXEC); 2211 fcntl(sock_in, F_SETFD, FD_CLOEXEC); 2212 2213 /* We will not restart on SIGHUP since it no longer makes sense. */ 2214 ssh_signal(SIGALRM, SIG_DFL); 2215 ssh_signal(SIGHUP, SIG_DFL); 2216 ssh_signal(SIGTERM, SIG_DFL); 2217 ssh_signal(SIGQUIT, SIG_DFL); 2218 ssh_signal(SIGCHLD, SIG_DFL); 2219 ssh_signal(SIGINT, SIG_DFL); 2220 2221 #ifdef __FreeBSD__ 2222 /* 2223 * Initialize the resolver. This may not happen automatically 2224 * before privsep chroot(). 2225 */ 2226 if ((_res.options & RES_INIT) == 0) { 2227 debug("res_init()"); 2228 res_init(); 2229 } 2230 #ifdef GSSAPI 2231 /* 2232 * Force GSS-API to parse its configuration and load any 2233 * mechanism plugins. 2234 */ 2235 { 2236 gss_OID_set mechs; 2237 OM_uint32 minor_status; 2238 gss_indicate_mechs(&minor_status, &mechs); 2239 gss_release_oid_set(&minor_status, &mechs); 2240 } 2241 #endif 2242 #endif 2243 2244 /* 2245 * Register our connection. This turns encryption off because we do 2246 * not have a key. 2247 */ 2248 if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL) 2249 fatal("Unable to create connection"); 2250 the_active_state = ssh; 2251 ssh_packet_set_server(ssh); 2252 2253 check_ip_options(ssh); 2254 2255 /* Prepare the channels layer */ 2256 channel_init_channels(ssh); 2257 channel_set_af(ssh, options.address_family); 2258 process_permitopen(ssh, &options); 2259 2260 /* Set SO_KEEPALIVE if requested. */ 2261 if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) && 2262 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1) 2263 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno)); 2264 2265 if ((remote_port = ssh_remote_port(ssh)) < 0) { 2266 debug("ssh_remote_port failed"); 2267 cleanup_exit(255); 2268 } 2269 2270 if (options.routing_domain != NULL) 2271 set_process_rdomain(ssh, options.routing_domain); 2272 2273 /* 2274 * The rest of the code depends on the fact that 2275 * ssh_remote_ipaddr() caches the remote ip, even if 2276 * the socket goes away. 2277 */ 2278 remote_ip = ssh_remote_ipaddr(ssh); 2279 2280 #ifdef HAVE_LOGIN_CAP 2281 /* Also caches remote hostname for sandboxed child. */ 2282 auth_get_canonical_hostname(ssh, options.use_dns); 2283 #endif 2284 2285 #ifdef SSH_AUDIT_EVENTS 2286 audit_connection_from(remote_ip, remote_port); 2287 #endif 2288 2289 rdomain = ssh_packet_rdomain_in(ssh); 2290 2291 /* Log the connection. */ 2292 laddr = get_local_ipaddr(sock_in); 2293 verbose("Connection from %s port %d on %s port %d%s%s%s", 2294 remote_ip, remote_port, laddr, ssh_local_port(ssh), 2295 rdomain == NULL ? "" : " rdomain \"", 2296 rdomain == NULL ? "" : rdomain, 2297 rdomain == NULL ? "" : "\""); 2298 free(laddr); 2299 2300 /* 2301 * We don't want to listen forever unless the other side 2302 * successfully authenticates itself. So we set up an alarm which is 2303 * cleared after successful authentication. A limit of zero 2304 * indicates no limit. Note that we don't set the alarm in debugging 2305 * mode; it is just annoying to have the server exit just when you 2306 * are about to discover the bug. 2307 */ 2308 ssh_signal(SIGALRM, grace_alarm_handler); 2309 if (!debug_flag) 2310 alarm(options.login_grace_time); 2311 2312 if ((r = kex_exchange_identification(ssh, -1, 2313 options.version_addendum)) != 0) 2314 sshpkt_fatal(ssh, r, "banner exchange"); 2315 2316 ssh_packet_set_nonblocking(ssh); 2317 2318 /* allocate authentication context */ 2319 authctxt = xcalloc(1, sizeof(*authctxt)); 2320 ssh->authctxt = authctxt; 2321 2322 authctxt->loginmsg = loginmsg; 2323 2324 /* XXX global for cleanup, access from other modules */ 2325 the_authctxt = authctxt; 2326 2327 /* Set default key authentication options */ 2328 if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL) 2329 fatal("allocation failed"); 2330 2331 /* prepare buffer to collect messages to display to user after login */ 2332 if ((loginmsg = sshbuf_new()) == NULL) 2333 fatal_f("sshbuf_new failed"); 2334 auth_debug_reset(); 2335 2336 BLACKLIST_INIT(); 2337 2338 if (use_privsep) { 2339 if (privsep_preauth(ssh) == 1) 2340 goto authenticated; 2341 } else if (have_agent) { 2342 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) { 2343 error_r(r, "Unable to get agent socket"); 2344 have_agent = 0; 2345 } 2346 } 2347 2348 /* perform the key exchange */ 2349 /* authenticate user and start session */ 2350 do_ssh2_kex(ssh); 2351 do_authentication2(ssh); 2352 2353 /* 2354 * If we use privilege separation, the unprivileged child transfers 2355 * the current keystate and exits 2356 */ 2357 if (use_privsep) { 2358 mm_send_keystate(ssh, pmonitor); 2359 ssh_packet_clear_keys(ssh); 2360 exit(0); 2361 } 2362 2363 authenticated: 2364 /* 2365 * Cancel the alarm we set to limit the time taken for 2366 * authentication. 2367 */ 2368 alarm(0); 2369 ssh_signal(SIGALRM, SIG_DFL); 2370 authctxt->authenticated = 1; 2371 if (startup_pipe != -1) { 2372 close(startup_pipe); 2373 startup_pipe = -1; 2374 } 2375 2376 #ifdef SSH_AUDIT_EVENTS 2377 audit_event(ssh, SSH_AUTH_SUCCESS); 2378 #endif 2379 2380 #ifdef GSSAPI 2381 if (options.gss_authentication) { 2382 temporarily_use_uid(authctxt->pw); 2383 ssh_gssapi_storecreds(); 2384 restore_uid(); 2385 } 2386 #endif 2387 #ifdef USE_PAM 2388 if (options.use_pam) { 2389 do_pam_setcred(1); 2390 do_pam_session(ssh); 2391 } 2392 #endif 2393 2394 /* 2395 * In privilege separation, we fork another child and prepare 2396 * file descriptor passing. 2397 */ 2398 if (use_privsep) { 2399 privsep_postauth(ssh, authctxt); 2400 /* the monitor process [priv] will not return */ 2401 } 2402 2403 ssh_packet_set_timeout(ssh, options.client_alive_interval, 2404 options.client_alive_count_max); 2405 2406 /* Try to send all our hostkeys to the client */ 2407 notify_hostkeys(ssh); 2408 2409 /* Start session. */ 2410 do_authenticated(ssh, authctxt); 2411 2412 /* The connection has been terminated. */ 2413 ssh_packet_get_bytes(ssh, &ibytes, &obytes); 2414 verbose("Transferred: sent %llu, received %llu bytes", 2415 (unsigned long long)obytes, (unsigned long long)ibytes); 2416 2417 verbose("Closing connection to %.500s port %d", remote_ip, remote_port); 2418 2419 #ifdef USE_PAM 2420 if (options.use_pam) 2421 finish_pam(); 2422 #endif /* USE_PAM */ 2423 2424 #ifdef SSH_AUDIT_EVENTS 2425 PRIVSEP(audit_event(ssh, SSH_CONNECTION_CLOSE)); 2426 #endif 2427 2428 ssh_packet_close(ssh); 2429 2430 if (use_privsep) 2431 mm_terminate(); 2432 2433 exit(0); 2434 } 2435 2436 int 2437 sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey, 2438 struct sshkey *pubkey, u_char **signature, size_t *slenp, 2439 const u_char *data, size_t dlen, const char *alg) 2440 { 2441 int r; 2442 2443 if (use_privsep) { 2444 if (privkey) { 2445 if (mm_sshkey_sign(ssh, privkey, signature, slenp, 2446 data, dlen, alg, options.sk_provider, NULL, 2447 ssh->compat) < 0) 2448 fatal_f("privkey sign failed"); 2449 } else { 2450 if (mm_sshkey_sign(ssh, pubkey, signature, slenp, 2451 data, dlen, alg, options.sk_provider, NULL, 2452 ssh->compat) < 0) 2453 fatal_f("pubkey sign failed"); 2454 } 2455 } else { 2456 if (privkey) { 2457 if (sshkey_sign(privkey, signature, slenp, data, dlen, 2458 alg, options.sk_provider, NULL, ssh->compat) < 0) 2459 fatal_f("privkey sign failed"); 2460 } else { 2461 if ((r = ssh_agent_sign(auth_sock, pubkey, 2462 signature, slenp, data, dlen, alg, 2463 ssh->compat)) != 0) { 2464 fatal_fr(r, "agent sign failed"); 2465 } 2466 } 2467 } 2468 return 0; 2469 } 2470 2471 /* SSH2 key exchange */ 2472 static void 2473 do_ssh2_kex(struct ssh *ssh) 2474 { 2475 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER }; 2476 struct kex *kex; 2477 char *prop_kex = NULL, *prop_enc = NULL, *prop_hostkey = NULL; 2478 int r; 2479 2480 myproposal[PROPOSAL_KEX_ALGS] = prop_kex = compat_kex_proposal(ssh, 2481 options.kex_algorithms); 2482 myproposal[PROPOSAL_ENC_ALGS_CTOS] = 2483 myproposal[PROPOSAL_ENC_ALGS_STOC] = prop_enc = 2484 compat_cipher_proposal(ssh, options.ciphers); 2485 myproposal[PROPOSAL_MAC_ALGS_CTOS] = 2486 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs; 2487 2488 if (options.compression == COMP_NONE) { 2489 myproposal[PROPOSAL_COMP_ALGS_CTOS] = 2490 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none"; 2491 } 2492 2493 if (options.rekey_limit || options.rekey_interval) 2494 ssh_packet_set_rekey_limits(ssh, options.rekey_limit, 2495 options.rekey_interval); 2496 2497 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = prop_hostkey = 2498 compat_pkalg_proposal(ssh, list_hostkey_types()); 2499 2500 /* start key exchange */ 2501 if ((r = kex_setup(ssh, myproposal)) != 0) 2502 fatal_r(r, "kex_setup"); 2503 kex = ssh->kex; 2504 #ifdef WITH_OPENSSL 2505 kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server; 2506 kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server; 2507 kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server; 2508 kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server; 2509 kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server; 2510 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server; 2511 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server; 2512 # ifdef OPENSSL_HAS_ECC 2513 kex->kex[KEX_ECDH_SHA2] = kex_gen_server; 2514 # endif 2515 #endif 2516 kex->kex[KEX_C25519_SHA256] = kex_gen_server; 2517 kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server; 2518 kex->load_host_public_key=&get_hostkey_public_by_type; 2519 kex->load_host_private_key=&get_hostkey_private_by_type; 2520 kex->host_key_index=&get_hostkey_index; 2521 kex->sign = sshd_hostkey_sign; 2522 2523 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done); 2524 2525 #ifdef DEBUG_KEXDH 2526 /* send 1st encrypted/maced/compressed message */ 2527 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 || 2528 (r = sshpkt_put_cstring(ssh, "markus")) != 0 || 2529 (r = sshpkt_send(ssh)) != 0 || 2530 (r = ssh_packet_write_wait(ssh)) != 0) 2531 fatal_fr(r, "send test"); 2532 #endif 2533 free(prop_kex); 2534 free(prop_enc); 2535 free(prop_hostkey); 2536 debug("KEX done"); 2537 } 2538 2539 /* server specific fatal cleanup */ 2540 void 2541 cleanup_exit(int i) 2542 { 2543 if (the_active_state != NULL && the_authctxt != NULL) { 2544 do_cleanup(the_active_state, the_authctxt); 2545 if (use_privsep && privsep_is_preauth && 2546 pmonitor != NULL && pmonitor->m_pid > 1) { 2547 debug("Killing privsep child %d", pmonitor->m_pid); 2548 if (kill(pmonitor->m_pid, SIGKILL) != 0 && 2549 errno != ESRCH) { 2550 error_f("kill(%d): %s", pmonitor->m_pid, 2551 strerror(errno)); 2552 } 2553 } 2554 } 2555 #ifdef SSH_AUDIT_EVENTS 2556 /* done after do_cleanup so it can cancel the PAM auth 'thread' */ 2557 if (the_active_state != NULL && (!use_privsep || mm_is_monitor())) 2558 audit_event(the_active_state, SSH_CONNECTION_ABANDON); 2559 #endif 2560 _exit(i); 2561 } 2562