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