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