1 /* $OpenBSD: sshd.c,v 1.475 2016/08/28 22:28:12 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 <sys/types.h> 46 #include <sys/ioctl.h> 47 #include <sys/wait.h> 48 #include <sys/tree.h> 49 #include <sys/stat.h> 50 #include <sys/socket.h> 51 #include <sys/time.h> 52 #include <sys/queue.h> 53 54 #include <errno.h> 55 #include <fcntl.h> 56 #include <netdb.h> 57 #include <paths.h> 58 #include <pwd.h> 59 #include <signal.h> 60 #include <stdio.h> 61 #include <stdlib.h> 62 #include <string.h> 63 #include <unistd.h> 64 #include <limits.h> 65 66 #ifdef WITH_OPENSSL 67 #include <openssl/bn.h> 68 #endif 69 70 #include "xmalloc.h" 71 #include "ssh.h" 72 #include "ssh2.h" 73 #include "rsa.h" 74 #include "sshpty.h" 75 #include "packet.h" 76 #include "log.h" 77 #include "buffer.h" 78 #include "misc.h" 79 #include "match.h" 80 #include "servconf.h" 81 #include "uidswap.h" 82 #include "compat.h" 83 #include "cipher.h" 84 #include "digest.h" 85 #include "key.h" 86 #include "kex.h" 87 #include "myproposal.h" 88 #include "authfile.h" 89 #include "pathnames.h" 90 #include "atomicio.h" 91 #include "canohost.h" 92 #include "hostfile.h" 93 #include "auth.h" 94 #include "authfd.h" 95 #include "msg.h" 96 #include "dispatch.h" 97 #include "channels.h" 98 #include "session.h" 99 #include "monitor_mm.h" 100 #include "monitor.h" 101 #ifdef GSSAPI 102 #include "ssh-gss.h" 103 #endif 104 #include "monitor_wrap.h" 105 #include "ssh-sandbox.h" 106 #include "version.h" 107 #include "ssherr.h" 108 109 #ifndef O_NOCTTY 110 #define O_NOCTTY 0 111 #endif 112 113 /* Re-exec fds */ 114 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1) 115 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2) 116 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3) 117 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4) 118 119 extern char *__progname; 120 121 /* Server configuration options. */ 122 ServerOptions options; 123 124 /* Name of the server configuration file. */ 125 char *config_file_name = _PATH_SERVER_CONFIG_FILE; 126 127 /* 128 * Debug mode flag. This can be set on the command line. If debug 129 * mode is enabled, extra debugging output will be sent to the system 130 * log, the daemon will not go to background, and will exit after processing 131 * the first connection. 132 */ 133 int debug_flag = 0; 134 135 /* Flag indicating that the daemon should only test the configuration and keys. */ 136 int test_flag = 0; 137 138 /* Flag indicating that the daemon is being started from inetd. */ 139 int inetd_flag = 0; 140 141 /* Flag indicating that sshd should not detach and become a daemon. */ 142 int no_daemon_flag = 0; 143 144 /* debug goes to stderr unless inetd_flag is set */ 145 int log_stderr = 0; 146 147 /* Saved arguments to main(). */ 148 char **saved_argv; 149 150 /* re-exec */ 151 int rexeced_flag = 0; 152 int rexec_flag = 1; 153 int rexec_argc = 0; 154 char **rexec_argv; 155 156 /* 157 * The sockets that the server is listening; this is used in the SIGHUP 158 * signal handler. 159 */ 160 #define MAX_LISTEN_SOCKS 16 161 int listen_socks[MAX_LISTEN_SOCKS]; 162 int num_listen_socks = 0; 163 164 /* 165 * the client's version string, passed by sshd2 in compat mode. if != NULL, 166 * sshd will skip the version-number exchange 167 */ 168 char *client_version_string = NULL; 169 char *server_version_string = NULL; 170 171 /* Daemon's agent connection */ 172 int auth_sock = -1; 173 int have_agent = 0; 174 175 /* 176 * Any really sensitive data in the application is contained in this 177 * structure. The idea is that this structure could be locked into memory so 178 * that the pages do not get written into swap. However, there are some 179 * problems. The private key contains BIGNUMs, and we do not (in principle) 180 * have access to the internals of them, and locking just the structure is 181 * not very useful. Currently, memory locking is not implemented. 182 */ 183 struct { 184 Key **host_keys; /* all private host keys */ 185 Key **host_pubkeys; /* all public host keys */ 186 Key **host_certificates; /* all public host certificates */ 187 int have_ssh2_key; 188 } sensitive_data; 189 190 /* This is set to true when a signal is received. */ 191 static volatile sig_atomic_t received_sighup = 0; 192 static volatile sig_atomic_t received_sigterm = 0; 193 194 /* session identifier, used by RSA-auth */ 195 u_char session_id[16]; 196 197 /* same for ssh2 */ 198 u_char *session_id2 = NULL; 199 u_int session_id2_len = 0; 200 201 /* record remote hostname or ip */ 202 u_int utmp_len = HOST_NAME_MAX+1; 203 204 /* options.max_startup sized array of fd ints */ 205 int *startup_pipes = NULL; 206 int startup_pipe; /* in child */ 207 208 /* variables used for privilege separation */ 209 int use_privsep = -1; 210 struct monitor *pmonitor = NULL; 211 int privsep_is_preauth = 1; 212 213 /* global authentication context */ 214 Authctxt *the_authctxt = NULL; 215 216 /* sshd_config buffer */ 217 Buffer cfg; 218 219 /* message to be displayed after login */ 220 Buffer loginmsg; 221 222 /* Prototypes for various functions defined later in this file. */ 223 void destroy_sensitive_data(void); 224 void demote_sensitive_data(void); 225 static void do_ssh2_kex(void); 226 227 /* 228 * Close all listening sockets 229 */ 230 static void 231 close_listen_socks(void) 232 { 233 int i; 234 235 for (i = 0; i < num_listen_socks; i++) 236 close(listen_socks[i]); 237 num_listen_socks = -1; 238 } 239 240 static void 241 close_startup_pipes(void) 242 { 243 int i; 244 245 if (startup_pipes) 246 for (i = 0; i < options.max_startups; i++) 247 if (startup_pipes[i] != -1) 248 close(startup_pipes[i]); 249 } 250 251 /* 252 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP; 253 * the effect is to reread the configuration file (and to regenerate 254 * the server key). 255 */ 256 257 /*ARGSUSED*/ 258 static void 259 sighup_handler(int sig) 260 { 261 int save_errno = errno; 262 263 received_sighup = 1; 264 signal(SIGHUP, sighup_handler); 265 errno = save_errno; 266 } 267 268 /* 269 * Called from the main program after receiving SIGHUP. 270 * Restarts the server. 271 */ 272 static void 273 sighup_restart(void) 274 { 275 logit("Received SIGHUP; restarting."); 276 close_listen_socks(); 277 close_startup_pipes(); 278 alarm(0); /* alarm timer persists across exec */ 279 signal(SIGHUP, SIG_IGN); /* will be restored after exec */ 280 execv(saved_argv[0], saved_argv); 281 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], 282 strerror(errno)); 283 exit(1); 284 } 285 286 /* 287 * Generic signal handler for terminating signals in the master daemon. 288 */ 289 /*ARGSUSED*/ 290 static void 291 sigterm_handler(int sig) 292 { 293 received_sigterm = sig; 294 } 295 296 /* 297 * SIGCHLD handler. This is called whenever a child dies. This will then 298 * reap any zombies left by exited children. 299 */ 300 /*ARGSUSED*/ 301 static void 302 main_sigchld_handler(int sig) 303 { 304 int save_errno = errno; 305 pid_t pid; 306 int status; 307 308 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 309 (pid < 0 && errno == EINTR)) 310 ; 311 312 signal(SIGCHLD, main_sigchld_handler); 313 errno = save_errno; 314 } 315 316 /* 317 * Signal handler for the alarm after the login grace period has expired. 318 */ 319 /*ARGSUSED*/ 320 static void 321 grace_alarm_handler(int sig) 322 { 323 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0) 324 kill(pmonitor->m_pid, SIGALRM); 325 326 /* 327 * Try to kill any processes that we have spawned, E.g. authorized 328 * keys command helpers. 329 */ 330 if (getpgid(0) == getpid()) { 331 signal(SIGTERM, SIG_IGN); 332 kill(0, SIGTERM); 333 } 334 335 /* Log error and exit. */ 336 sigdie("Timeout before authentication for %s port %d", 337 ssh_remote_ipaddr(active_state), ssh_remote_port(active_state)); 338 } 339 340 static void 341 sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out) 342 { 343 u_int i; 344 int remote_major, remote_minor; 345 char *s, *newline = "\n"; 346 char buf[256]; /* Must not be larger than remote_version. */ 347 char remote_version[256]; /* Must be at least as big as buf. */ 348 349 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s", 350 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION, 351 *options.version_addendum == '\0' ? "" : " ", 352 options.version_addendum, newline); 353 354 /* Send our protocol version identification. */ 355 if (atomicio(vwrite, sock_out, server_version_string, 356 strlen(server_version_string)) 357 != strlen(server_version_string)) { 358 logit("Could not write ident string to %s port %d", 359 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 360 cleanup_exit(255); 361 } 362 363 /* Read other sides version identification. */ 364 memset(buf, 0, sizeof(buf)); 365 for (i = 0; i < sizeof(buf) - 1; i++) { 366 if (atomicio(read, sock_in, &buf[i], 1) != 1) { 367 logit("Did not receive identification string " 368 "from %s port %d", 369 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 370 cleanup_exit(255); 371 } 372 if (buf[i] == '\r') { 373 buf[i] = 0; 374 /* Kludge for F-Secure Macintosh < 1.0.2 */ 375 if (i == 12 && 376 strncmp(buf, "SSH-1.5-W1.0", 12) == 0) 377 break; 378 continue; 379 } 380 if (buf[i] == '\n') { 381 buf[i] = 0; 382 break; 383 } 384 } 385 buf[sizeof(buf) - 1] = 0; 386 client_version_string = xstrdup(buf); 387 388 /* 389 * Check that the versions match. In future this might accept 390 * several versions and set appropriate flags to handle them. 391 */ 392 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n", 393 &remote_major, &remote_minor, remote_version) != 3) { 394 s = "Protocol mismatch.\n"; 395 (void) atomicio(vwrite, sock_out, s, strlen(s)); 396 logit("Bad protocol version identification '%.100s' " 397 "from %s port %d", client_version_string, 398 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 399 close(sock_in); 400 close(sock_out); 401 cleanup_exit(255); 402 } 403 debug("Client protocol version %d.%d; client software version %.100s", 404 remote_major, remote_minor, remote_version); 405 406 ssh->compat = compat_datafellows(remote_version); 407 408 if ((ssh->compat & SSH_BUG_PROBE) != 0) { 409 logit("probed from %s port %d with %s. Don't panic.", 410 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), 411 client_version_string); 412 cleanup_exit(255); 413 } 414 if ((ssh->compat & SSH_BUG_SCANNER) != 0) { 415 logit("scanned from %s port %d with %s. Don't panic.", 416 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), 417 client_version_string); 418 cleanup_exit(255); 419 } 420 if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) { 421 logit("Client version \"%.100s\" uses unsafe RSA signature " 422 "scheme; disabling use of RSA keys", remote_version); 423 } 424 if ((ssh->compat & SSH_BUG_DERIVEKEY) != 0) { 425 fatal("Client version \"%.100s\" uses unsafe key agreement; " 426 "refusing connection", remote_version); 427 } 428 429 chop(server_version_string); 430 debug("Local version string %.200s", server_version_string); 431 432 if (remote_major == 2 || 433 (remote_major == 1 && remote_minor == 99)) { 434 enable_compat20(); 435 } else { 436 s = "Protocol major versions differ.\n"; 437 (void) atomicio(vwrite, sock_out, s, strlen(s)); 438 close(sock_in); 439 close(sock_out); 440 logit("Protocol major versions differ for %s port %d: " 441 "%.200s vs. %.200s", 442 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), 443 server_version_string, client_version_string); 444 cleanup_exit(255); 445 } 446 } 447 448 /* Destroy the host and server keys. They will no longer be needed. */ 449 void 450 destroy_sensitive_data(void) 451 { 452 int i; 453 454 for (i = 0; i < options.num_host_key_files; i++) { 455 if (sensitive_data.host_keys[i]) { 456 key_free(sensitive_data.host_keys[i]); 457 sensitive_data.host_keys[i] = NULL; 458 } 459 if (sensitive_data.host_certificates[i]) { 460 key_free(sensitive_data.host_certificates[i]); 461 sensitive_data.host_certificates[i] = NULL; 462 } 463 } 464 } 465 466 /* Demote private to public keys for network child */ 467 void 468 demote_sensitive_data(void) 469 { 470 Key *tmp; 471 int i; 472 473 for (i = 0; i < options.num_host_key_files; i++) { 474 if (sensitive_data.host_keys[i]) { 475 tmp = key_demote(sensitive_data.host_keys[i]); 476 key_free(sensitive_data.host_keys[i]); 477 sensitive_data.host_keys[i] = tmp; 478 } 479 /* Certs do not need demotion */ 480 } 481 } 482 483 static void 484 privsep_preauth_child(void) 485 { 486 gid_t gidset[1]; 487 struct passwd *pw; 488 489 /* Enable challenge-response authentication for privilege separation */ 490 privsep_challenge_enable(); 491 492 #ifdef GSSAPI 493 /* Cache supported mechanism OIDs for later use */ 494 if (options.gss_authentication) 495 ssh_gssapi_prepare_supported_oids(); 496 #endif 497 498 /* Demote the private keys to public keys. */ 499 demote_sensitive_data(); 500 501 /* Demote the child */ 502 if (getuid() == 0 || geteuid() == 0) { 503 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) 504 fatal("Privilege separation user %s does not exist", 505 SSH_PRIVSEP_USER); 506 explicit_bzero(pw->pw_passwd, strlen(pw->pw_passwd)); 507 endpwent(); 508 509 /* Change our root directory */ 510 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1) 511 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR, 512 strerror(errno)); 513 if (chdir("/") == -1) 514 fatal("chdir(\"/\"): %s", strerror(errno)); 515 516 /* 517 * Drop our privileges 518 * NB. Can't use setusercontext() after chroot. 519 */ 520 debug3("privsep user:group %u:%u", (u_int)pw->pw_uid, 521 (u_int)pw->pw_gid); 522 gidset[0] = pw->pw_gid; 523 if (setgroups(1, gidset) < 0) 524 fatal("setgroups: %.100s", strerror(errno)); 525 permanently_set_uid(pw); 526 } 527 } 528 529 static int 530 privsep_preauth(Authctxt *authctxt) 531 { 532 int status, r; 533 pid_t pid; 534 struct ssh_sandbox *box = NULL; 535 536 /* Set up unprivileged child process to deal with network data */ 537 pmonitor = monitor_init(); 538 /* Store a pointer to the kex for later rekeying */ 539 pmonitor->m_pkex = &active_state->kex; 540 541 if (use_privsep == PRIVSEP_ON) 542 box = ssh_sandbox_init(); 543 pid = fork(); 544 if (pid == -1) { 545 fatal("fork of unprivileged child failed"); 546 } else if (pid != 0) { 547 debug2("Network child is on pid %ld", (long)pid); 548 549 pmonitor->m_pid = pid; 550 if (have_agent) { 551 r = ssh_get_authentication_socket(&auth_sock); 552 if (r != 0) { 553 error("Could not get agent socket: %s", 554 ssh_err(r)); 555 have_agent = 0; 556 } 557 } 558 if (box != NULL) 559 ssh_sandbox_parent_preauth(box, pid); 560 monitor_child_preauth(authctxt, pmonitor); 561 562 /* Sync memory */ 563 monitor_sync(pmonitor); 564 565 /* Wait for the child's exit status */ 566 while (waitpid(pid, &status, 0) < 0) { 567 if (errno == EINTR) 568 continue; 569 pmonitor->m_pid = -1; 570 fatal("%s: waitpid: %s", __func__, strerror(errno)); 571 } 572 privsep_is_preauth = 0; 573 pmonitor->m_pid = -1; 574 if (WIFEXITED(status)) { 575 if (WEXITSTATUS(status) != 0) 576 fatal("%s: preauth child exited with status %d", 577 __func__, WEXITSTATUS(status)); 578 } else if (WIFSIGNALED(status)) 579 fatal("%s: preauth child terminated by signal %d", 580 __func__, WTERMSIG(status)); 581 if (box != NULL) 582 ssh_sandbox_parent_finish(box); 583 return 1; 584 } else { 585 /* child */ 586 close(pmonitor->m_sendfd); 587 close(pmonitor->m_log_recvfd); 588 589 /* Arrange for logging to be sent to the monitor */ 590 set_log_handler(mm_log_handler, pmonitor); 591 592 privsep_preauth_child(); 593 setproctitle("%s", "[net]"); 594 if (box != NULL) 595 ssh_sandbox_child(box); 596 597 return 0; 598 } 599 } 600 601 static void 602 privsep_postauth(Authctxt *authctxt) 603 { 604 if (authctxt->pw->pw_uid == 0) { 605 /* File descriptor passing is broken or root login */ 606 use_privsep = 0; 607 goto skip; 608 } 609 610 /* New socket pair */ 611 monitor_reinit(pmonitor); 612 613 pmonitor->m_pid = fork(); 614 if (pmonitor->m_pid == -1) 615 fatal("fork of unprivileged child failed"); 616 else if (pmonitor->m_pid != 0) { 617 verbose("User child is on pid %ld", (long)pmonitor->m_pid); 618 buffer_clear(&loginmsg); 619 monitor_child_postauth(pmonitor); 620 621 /* NEVERREACHED */ 622 exit(0); 623 } 624 625 /* child */ 626 627 close(pmonitor->m_sendfd); 628 pmonitor->m_sendfd = -1; 629 630 /* Demote the private keys to public keys. */ 631 demote_sensitive_data(); 632 633 /* Drop privileges */ 634 do_setusercontext(authctxt->pw); 635 636 skip: 637 /* It is safe now to apply the key state */ 638 monitor_apply_keystate(pmonitor); 639 640 /* 641 * Tell the packet layer that authentication was successful, since 642 * this information is not part of the key state. 643 */ 644 packet_set_authenticated(); 645 } 646 647 static char * 648 list_hostkey_types(void) 649 { 650 Buffer b; 651 const char *p; 652 char *ret; 653 int i; 654 Key *key; 655 656 buffer_init(&b); 657 for (i = 0; i < options.num_host_key_files; i++) { 658 key = sensitive_data.host_keys[i]; 659 if (key == NULL) 660 key = sensitive_data.host_pubkeys[i]; 661 if (key == NULL) 662 continue; 663 /* Check that the key is accepted in HostkeyAlgorithms */ 664 if (match_pattern_list(sshkey_ssh_name(key), 665 options.hostkeyalgorithms, 0) != 1) { 666 debug3("%s: %s key not permitted by HostkeyAlgorithms", 667 __func__, sshkey_ssh_name(key)); 668 continue; 669 } 670 switch (key->type) { 671 case KEY_RSA: 672 case KEY_DSA: 673 case KEY_ECDSA: 674 case KEY_ED25519: 675 if (buffer_len(&b) > 0) 676 buffer_append(&b, ",", 1); 677 p = key_ssh_name(key); 678 buffer_append(&b, p, strlen(p)); 679 680 /* for RSA we also support SHA2 signatures */ 681 if (key->type == KEY_RSA) { 682 p = ",rsa-sha2-512,rsa-sha2-256"; 683 buffer_append(&b, p, strlen(p)); 684 } 685 break; 686 } 687 /* If the private key has a cert peer, then list that too */ 688 key = sensitive_data.host_certificates[i]; 689 if (key == NULL) 690 continue; 691 switch (key->type) { 692 case KEY_RSA_CERT: 693 case KEY_DSA_CERT: 694 case KEY_ECDSA_CERT: 695 case KEY_ED25519_CERT: 696 if (buffer_len(&b) > 0) 697 buffer_append(&b, ",", 1); 698 p = key_ssh_name(key); 699 buffer_append(&b, p, strlen(p)); 700 break; 701 } 702 } 703 if ((ret = sshbuf_dup_string(&b)) == NULL) 704 fatal("%s: sshbuf_dup_string failed", __func__); 705 buffer_free(&b); 706 debug("list_hostkey_types: %s", ret); 707 return ret; 708 } 709 710 static Key * 711 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh) 712 { 713 int i; 714 Key *key; 715 716 for (i = 0; i < options.num_host_key_files; i++) { 717 switch (type) { 718 case KEY_RSA_CERT: 719 case KEY_DSA_CERT: 720 case KEY_ECDSA_CERT: 721 case KEY_ED25519_CERT: 722 key = sensitive_data.host_certificates[i]; 723 break; 724 default: 725 key = sensitive_data.host_keys[i]; 726 if (key == NULL && !need_private) 727 key = sensitive_data.host_pubkeys[i]; 728 break; 729 } 730 if (key != NULL && key->type == type && 731 (key->type != KEY_ECDSA || key->ecdsa_nid == nid)) 732 return need_private ? 733 sensitive_data.host_keys[i] : key; 734 } 735 return NULL; 736 } 737 738 Key * 739 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh) 740 { 741 return get_hostkey_by_type(type, nid, 0, ssh); 742 } 743 744 Key * 745 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh) 746 { 747 return get_hostkey_by_type(type, nid, 1, ssh); 748 } 749 750 Key * 751 get_hostkey_by_index(int ind) 752 { 753 if (ind < 0 || ind >= options.num_host_key_files) 754 return (NULL); 755 return (sensitive_data.host_keys[ind]); 756 } 757 758 Key * 759 get_hostkey_public_by_index(int ind, struct ssh *ssh) 760 { 761 if (ind < 0 || ind >= options.num_host_key_files) 762 return (NULL); 763 return (sensitive_data.host_pubkeys[ind]); 764 } 765 766 int 767 get_hostkey_index(Key *key, int compare, struct ssh *ssh) 768 { 769 int i; 770 771 for (i = 0; i < options.num_host_key_files; i++) { 772 if (key_is_cert(key)) { 773 if (key == sensitive_data.host_certificates[i] || 774 (compare && sensitive_data.host_certificates[i] && 775 sshkey_equal(key, 776 sensitive_data.host_certificates[i]))) 777 return (i); 778 } else { 779 if (key == sensitive_data.host_keys[i] || 780 (compare && sensitive_data.host_keys[i] && 781 sshkey_equal(key, sensitive_data.host_keys[i]))) 782 return (i); 783 if (key == sensitive_data.host_pubkeys[i] || 784 (compare && sensitive_data.host_pubkeys[i] && 785 sshkey_equal(key, sensitive_data.host_pubkeys[i]))) 786 return (i); 787 } 788 } 789 return (-1); 790 } 791 792 /* Inform the client of all hostkeys */ 793 static void 794 notify_hostkeys(struct ssh *ssh) 795 { 796 struct sshbuf *buf; 797 struct sshkey *key; 798 int i, nkeys, r; 799 char *fp; 800 801 /* Some clients cannot cope with the hostkeys message, skip those. */ 802 if (datafellows & SSH_BUG_HOSTKEYS) 803 return; 804 805 if ((buf = sshbuf_new()) == NULL) 806 fatal("%s: sshbuf_new", __func__); 807 for (i = nkeys = 0; i < options.num_host_key_files; i++) { 808 key = get_hostkey_public_by_index(i, ssh); 809 if (key == NULL || key->type == KEY_UNSPEC || 810 sshkey_is_cert(key)) 811 continue; 812 fp = sshkey_fingerprint(key, options.fingerprint_hash, 813 SSH_FP_DEFAULT); 814 debug3("%s: key %d: %s %s", __func__, i, 815 sshkey_ssh_name(key), fp); 816 free(fp); 817 if (nkeys == 0) { 818 packet_start(SSH2_MSG_GLOBAL_REQUEST); 819 packet_put_cstring("hostkeys-00@openssh.com"); 820 packet_put_char(0); /* want-reply */ 821 } 822 sshbuf_reset(buf); 823 if ((r = sshkey_putb(key, buf)) != 0) 824 fatal("%s: couldn't put hostkey %d: %s", 825 __func__, i, ssh_err(r)); 826 packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf)); 827 nkeys++; 828 } 829 debug3("%s: sent %d hostkeys", __func__, nkeys); 830 if (nkeys == 0) 831 fatal("%s: no hostkeys", __func__); 832 packet_send(); 833 sshbuf_free(buf); 834 } 835 836 /* 837 * returns 1 if connection should be dropped, 0 otherwise. 838 * dropping starts at connection #max_startups_begin with a probability 839 * of (max_startups_rate/100). the probability increases linearly until 840 * all connections are dropped for startups > max_startups 841 */ 842 static int 843 drop_connection(int startups) 844 { 845 int p, r; 846 847 if (startups < options.max_startups_begin) 848 return 0; 849 if (startups >= options.max_startups) 850 return 1; 851 if (options.max_startups_rate == 100) 852 return 1; 853 854 p = 100 - options.max_startups_rate; 855 p *= startups - options.max_startups_begin; 856 p /= options.max_startups - options.max_startups_begin; 857 p += options.max_startups_rate; 858 r = arc4random_uniform(100); 859 860 debug("drop_connection: p %d, r %d", p, r); 861 return (r < p) ? 1 : 0; 862 } 863 864 static void 865 usage(void) 866 { 867 fprintf(stderr, "%s, %s\n", 868 SSH_VERSION, 869 #ifdef WITH_OPENSSL 870 SSLeay_version(SSLEAY_VERSION) 871 #else 872 "without OpenSSL" 873 #endif 874 ); 875 fprintf(stderr, 876 "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n" 877 " [-E log_file] [-f config_file] [-g login_grace_time]\n" 878 " [-h host_key_file] [-o option] [-p port] [-u len]\n" 879 ); 880 exit(1); 881 } 882 883 static void 884 send_rexec_state(int fd, struct sshbuf *conf) 885 { 886 struct sshbuf *m; 887 int r; 888 889 debug3("%s: entering fd = %d config len %zu", __func__, fd, 890 sshbuf_len(conf)); 891 892 /* 893 * Protocol from reexec master to child: 894 * string configuration 895 */ 896 if ((m = sshbuf_new()) == NULL) 897 fatal("%s: sshbuf_new failed", __func__); 898 if ((r = sshbuf_put_stringb(m, conf)) != 0) 899 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 900 if (ssh_msg_send(fd, 0, m) == -1) 901 fatal("%s: ssh_msg_send failed", __func__); 902 903 sshbuf_free(m); 904 905 debug3("%s: done", __func__); 906 } 907 908 static void 909 recv_rexec_state(int fd, Buffer *conf) 910 { 911 Buffer m; 912 char *cp; 913 u_int len; 914 915 debug3("%s: entering fd = %d", __func__, fd); 916 917 buffer_init(&m); 918 919 if (ssh_msg_recv(fd, &m) == -1) 920 fatal("%s: ssh_msg_recv failed", __func__); 921 if (buffer_get_char(&m) != 0) 922 fatal("%s: rexec version mismatch", __func__); 923 924 cp = buffer_get_string(&m, &len); 925 if (conf != NULL) 926 buffer_append(conf, cp, len); 927 free(cp); 928 929 buffer_free(&m); 930 931 debug3("%s: done", __func__); 932 } 933 934 /* Accept a connection from inetd */ 935 static void 936 server_accept_inetd(int *sock_in, int *sock_out) 937 { 938 int fd; 939 940 startup_pipe = -1; 941 if (rexeced_flag) { 942 close(REEXEC_CONFIG_PASS_FD); 943 *sock_in = *sock_out = dup(STDIN_FILENO); 944 if (!debug_flag) { 945 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD); 946 close(REEXEC_STARTUP_PIPE_FD); 947 } 948 } else { 949 *sock_in = dup(STDIN_FILENO); 950 *sock_out = dup(STDOUT_FILENO); 951 } 952 /* 953 * We intentionally do not close the descriptors 0, 1, and 2 954 * as our code for setting the descriptors won't work if 955 * ttyfd happens to be one of those. 956 */ 957 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { 958 dup2(fd, STDIN_FILENO); 959 dup2(fd, STDOUT_FILENO); 960 if (!log_stderr) 961 dup2(fd, STDERR_FILENO); 962 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO)) 963 close(fd); 964 } 965 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out); 966 } 967 968 /* 969 * Listen for TCP connections 970 */ 971 static void 972 server_listen(void) 973 { 974 int ret, listen_sock, on = 1; 975 struct addrinfo *ai; 976 char ntop[NI_MAXHOST], strport[NI_MAXSERV]; 977 978 for (ai = options.listen_addrs; ai; ai = ai->ai_next) { 979 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) 980 continue; 981 if (num_listen_socks >= MAX_LISTEN_SOCKS) 982 fatal("Too many listen sockets. " 983 "Enlarge MAX_LISTEN_SOCKS"); 984 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen, 985 ntop, sizeof(ntop), strport, sizeof(strport), 986 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) { 987 error("getnameinfo failed: %.100s", 988 ssh_gai_strerror(ret)); 989 continue; 990 } 991 /* Create socket for listening. */ 992 listen_sock = socket(ai->ai_family, ai->ai_socktype, 993 ai->ai_protocol); 994 if (listen_sock < 0) { 995 /* kernel may not support ipv6 */ 996 verbose("socket: %.100s", strerror(errno)); 997 continue; 998 } 999 if (set_nonblock(listen_sock) == -1) { 1000 close(listen_sock); 1001 continue; 1002 } 1003 /* 1004 * Set socket options. 1005 * Allow local port reuse in TIME_WAIT. 1006 */ 1007 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, 1008 &on, sizeof(on)) == -1) 1009 error("setsockopt SO_REUSEADDR: %s", strerror(errno)); 1010 1011 debug("Bind to port %s on %s.", strport, ntop); 1012 1013 /* Bind the socket to the desired port. */ 1014 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) { 1015 error("Bind to port %s on %s failed: %.200s.", 1016 strport, ntop, strerror(errno)); 1017 close(listen_sock); 1018 continue; 1019 } 1020 listen_socks[num_listen_socks] = listen_sock; 1021 num_listen_socks++; 1022 1023 /* Start listening on the port. */ 1024 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0) 1025 fatal("listen on [%s]:%s: %.100s", 1026 ntop, strport, strerror(errno)); 1027 logit("Server listening on %s port %s.", ntop, strport); 1028 } 1029 freeaddrinfo(options.listen_addrs); 1030 1031 if (!num_listen_socks) 1032 fatal("Cannot bind any address."); 1033 } 1034 1035 /* 1036 * The main TCP accept loop. Note that, for the non-debug case, returns 1037 * from this function are in a forked subprocess. 1038 */ 1039 static void 1040 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s) 1041 { 1042 fd_set *fdset; 1043 int i, j, ret, maxfd; 1044 int startups = 0; 1045 int startup_p[2] = { -1 , -1 }; 1046 struct sockaddr_storage from; 1047 socklen_t fromlen; 1048 pid_t pid; 1049 1050 /* setup fd set for accept */ 1051 fdset = NULL; 1052 maxfd = 0; 1053 for (i = 0; i < num_listen_socks; i++) 1054 if (listen_socks[i] > maxfd) 1055 maxfd = listen_socks[i]; 1056 /* pipes connected to unauthenticated childs */ 1057 startup_pipes = xcalloc(options.max_startups, sizeof(int)); 1058 for (i = 0; i < options.max_startups; i++) 1059 startup_pipes[i] = -1; 1060 1061 /* 1062 * Stay listening for connections until the system crashes or 1063 * the daemon is killed with a signal. 1064 */ 1065 for (;;) { 1066 if (received_sighup) 1067 sighup_restart(); 1068 free(fdset); 1069 fdset = xcalloc(howmany(maxfd + 1, NFDBITS), 1070 sizeof(fd_mask)); 1071 1072 for (i = 0; i < num_listen_socks; i++) 1073 FD_SET(listen_socks[i], fdset); 1074 for (i = 0; i < options.max_startups; i++) 1075 if (startup_pipes[i] != -1) 1076 FD_SET(startup_pipes[i], fdset); 1077 1078 /* Wait in select until there is a connection. */ 1079 ret = select(maxfd+1, fdset, NULL, NULL, NULL); 1080 if (ret < 0 && errno != EINTR) 1081 error("select: %.100s", strerror(errno)); 1082 if (received_sigterm) { 1083 logit("Received signal %d; terminating.", 1084 (int) received_sigterm); 1085 close_listen_socks(); 1086 if (options.pid_file != NULL) 1087 unlink(options.pid_file); 1088 exit(received_sigterm == SIGTERM ? 0 : 255); 1089 } 1090 if (ret < 0) 1091 continue; 1092 1093 for (i = 0; i < options.max_startups; i++) 1094 if (startup_pipes[i] != -1 && 1095 FD_ISSET(startup_pipes[i], fdset)) { 1096 /* 1097 * the read end of the pipe is ready 1098 * if the child has closed the pipe 1099 * after successful authentication 1100 * or if the child has died 1101 */ 1102 close(startup_pipes[i]); 1103 startup_pipes[i] = -1; 1104 startups--; 1105 } 1106 for (i = 0; i < num_listen_socks; i++) { 1107 if (!FD_ISSET(listen_socks[i], fdset)) 1108 continue; 1109 fromlen = sizeof(from); 1110 *newsock = accept(listen_socks[i], 1111 (struct sockaddr *)&from, &fromlen); 1112 if (*newsock < 0) { 1113 if (errno != EINTR && errno != EWOULDBLOCK && 1114 errno != ECONNABORTED) 1115 error("accept: %.100s", 1116 strerror(errno)); 1117 if (errno == EMFILE || errno == ENFILE) 1118 usleep(100 * 1000); 1119 continue; 1120 } 1121 if (unset_nonblock(*newsock) == -1) { 1122 close(*newsock); 1123 continue; 1124 } 1125 if (drop_connection(startups) == 1) { 1126 debug("drop connection #%d", startups); 1127 close(*newsock); 1128 continue; 1129 } 1130 if (pipe(startup_p) == -1) { 1131 close(*newsock); 1132 continue; 1133 } 1134 1135 if (rexec_flag && socketpair(AF_UNIX, 1136 SOCK_STREAM, 0, config_s) == -1) { 1137 error("reexec socketpair: %s", 1138 strerror(errno)); 1139 close(*newsock); 1140 close(startup_p[0]); 1141 close(startup_p[1]); 1142 continue; 1143 } 1144 1145 for (j = 0; j < options.max_startups; j++) 1146 if (startup_pipes[j] == -1) { 1147 startup_pipes[j] = startup_p[0]; 1148 if (maxfd < startup_p[0]) 1149 maxfd = startup_p[0]; 1150 startups++; 1151 break; 1152 } 1153 1154 /* 1155 * Got connection. Fork a child to handle it, unless 1156 * we are in debugging mode. 1157 */ 1158 if (debug_flag) { 1159 /* 1160 * In debugging mode. Close the listening 1161 * socket, and start processing the 1162 * connection without forking. 1163 */ 1164 debug("Server will not fork when running in debugging mode."); 1165 close_listen_socks(); 1166 *sock_in = *newsock; 1167 *sock_out = *newsock; 1168 close(startup_p[0]); 1169 close(startup_p[1]); 1170 startup_pipe = -1; 1171 pid = getpid(); 1172 if (rexec_flag) { 1173 send_rexec_state(config_s[0], 1174 &cfg); 1175 close(config_s[0]); 1176 } 1177 break; 1178 } 1179 1180 /* 1181 * Normal production daemon. Fork, and have 1182 * the child process the connection. The 1183 * parent continues listening. 1184 */ 1185 if ((pid = fork()) == 0) { 1186 /* 1187 * Child. Close the listening and 1188 * max_startup sockets. Start using 1189 * the accepted socket. Reinitialize 1190 * logging (since our pid has changed). 1191 * We break out of the loop to handle 1192 * the connection. 1193 */ 1194 startup_pipe = startup_p[1]; 1195 close_startup_pipes(); 1196 close_listen_socks(); 1197 *sock_in = *newsock; 1198 *sock_out = *newsock; 1199 log_init(__progname, 1200 options.log_level, 1201 options.log_facility, 1202 log_stderr); 1203 if (rexec_flag) 1204 close(config_s[0]); 1205 break; 1206 } 1207 1208 /* Parent. Stay in the loop. */ 1209 if (pid < 0) 1210 error("fork: %.100s", strerror(errno)); 1211 else 1212 debug("Forked child %ld.", (long)pid); 1213 1214 close(startup_p[1]); 1215 1216 if (rexec_flag) { 1217 send_rexec_state(config_s[0], &cfg); 1218 close(config_s[0]); 1219 close(config_s[1]); 1220 } 1221 close(*newsock); 1222 } 1223 1224 /* child process check (or debug mode) */ 1225 if (num_listen_socks < 0) 1226 break; 1227 } 1228 } 1229 1230 /* 1231 * If IP options are supported, make sure there are none (log and 1232 * return an error if any are found). Basically we are worried about 1233 * source routing; it can be used to pretend you are somebody 1234 * (ip-address) you are not. That itself may be "almost acceptable" 1235 * under certain circumstances, but rhosts autentication is useless 1236 * if source routing is accepted. Notice also that if we just dropped 1237 * source routing here, the other side could use IP spoofing to do 1238 * rest of the interaction and could still bypass security. So we 1239 * exit here if we detect any IP options. 1240 */ 1241 static void 1242 check_ip_options(struct ssh *ssh) 1243 { 1244 int sock_in = ssh_packet_get_connection_in(ssh); 1245 struct sockaddr_storage from; 1246 u_char opts[200]; 1247 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from); 1248 char text[sizeof(opts) * 3 + 1]; 1249 1250 memset(&from, 0, sizeof(from)); 1251 if (getpeername(sock_in, (struct sockaddr *)&from, 1252 &fromlen) < 0) 1253 return; 1254 if (from.ss_family != AF_INET) 1255 return; 1256 /* XXX IPv6 options? */ 1257 1258 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts, 1259 &option_size) >= 0 && option_size != 0) { 1260 text[0] = '\0'; 1261 for (i = 0; i < option_size; i++) 1262 snprintf(text + i*3, sizeof(text) - i*3, 1263 " %2.2x", opts[i]); 1264 fatal("Connection from %.100s port %d with IP opts: %.800s", 1265 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text); 1266 } 1267 return; 1268 } 1269 1270 /* 1271 * Main program for the daemon. 1272 */ 1273 int 1274 main(int ac, char **av) 1275 { 1276 struct ssh *ssh = NULL; 1277 extern char *optarg; 1278 extern int optind; 1279 int r, opt, i, j, on = 1; 1280 int sock_in = -1, sock_out = -1, newsock = -1; 1281 const char *remote_ip; 1282 int remote_port; 1283 char *fp, *line, *laddr, *logfile = NULL; 1284 int config_s[2] = { -1 , -1 }; 1285 u_int n; 1286 u_int64_t ibytes, obytes; 1287 mode_t new_umask; 1288 Key *key; 1289 Key *pubkey; 1290 int keytype; 1291 Authctxt *authctxt; 1292 struct connection_info *connection_info = get_connection_info(0, 0); 1293 1294 ssh_malloc_init(); /* must be called before any mallocs */ 1295 /* Save argv. */ 1296 saved_argv = av; 1297 rexec_argc = ac; 1298 1299 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 1300 sanitise_stdfd(); 1301 1302 /* Initialize configuration options to their default values. */ 1303 initialize_server_options(&options); 1304 1305 /* Parse command-line arguments. */ 1306 while ((opt = getopt(ac, av, 1307 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) { 1308 switch (opt) { 1309 case '4': 1310 options.address_family = AF_INET; 1311 break; 1312 case '6': 1313 options.address_family = AF_INET6; 1314 break; 1315 case 'f': 1316 config_file_name = optarg; 1317 break; 1318 case 'c': 1319 if (options.num_host_cert_files >= MAX_HOSTCERTS) { 1320 fprintf(stderr, "too many host certificates.\n"); 1321 exit(1); 1322 } 1323 options.host_cert_files[options.num_host_cert_files++] = 1324 derelativise_path(optarg); 1325 break; 1326 case 'd': 1327 if (debug_flag == 0) { 1328 debug_flag = 1; 1329 options.log_level = SYSLOG_LEVEL_DEBUG1; 1330 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) 1331 options.log_level++; 1332 break; 1333 case 'D': 1334 no_daemon_flag = 1; 1335 break; 1336 case 'E': 1337 logfile = optarg; 1338 /* FALLTHROUGH */ 1339 case 'e': 1340 log_stderr = 1; 1341 break; 1342 case 'i': 1343 inetd_flag = 1; 1344 break; 1345 case 'r': 1346 rexec_flag = 0; 1347 break; 1348 case 'R': 1349 rexeced_flag = 1; 1350 inetd_flag = 1; 1351 break; 1352 case 'Q': 1353 /* ignored */ 1354 break; 1355 case 'q': 1356 options.log_level = SYSLOG_LEVEL_QUIET; 1357 break; 1358 case 'b': 1359 /* protocol 1, ignored */ 1360 break; 1361 case 'p': 1362 options.ports_from_cmdline = 1; 1363 if (options.num_ports >= MAX_PORTS) { 1364 fprintf(stderr, "too many ports.\n"); 1365 exit(1); 1366 } 1367 options.ports[options.num_ports++] = a2port(optarg); 1368 if (options.ports[options.num_ports-1] <= 0) { 1369 fprintf(stderr, "Bad port number.\n"); 1370 exit(1); 1371 } 1372 break; 1373 case 'g': 1374 if ((options.login_grace_time = convtime(optarg)) == -1) { 1375 fprintf(stderr, "Invalid login grace time.\n"); 1376 exit(1); 1377 } 1378 break; 1379 case 'k': 1380 /* protocol 1, ignored */ 1381 break; 1382 case 'h': 1383 if (options.num_host_key_files >= MAX_HOSTKEYS) { 1384 fprintf(stderr, "too many host keys.\n"); 1385 exit(1); 1386 } 1387 options.host_key_files[options.num_host_key_files++] = 1388 derelativise_path(optarg); 1389 break; 1390 case 't': 1391 test_flag = 1; 1392 break; 1393 case 'T': 1394 test_flag = 2; 1395 break; 1396 case 'C': 1397 if (parse_server_match_testspec(connection_info, 1398 optarg) == -1) 1399 exit(1); 1400 break; 1401 case 'u': 1402 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL); 1403 if (utmp_len > HOST_NAME_MAX+1) { 1404 fprintf(stderr, "Invalid utmp length.\n"); 1405 exit(1); 1406 } 1407 break; 1408 case 'o': 1409 line = xstrdup(optarg); 1410 if (process_server_config_line(&options, line, 1411 "command-line", 0, NULL, NULL) != 0) 1412 exit(1); 1413 free(line); 1414 break; 1415 case '?': 1416 default: 1417 usage(); 1418 break; 1419 } 1420 } 1421 if (rexeced_flag || inetd_flag) 1422 rexec_flag = 0; 1423 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/'))) 1424 fatal("sshd re-exec requires execution with an absolute path"); 1425 if (rexeced_flag) 1426 closefrom(REEXEC_MIN_FREE_FD); 1427 else 1428 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD); 1429 1430 #ifdef WITH_OPENSSL 1431 OpenSSL_add_all_algorithms(); 1432 #endif 1433 1434 /* If requested, redirect the logs to the specified logfile. */ 1435 if (logfile != NULL) 1436 log_redirect_stderr_to(logfile); 1437 /* 1438 * Force logging to stderr until we have loaded the private host 1439 * key (unless started from inetd) 1440 */ 1441 log_init(__progname, 1442 options.log_level == SYSLOG_LEVEL_NOT_SET ? 1443 SYSLOG_LEVEL_INFO : options.log_level, 1444 options.log_facility == SYSLOG_FACILITY_NOT_SET ? 1445 SYSLOG_FACILITY_AUTH : options.log_facility, 1446 log_stderr || !inetd_flag); 1447 1448 sensitive_data.have_ssh2_key = 0; 1449 1450 /* 1451 * If we're doing an extended config test, make sure we have all of 1452 * the parameters we need. If we're not doing an extended test, 1453 * do not silently ignore connection test params. 1454 */ 1455 if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0) 1456 fatal("user, host and addr are all required when testing " 1457 "Match configs"); 1458 if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0) 1459 fatal("Config test connection parameter (-C) provided without " 1460 "test mode (-T)"); 1461 1462 /* Fetch our configuration */ 1463 buffer_init(&cfg); 1464 if (rexeced_flag) 1465 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg); 1466 else if (strcasecmp(config_file_name, "none") != 0) 1467 load_server_config(config_file_name, &cfg); 1468 1469 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name, 1470 &cfg, NULL); 1471 1472 /* Fill in default values for those options not explicitly set. */ 1473 fill_default_server_options(&options); 1474 1475 /* challenge-response is implemented via keyboard interactive */ 1476 if (options.challenge_response_authentication) 1477 options.kbd_interactive_authentication = 1; 1478 1479 /* Check that options are sensible */ 1480 if (options.authorized_keys_command_user == NULL && 1481 (options.authorized_keys_command != NULL && 1482 strcasecmp(options.authorized_keys_command, "none") != 0)) 1483 fatal("AuthorizedKeysCommand set without " 1484 "AuthorizedKeysCommandUser"); 1485 if (options.authorized_principals_command_user == NULL && 1486 (options.authorized_principals_command != NULL && 1487 strcasecmp(options.authorized_principals_command, "none") != 0)) 1488 fatal("AuthorizedPrincipalsCommand set without " 1489 "AuthorizedPrincipalsCommandUser"); 1490 1491 /* 1492 * Check whether there is any path through configured auth methods. 1493 * Unfortunately it is not possible to verify this generally before 1494 * daemonisation in the presence of Match block, but this catches 1495 * and warns for trivial misconfigurations that could break login. 1496 */ 1497 if (options.num_auth_methods != 0) { 1498 for (n = 0; n < options.num_auth_methods; n++) { 1499 if (auth2_methods_valid(options.auth_methods[n], 1500 1) == 0) 1501 break; 1502 } 1503 if (n >= options.num_auth_methods) 1504 fatal("AuthenticationMethods cannot be satisfied by " 1505 "enabled authentication methods"); 1506 } 1507 1508 /* set default channel AF */ 1509 channel_set_af(options.address_family); 1510 1511 /* Check that there are no remaining arguments. */ 1512 if (optind < ac) { 1513 fprintf(stderr, "Extra argument %s.\n", av[optind]); 1514 exit(1); 1515 } 1516 1517 debug("sshd version %s, %s", SSH_VERSION, 1518 #ifdef WITH_OPENSSL 1519 SSLeay_version(SSLEAY_VERSION) 1520 #else 1521 "without OpenSSL" 1522 #endif 1523 ); 1524 1525 /* load host keys */ 1526 sensitive_data.host_keys = xcalloc(options.num_host_key_files, 1527 sizeof(Key *)); 1528 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files, 1529 sizeof(Key *)); 1530 1531 if (options.host_key_agent) { 1532 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME)) 1533 setenv(SSH_AUTHSOCKET_ENV_NAME, 1534 options.host_key_agent, 1); 1535 if ((r = ssh_get_authentication_socket(NULL)) == 0) 1536 have_agent = 1; 1537 else 1538 error("Could not connect to agent \"%s\": %s", 1539 options.host_key_agent, ssh_err(r)); 1540 } 1541 1542 for (i = 0; i < options.num_host_key_files; i++) { 1543 if (options.host_key_files[i] == NULL) 1544 continue; 1545 key = key_load_private(options.host_key_files[i], "", NULL); 1546 pubkey = key_load_public(options.host_key_files[i], NULL); 1547 if (pubkey == NULL && key != NULL) 1548 pubkey = key_demote(key); 1549 sensitive_data.host_keys[i] = key; 1550 sensitive_data.host_pubkeys[i] = pubkey; 1551 1552 if (key == NULL && pubkey != NULL && have_agent) { 1553 debug("will rely on agent for hostkey %s", 1554 options.host_key_files[i]); 1555 keytype = pubkey->type; 1556 } else if (key != NULL) { 1557 keytype = key->type; 1558 } else { 1559 error("Could not load host key: %s", 1560 options.host_key_files[i]); 1561 sensitive_data.host_keys[i] = NULL; 1562 sensitive_data.host_pubkeys[i] = NULL; 1563 continue; 1564 } 1565 1566 switch (keytype) { 1567 case KEY_RSA: 1568 case KEY_DSA: 1569 case KEY_ECDSA: 1570 case KEY_ED25519: 1571 if (have_agent || key != NULL) 1572 sensitive_data.have_ssh2_key = 1; 1573 break; 1574 } 1575 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash, 1576 SSH_FP_DEFAULT)) == NULL) 1577 fatal("sshkey_fingerprint failed"); 1578 debug("%s host key #%d: %s %s", 1579 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp); 1580 free(fp); 1581 } 1582 if (!sensitive_data.have_ssh2_key) { 1583 logit("sshd: no hostkeys available -- exiting."); 1584 exit(1); 1585 } 1586 1587 /* 1588 * Load certificates. They are stored in an array at identical 1589 * indices to the public keys that they relate to. 1590 */ 1591 sensitive_data.host_certificates = xcalloc(options.num_host_key_files, 1592 sizeof(Key *)); 1593 for (i = 0; i < options.num_host_key_files; i++) 1594 sensitive_data.host_certificates[i] = NULL; 1595 1596 for (i = 0; i < options.num_host_cert_files; i++) { 1597 if (options.host_cert_files[i] == NULL) 1598 continue; 1599 key = key_load_public(options.host_cert_files[i], NULL); 1600 if (key == NULL) { 1601 error("Could not load host certificate: %s", 1602 options.host_cert_files[i]); 1603 continue; 1604 } 1605 if (!key_is_cert(key)) { 1606 error("Certificate file is not a certificate: %s", 1607 options.host_cert_files[i]); 1608 key_free(key); 1609 continue; 1610 } 1611 /* Find matching private key */ 1612 for (j = 0; j < options.num_host_key_files; j++) { 1613 if (key_equal_public(key, 1614 sensitive_data.host_keys[j])) { 1615 sensitive_data.host_certificates[j] = key; 1616 break; 1617 } 1618 } 1619 if (j >= options.num_host_key_files) { 1620 error("No matching private key for certificate: %s", 1621 options.host_cert_files[i]); 1622 key_free(key); 1623 continue; 1624 } 1625 sensitive_data.host_certificates[j] = key; 1626 debug("host certificate: #%d type %d %s", j, key->type, 1627 key_type(key)); 1628 } 1629 1630 if (use_privsep) { 1631 struct stat st; 1632 1633 if (getpwnam(SSH_PRIVSEP_USER) == NULL) 1634 fatal("Privilege separation user %s does not exist", 1635 SSH_PRIVSEP_USER); 1636 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) || 1637 (S_ISDIR(st.st_mode) == 0)) 1638 fatal("Missing privilege separation directory: %s", 1639 _PATH_PRIVSEP_CHROOT_DIR); 1640 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0) 1641 fatal("%s must be owned by root and not group or " 1642 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR); 1643 } 1644 1645 if (test_flag > 1) { 1646 if (server_match_spec_complete(connection_info) == 1) 1647 parse_server_match_config(&options, connection_info); 1648 dump_config(&options); 1649 } 1650 1651 /* Configuration looks good, so exit if in test mode. */ 1652 if (test_flag) 1653 exit(0); 1654 1655 if (rexec_flag) { 1656 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *)); 1657 for (i = 0; i < rexec_argc; i++) { 1658 debug("rexec_argv[%d]='%s'", i, saved_argv[i]); 1659 rexec_argv[i] = saved_argv[i]; 1660 } 1661 rexec_argv[rexec_argc] = "-R"; 1662 rexec_argv[rexec_argc + 1] = NULL; 1663 } 1664 1665 /* Ensure that umask disallows at least group and world write */ 1666 new_umask = umask(0077) | 0022; 1667 (void) umask(new_umask); 1668 1669 /* Initialize the log (it is reinitialized below in case we forked). */ 1670 if (debug_flag && (!inetd_flag || rexeced_flag)) 1671 log_stderr = 1; 1672 log_init(__progname, options.log_level, options.log_facility, log_stderr); 1673 1674 /* 1675 * If not in debugging mode, and not started from inetd, disconnect 1676 * from the controlling terminal, and fork. The original process 1677 * exits. 1678 */ 1679 if (!(debug_flag || inetd_flag || no_daemon_flag)) { 1680 int fd; 1681 1682 if (daemon(0, 0) < 0) 1683 fatal("daemon() failed: %.200s", strerror(errno)); 1684 1685 /* Disconnect from the controlling tty. */ 1686 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY); 1687 if (fd >= 0) { 1688 (void) ioctl(fd, TIOCNOTTY, NULL); 1689 close(fd); 1690 } 1691 } 1692 /* Reinitialize the log (because of the fork above). */ 1693 log_init(__progname, options.log_level, options.log_facility, log_stderr); 1694 1695 /* Chdir to the root directory so that the current disk can be 1696 unmounted if desired. */ 1697 if (chdir("/") == -1) 1698 error("chdir(\"/\"): %s", strerror(errno)); 1699 1700 /* ignore SIGPIPE */ 1701 signal(SIGPIPE, SIG_IGN); 1702 1703 /* Get a connection, either from inetd or a listening TCP socket */ 1704 if (inetd_flag) { 1705 server_accept_inetd(&sock_in, &sock_out); 1706 } else { 1707 server_listen(); 1708 1709 signal(SIGHUP, sighup_handler); 1710 signal(SIGCHLD, main_sigchld_handler); 1711 signal(SIGTERM, sigterm_handler); 1712 signal(SIGQUIT, sigterm_handler); 1713 1714 /* 1715 * Write out the pid file after the sigterm handler 1716 * is setup and the listen sockets are bound 1717 */ 1718 if (options.pid_file != NULL && !debug_flag) { 1719 FILE *f = fopen(options.pid_file, "w"); 1720 1721 if (f == NULL) { 1722 error("Couldn't create pid file \"%s\": %s", 1723 options.pid_file, strerror(errno)); 1724 } else { 1725 fprintf(f, "%ld\n", (long) getpid()); 1726 fclose(f); 1727 } 1728 } 1729 1730 /* Accept a connection and return in a forked child */ 1731 server_accept_loop(&sock_in, &sock_out, 1732 &newsock, config_s); 1733 } 1734 1735 /* This is the child processing a new connection. */ 1736 setproctitle("%s", "[accepted]"); 1737 1738 /* 1739 * Create a new session and process group since the 4.4BSD 1740 * setlogin() affects the entire process group. We don't 1741 * want the child to be able to affect the parent. 1742 */ 1743 if (!debug_flag && !inetd_flag && setsid() < 0) 1744 error("setsid: %.100s", strerror(errno)); 1745 1746 if (rexec_flag) { 1747 int fd; 1748 1749 debug("rexec start in %d out %d newsock %d pipe %d sock %d", 1750 sock_in, sock_out, newsock, startup_pipe, config_s[0]); 1751 dup2(newsock, STDIN_FILENO); 1752 dup2(STDIN_FILENO, STDOUT_FILENO); 1753 if (startup_pipe == -1) 1754 close(REEXEC_STARTUP_PIPE_FD); 1755 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) { 1756 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD); 1757 close(startup_pipe); 1758 startup_pipe = REEXEC_STARTUP_PIPE_FD; 1759 } 1760 1761 dup2(config_s[1], REEXEC_CONFIG_PASS_FD); 1762 close(config_s[1]); 1763 1764 execv(rexec_argv[0], rexec_argv); 1765 1766 /* Reexec has failed, fall back and continue */ 1767 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno)); 1768 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL); 1769 log_init(__progname, options.log_level, 1770 options.log_facility, log_stderr); 1771 1772 /* Clean up fds */ 1773 close(REEXEC_CONFIG_PASS_FD); 1774 newsock = sock_out = sock_in = dup(STDIN_FILENO); 1775 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { 1776 dup2(fd, STDIN_FILENO); 1777 dup2(fd, STDOUT_FILENO); 1778 if (fd > STDERR_FILENO) 1779 close(fd); 1780 } 1781 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d", 1782 sock_in, sock_out, newsock, startup_pipe, config_s[0]); 1783 } 1784 1785 /* Executed child processes don't need these. */ 1786 fcntl(sock_out, F_SETFD, FD_CLOEXEC); 1787 fcntl(sock_in, F_SETFD, FD_CLOEXEC); 1788 1789 /* 1790 * Disable the key regeneration alarm. We will not regenerate the 1791 * key since we are no longer in a position to give it to anyone. We 1792 * will not restart on SIGHUP since it no longer makes sense. 1793 */ 1794 alarm(0); 1795 signal(SIGALRM, SIG_DFL); 1796 signal(SIGHUP, SIG_DFL); 1797 signal(SIGTERM, SIG_DFL); 1798 signal(SIGQUIT, SIG_DFL); 1799 signal(SIGCHLD, SIG_DFL); 1800 1801 /* 1802 * Register our connection. This turns encryption off because we do 1803 * not have a key. 1804 */ 1805 packet_set_connection(sock_in, sock_out); 1806 packet_set_server(); 1807 ssh = active_state; /* XXX */ 1808 check_ip_options(ssh); 1809 1810 /* Set SO_KEEPALIVE if requested. */ 1811 if (options.tcp_keep_alive && packet_connection_is_on_socket() && 1812 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0) 1813 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno)); 1814 1815 if ((remote_port = ssh_remote_port(ssh)) < 0) { 1816 debug("ssh_remote_port failed"); 1817 cleanup_exit(255); 1818 } 1819 1820 /* 1821 * The rest of the code depends on the fact that 1822 * ssh_remote_ipaddr() caches the remote ip, even if 1823 * the socket goes away. 1824 */ 1825 remote_ip = ssh_remote_ipaddr(ssh); 1826 1827 /* Log the connection. */ 1828 laddr = get_local_ipaddr(sock_in); 1829 verbose("Connection from %s port %d on %s port %d", 1830 remote_ip, remote_port, laddr, ssh_local_port(ssh)); 1831 free(laddr); 1832 1833 /* 1834 * We don't want to listen forever unless the other side 1835 * successfully authenticates itself. So we set up an alarm which is 1836 * cleared after successful authentication. A limit of zero 1837 * indicates no limit. Note that we don't set the alarm in debugging 1838 * mode; it is just annoying to have the server exit just when you 1839 * are about to discover the bug. 1840 */ 1841 signal(SIGALRM, grace_alarm_handler); 1842 if (!debug_flag) 1843 alarm(options.login_grace_time); 1844 1845 sshd_exchange_identification(ssh, sock_in, sock_out); 1846 packet_set_nonblocking(); 1847 1848 /* allocate authentication context */ 1849 authctxt = xcalloc(1, sizeof(*authctxt)); 1850 1851 /* XXX global for cleanup, access from other modules */ 1852 the_authctxt = authctxt; 1853 1854 /* prepare buffer to collect messages to display to user after login */ 1855 buffer_init(&loginmsg); 1856 auth_debug_reset(); 1857 1858 if (use_privsep) { 1859 if (privsep_preauth(authctxt) == 1) 1860 goto authenticated; 1861 } else if (have_agent) { 1862 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) { 1863 error("Unable to get agent socket: %s", ssh_err(r)); 1864 have_agent = 0; 1865 } 1866 } 1867 1868 /* perform the key exchange */ 1869 /* authenticate user and start session */ 1870 do_ssh2_kex(); 1871 do_authentication2(authctxt); 1872 1873 /* 1874 * If we use privilege separation, the unprivileged child transfers 1875 * the current keystate and exits 1876 */ 1877 if (use_privsep) { 1878 mm_send_keystate(pmonitor); 1879 exit(0); 1880 } 1881 1882 authenticated: 1883 /* 1884 * Cancel the alarm we set to limit the time taken for 1885 * authentication. 1886 */ 1887 alarm(0); 1888 signal(SIGALRM, SIG_DFL); 1889 authctxt->authenticated = 1; 1890 if (startup_pipe != -1) { 1891 close(startup_pipe); 1892 startup_pipe = -1; 1893 } 1894 1895 /* 1896 * In privilege separation, we fork another child and prepare 1897 * file descriptor passing. 1898 */ 1899 if (use_privsep) { 1900 privsep_postauth(authctxt); 1901 /* the monitor process [priv] will not return */ 1902 } 1903 1904 packet_set_timeout(options.client_alive_interval, 1905 options.client_alive_count_max); 1906 1907 /* Try to send all our hostkeys to the client */ 1908 notify_hostkeys(active_state); 1909 1910 /* Start session. */ 1911 do_authenticated(authctxt); 1912 1913 /* The connection has been terminated. */ 1914 packet_get_bytes(&ibytes, &obytes); 1915 verbose("Transferred: sent %llu, received %llu bytes", 1916 (unsigned long long)obytes, (unsigned long long)ibytes); 1917 1918 verbose("Closing connection to %.500s port %d", remote_ip, remote_port); 1919 packet_close(); 1920 1921 if (use_privsep) 1922 mm_terminate(); 1923 1924 exit(0); 1925 } 1926 1927 int 1928 sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen, 1929 const u_char *data, size_t dlen, const char *alg, u_int flag) 1930 { 1931 int r; 1932 u_int xxx_slen, xxx_dlen = dlen; 1933 1934 if (privkey) { 1935 if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen, 1936 alg) < 0)) 1937 fatal("%s: key_sign failed", __func__); 1938 if (slen) 1939 *slen = xxx_slen; 1940 } else if (use_privsep) { 1941 if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen, 1942 alg) < 0) 1943 fatal("%s: pubkey_sign failed", __func__); 1944 if (slen) 1945 *slen = xxx_slen; 1946 } else { 1947 if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen, 1948 data, dlen, alg, datafellows)) != 0) 1949 fatal("%s: ssh_agent_sign failed: %s", 1950 __func__, ssh_err(r)); 1951 } 1952 return 0; 1953 } 1954 1955 /* SSH2 key exchange */ 1956 static void 1957 do_ssh2_kex(void) 1958 { 1959 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER }; 1960 struct kex *kex; 1961 int r; 1962 1963 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal( 1964 options.kex_algorithms); 1965 myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal( 1966 options.ciphers); 1967 myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal( 1968 options.ciphers); 1969 myproposal[PROPOSAL_MAC_ALGS_CTOS] = 1970 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs; 1971 1972 if (options.compression == COMP_NONE) { 1973 myproposal[PROPOSAL_COMP_ALGS_CTOS] = 1974 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none"; 1975 } else if (options.compression == COMP_DELAYED) { 1976 myproposal[PROPOSAL_COMP_ALGS_CTOS] = 1977 myproposal[PROPOSAL_COMP_ALGS_STOC] = 1978 "none,zlib@openssh.com"; 1979 } 1980 1981 if (options.rekey_limit || options.rekey_interval) 1982 packet_set_rekey_limits(options.rekey_limit, 1983 (time_t)options.rekey_interval); 1984 1985 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal( 1986 list_hostkey_types()); 1987 1988 /* start key exchange */ 1989 if ((r = kex_setup(active_state, myproposal)) != 0) 1990 fatal("kex_setup: %s", ssh_err(r)); 1991 kex = active_state->kex; 1992 #ifdef WITH_OPENSSL 1993 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server; 1994 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server; 1995 kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server; 1996 kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server; 1997 kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server; 1998 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server; 1999 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server; 2000 kex->kex[KEX_ECDH_SHA2] = kexecdh_server; 2001 #endif 2002 kex->kex[KEX_C25519_SHA256] = kexc25519_server; 2003 kex->server = 1; 2004 kex->client_version_string=client_version_string; 2005 kex->server_version_string=server_version_string; 2006 kex->load_host_public_key=&get_hostkey_public_by_type; 2007 kex->load_host_private_key=&get_hostkey_private_by_type; 2008 kex->host_key_index=&get_hostkey_index; 2009 kex->sign = sshd_hostkey_sign; 2010 2011 dispatch_run(DISPATCH_BLOCK, &kex->done, active_state); 2012 2013 session_id2 = kex->session_id; 2014 session_id2_len = kex->session_id_len; 2015 2016 #ifdef DEBUG_KEXDH 2017 /* send 1st encrypted/maced/compressed message */ 2018 packet_start(SSH2_MSG_IGNORE); 2019 packet_put_cstring("markus"); 2020 packet_send(); 2021 packet_write_wait(); 2022 #endif 2023 debug("KEX done"); 2024 } 2025 2026 /* server specific fatal cleanup */ 2027 void 2028 cleanup_exit(int i) 2029 { 2030 if (the_authctxt) { 2031 do_cleanup(the_authctxt); 2032 if (use_privsep && privsep_is_preauth && 2033 pmonitor != NULL && pmonitor->m_pid > 1) { 2034 debug("Killing privsep child %d", pmonitor->m_pid); 2035 if (kill(pmonitor->m_pid, SIGKILL) != 0 && 2036 errno != ESRCH) 2037 error("%s: kill(%d): %s", __func__, 2038 pmonitor->m_pid, strerror(errno)); 2039 } 2040 } 2041 _exit(i); 2042 } 2043