1 /* 2 * Author: Tatu Ylonen <ylo@cs.hut.fi> 3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 4 * All rights reserved 5 * This program is the ssh daemon. It listens for connections from clients, 6 * and performs authentication, executes use commands or shell, and forwards 7 * information to/from the application to the user client over an encrypted 8 * connection. This can also handle forwarding of X11, TCP/IP, and 9 * authentication agent connections. 10 * 11 * As far as I am concerned, the code I have written for this software 12 * can be used freely for any purpose. Any derived versions of this 13 * software must be clearly marked as such, and if the derived work is 14 * incompatible with the protocol description in the RFC file, it must be 15 * called by a name other than "ssh" or "Secure Shell". 16 * 17 * SSH2 implementation: 18 * Privilege Separation: 19 * 20 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved. 21 * Copyright (c) 2002 Niels Provos. All rights reserved. 22 * 23 * Redistribution and use in source and binary forms, with or without 24 * modification, are permitted provided that the following conditions 25 * are met: 26 * 1. Redistributions of source code must retain the above copyright 27 * notice, this list of conditions and the following disclaimer. 28 * 2. Redistributions in binary form must reproduce the above copyright 29 * notice, this list of conditions and the following disclaimer in the 30 * documentation and/or other materials provided with the distribution. 31 * 32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 42 */ 43 44 #include "includes.h" 45 RCSID("$OpenBSD: sshd.c,v 1.251 2002/06/25 18:51:04 markus Exp $"); 46 RCSID("$FreeBSD$"); 47 48 #include <openssl/dh.h> 49 #include <openssl/bn.h> 50 #include <openssl/md5.h> 51 #include <openssl/rand.h> 52 #ifdef HAVE_SECUREWARE 53 #include <sys/security.h> 54 #include <prot.h> 55 #endif 56 57 #include "ssh.h" 58 #include "ssh1.h" 59 #include "ssh2.h" 60 #include "xmalloc.h" 61 #include "rsa.h" 62 #include "sshpty.h" 63 #include "packet.h" 64 #include "mpaux.h" 65 #include "log.h" 66 #include "servconf.h" 67 #include "uidswap.h" 68 #include "compat.h" 69 #include "buffer.h" 70 #include "cipher.h" 71 #include "kex.h" 72 #include "key.h" 73 #include "dh.h" 74 #include "myproposal.h" 75 #include "authfile.h" 76 #include "pathnames.h" 77 #include "atomicio.h" 78 #include "canohost.h" 79 #include "auth.h" 80 #include "misc.h" 81 #include "dispatch.h" 82 #include "channels.h" 83 #include "session.h" 84 #include "monitor_mm.h" 85 #include "monitor.h" 86 #include "monitor_wrap.h" 87 #include "monitor_fdpass.h" 88 89 #ifdef LIBWRAP 90 #include <tcpd.h> 91 #include <syslog.h> 92 int allow_severity = LOG_INFO; 93 int deny_severity = LOG_WARNING; 94 #endif /* LIBWRAP */ 95 96 #ifndef O_NOCTTY 97 #define O_NOCTTY 0 98 #endif 99 100 #ifdef HAVE___PROGNAME 101 extern char *__progname; 102 #else 103 char *__progname; 104 #endif 105 106 /* Server configuration options. */ 107 ServerOptions options; 108 109 /* Name of the server configuration file. */ 110 char *config_file_name = _PATH_SERVER_CONFIG_FILE; 111 112 /* 113 * Flag indicating whether IPv4 or IPv6. This can be set on the command line. 114 * Default value is AF_UNSPEC means both IPv4 and IPv6. 115 */ 116 #ifdef IPV4_DEFAULT 117 int IPv4or6 = AF_INET; 118 #else 119 int IPv4or6 = AF_UNSPEC; 120 #endif 121 122 /* 123 * Debug mode flag. This can be set on the command line. If debug 124 * mode is enabled, extra debugging output will be sent to the system 125 * log, the daemon will not go to background, and will exit after processing 126 * the first connection. 127 */ 128 int debug_flag = 0; 129 130 /* Flag indicating that the daemon should only test the configuration and keys. */ 131 int test_flag = 0; 132 133 /* Flag indicating that the daemon is being started from inetd. */ 134 int inetd_flag = 0; 135 136 /* Flag indicating that sshd should not detach and become a daemon. */ 137 int no_daemon_flag = 0; 138 139 /* debug goes to stderr unless inetd_flag is set */ 140 int log_stderr = 0; 141 142 /* Saved arguments to main(). */ 143 char **saved_argv; 144 int saved_argc; 145 146 /* 147 * The sockets that the server is listening; this is used in the SIGHUP 148 * signal handler. 149 */ 150 #define MAX_LISTEN_SOCKS 16 151 int listen_socks[MAX_LISTEN_SOCKS]; 152 int num_listen_socks = 0; 153 154 /* 155 * the client's version string, passed by sshd2 in compat mode. if != NULL, 156 * sshd will skip the version-number exchange 157 */ 158 char *client_version_string = NULL; 159 char *server_version_string = NULL; 160 161 /* for rekeying XXX fixme */ 162 Kex *xxx_kex; 163 164 /* 165 * Any really sensitive data in the application is contained in this 166 * structure. The idea is that this structure could be locked into memory so 167 * that the pages do not get written into swap. However, there are some 168 * problems. The private key contains BIGNUMs, and we do not (in principle) 169 * have access to the internals of them, and locking just the structure is 170 * not very useful. Currently, memory locking is not implemented. 171 */ 172 struct { 173 Key *server_key; /* ephemeral server key */ 174 Key *ssh1_host_key; /* ssh1 host key */ 175 Key **host_keys; /* all private host keys */ 176 int have_ssh1_key; 177 int have_ssh2_key; 178 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH]; 179 } sensitive_data; 180 181 /* 182 * Flag indicating whether the RSA server key needs to be regenerated. 183 * Is set in the SIGALRM handler and cleared when the key is regenerated. 184 */ 185 static volatile sig_atomic_t key_do_regen = 0; 186 187 /* This is set to true when a signal is received. */ 188 static volatile sig_atomic_t received_sighup = 0; 189 static volatile sig_atomic_t received_sigterm = 0; 190 191 /* session identifier, used by RSA-auth */ 192 u_char session_id[16]; 193 194 /* same for ssh2 */ 195 u_char *session_id2 = NULL; 196 int session_id2_len = 0; 197 198 /* record remote hostname or ip */ 199 u_int utmp_len = MAXHOSTNAMELEN; 200 201 /* options.max_startup sized array of fd ints */ 202 int *startup_pipes = NULL; 203 int startup_pipe; /* in child */ 204 205 /* variables used for privilege separation */ 206 extern struct monitor *pmonitor; 207 extern int use_privsep; 208 209 /* Prototypes for various functions defined later in this file. */ 210 void destroy_sensitive_data(void); 211 void demote_sensitive_data(void); 212 213 static void do_ssh1_kex(void); 214 static void do_ssh2_kex(void); 215 216 /* 217 * Close all listening sockets 218 */ 219 static void 220 close_listen_socks(void) 221 { 222 int i; 223 224 for (i = 0; i < num_listen_socks; i++) 225 close(listen_socks[i]); 226 num_listen_socks = -1; 227 } 228 229 static void 230 close_startup_pipes(void) 231 { 232 int i; 233 234 if (startup_pipes) 235 for (i = 0; i < options.max_startups; i++) 236 if (startup_pipes[i] != -1) 237 close(startup_pipes[i]); 238 } 239 240 /* 241 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP; 242 * the effect is to reread the configuration file (and to regenerate 243 * the server key). 244 */ 245 static void 246 sighup_handler(int sig) 247 { 248 int save_errno = errno; 249 250 received_sighup = 1; 251 signal(SIGHUP, sighup_handler); 252 errno = save_errno; 253 } 254 255 /* 256 * Called from the main program after receiving SIGHUP. 257 * Restarts the server. 258 */ 259 static void 260 sighup_restart(void) 261 { 262 log("Received SIGHUP; restarting."); 263 close_listen_socks(); 264 close_startup_pipes(); 265 execv(saved_argv[0], saved_argv); 266 log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], 267 strerror(errno)); 268 exit(1); 269 } 270 271 /* 272 * Generic signal handler for terminating signals in the master daemon. 273 */ 274 static void 275 sigterm_handler(int sig) 276 { 277 received_sigterm = sig; 278 } 279 280 /* 281 * SIGCHLD handler. This is called whenever a child dies. This will then 282 * reap any zombies left by exited children. 283 */ 284 static void 285 main_sigchld_handler(int sig) 286 { 287 int save_errno = errno; 288 pid_t pid; 289 int status; 290 291 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 292 (pid < 0 && errno == EINTR)) 293 ; 294 295 signal(SIGCHLD, main_sigchld_handler); 296 errno = save_errno; 297 } 298 299 /* 300 * Signal handler for the alarm after the login grace period has expired. 301 */ 302 static void 303 grace_alarm_handler(int sig) 304 { 305 /* XXX no idea how fix this signal handler */ 306 307 /* Close the connection. */ 308 packet_close(); 309 310 /* Log error and exit. */ 311 fatal("Timeout before authentication for %s.", get_remote_ipaddr()); 312 } 313 314 /* 315 * Signal handler for the key regeneration alarm. Note that this 316 * alarm only occurs in the daemon waiting for connections, and it does not 317 * do anything with the private key or random state before forking. 318 * Thus there should be no concurrency control/asynchronous execution 319 * problems. 320 */ 321 static void 322 generate_ephemeral_server_key(void) 323 { 324 u_int32_t rand = 0; 325 int i; 326 327 verbose("Generating %s%d bit RSA key.", 328 sensitive_data.server_key ? "new " : "", options.server_key_bits); 329 if (sensitive_data.server_key != NULL) 330 key_free(sensitive_data.server_key); 331 sensitive_data.server_key = key_generate(KEY_RSA1, 332 options.server_key_bits); 333 verbose("RSA key generation complete."); 334 335 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) { 336 if (i % 4 == 0) 337 rand = arc4random(); 338 sensitive_data.ssh1_cookie[i] = rand & 0xff; 339 rand >>= 8; 340 } 341 arc4random_stir(); 342 } 343 344 static void 345 key_regeneration_alarm(int sig) 346 { 347 int save_errno = errno; 348 349 signal(SIGALRM, SIG_DFL); 350 errno = save_errno; 351 key_do_regen = 1; 352 } 353 354 static void 355 sshd_exchange_identification(int sock_in, int sock_out) 356 { 357 int i, mismatch; 358 int remote_major, remote_minor; 359 int major, minor; 360 char *s; 361 char buf[256]; /* Must not be larger than remote_version. */ 362 char remote_version[256]; /* Must be at least as big as buf. */ 363 364 if ((options.protocol & SSH_PROTO_1) && 365 (options.protocol & SSH_PROTO_2)) { 366 major = PROTOCOL_MAJOR_1; 367 minor = 99; 368 } else if (options.protocol & SSH_PROTO_2) { 369 major = PROTOCOL_MAJOR_2; 370 minor = PROTOCOL_MINOR_2; 371 } else { 372 major = PROTOCOL_MAJOR_1; 373 minor = PROTOCOL_MINOR_1; 374 } 375 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION); 376 server_version_string = xstrdup(buf); 377 378 if (client_version_string == NULL) { 379 /* Send our protocol version identification. */ 380 if (atomicio(write, sock_out, server_version_string, 381 strlen(server_version_string)) 382 != strlen(server_version_string)) { 383 log("Could not write ident string to %s", get_remote_ipaddr()); 384 fatal_cleanup(); 385 } 386 387 /* Read other sides version identification. */ 388 memset(buf, 0, sizeof(buf)); 389 for (i = 0; i < sizeof(buf) - 1; i++) { 390 if (atomicio(read, sock_in, &buf[i], 1) != 1) { 391 log("Did not receive identification string from %s", 392 get_remote_ipaddr()); 393 fatal_cleanup(); 394 } 395 if (buf[i] == '\r') { 396 buf[i] = 0; 397 /* Kludge for F-Secure Macintosh < 1.0.2 */ 398 if (i == 12 && 399 strncmp(buf, "SSH-1.5-W1.0", 12) == 0) 400 break; 401 continue; 402 } 403 if (buf[i] == '\n') { 404 buf[i] = 0; 405 break; 406 } 407 } 408 buf[sizeof(buf) - 1] = 0; 409 client_version_string = xstrdup(buf); 410 } 411 412 /* 413 * Check that the versions match. In future this might accept 414 * several versions and set appropriate flags to handle them. 415 */ 416 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n", 417 &remote_major, &remote_minor, remote_version) != 3) { 418 s = "Protocol mismatch.\n"; 419 (void) atomicio(write, sock_out, s, strlen(s)); 420 close(sock_in); 421 close(sock_out); 422 log("Bad protocol version identification '%.100s' from %s", 423 client_version_string, get_remote_ipaddr()); 424 fatal_cleanup(); 425 } 426 debug("Client protocol version %d.%d; client software version %.100s", 427 remote_major, remote_minor, remote_version); 428 429 compat_datafellows(remote_version); 430 431 if (datafellows & SSH_BUG_SCANNER) { 432 log("scanned from %s with %s. Don't panic.", 433 get_remote_ipaddr(), client_version_string); 434 fatal_cleanup(); 435 } 436 437 mismatch = 0; 438 switch (remote_major) { 439 case 1: 440 if (remote_minor == 99) { 441 if (options.protocol & SSH_PROTO_2) 442 enable_compat20(); 443 else 444 mismatch = 1; 445 break; 446 } 447 if (!(options.protocol & SSH_PROTO_1)) { 448 mismatch = 1; 449 break; 450 } 451 if (remote_minor < 3) { 452 packet_disconnect("Your ssh version is too old and " 453 "is no longer supported. Please install a newer version."); 454 } else if (remote_minor == 3) { 455 /* note that this disables agent-forwarding */ 456 enable_compat13(); 457 } 458 break; 459 case 2: 460 if (options.protocol & SSH_PROTO_2) { 461 enable_compat20(); 462 break; 463 } 464 /* FALLTHROUGH */ 465 default: 466 mismatch = 1; 467 break; 468 } 469 chop(server_version_string); 470 debug("Local version string %.200s", server_version_string); 471 472 if (mismatch) { 473 s = "Protocol major versions differ.\n"; 474 (void) atomicio(write, sock_out, s, strlen(s)); 475 close(sock_in); 476 close(sock_out); 477 log("Protocol major versions differ for %s: %.200s vs. %.200s", 478 get_remote_ipaddr(), 479 server_version_string, client_version_string); 480 fatal_cleanup(); 481 } 482 } 483 484 /* Destroy the host and server keys. They will no longer be needed. */ 485 void 486 destroy_sensitive_data(void) 487 { 488 int i; 489 490 if (sensitive_data.server_key) { 491 key_free(sensitive_data.server_key); 492 sensitive_data.server_key = NULL; 493 } 494 for (i = 0; i < options.num_host_key_files; i++) { 495 if (sensitive_data.host_keys[i]) { 496 key_free(sensitive_data.host_keys[i]); 497 sensitive_data.host_keys[i] = NULL; 498 } 499 } 500 sensitive_data.ssh1_host_key = NULL; 501 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH); 502 } 503 504 /* Demote private to public keys for network child */ 505 void 506 demote_sensitive_data(void) 507 { 508 Key *tmp; 509 int i; 510 511 if (sensitive_data.server_key) { 512 tmp = key_demote(sensitive_data.server_key); 513 key_free(sensitive_data.server_key); 514 sensitive_data.server_key = tmp; 515 } 516 517 for (i = 0; i < options.num_host_key_files; i++) { 518 if (sensitive_data.host_keys[i]) { 519 tmp = key_demote(sensitive_data.host_keys[i]); 520 key_free(sensitive_data.host_keys[i]); 521 sensitive_data.host_keys[i] = tmp; 522 if (tmp->type == KEY_RSA1) 523 sensitive_data.ssh1_host_key = tmp; 524 } 525 } 526 527 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */ 528 } 529 530 static void 531 privsep_preauth_child(void) 532 { 533 u_int32_t rand[256]; 534 gid_t gidset[2]; 535 struct passwd *pw; 536 int i; 537 538 /* Enable challenge-response authentication for privilege separation */ 539 privsep_challenge_enable(); 540 541 for (i = 0; i < 256; i++) 542 rand[i] = arc4random(); 543 RAND_seed(rand, sizeof(rand)); 544 545 /* Demote the private keys to public keys. */ 546 demote_sensitive_data(); 547 548 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) 549 fatal("Privilege separation user %s does not exist", 550 SSH_PRIVSEP_USER); 551 memset(pw->pw_passwd, 0, strlen(pw->pw_passwd)); 552 endpwent(); 553 554 /* Change our root directory*/ 555 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1) 556 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR, 557 strerror(errno)); 558 if (chdir("/") == -1) 559 fatal("chdir(\"/\"): %s", strerror(errno)); 560 561 /* Drop our privileges */ 562 debug3("privsep user:group %u:%u", (u_int)pw->pw_uid, 563 (u_int)pw->pw_gid); 564 #if 0 565 /* XXX not ready, to heavy after chroot */ 566 do_setusercontext(pw); 567 #else 568 gidset[0] = pw->pw_gid; 569 if (setgid(pw->pw_gid) < 0) 570 fatal("setgid failed for %u", pw->pw_gid ); 571 if (setgroups(1, gidset) < 0) 572 fatal("setgroups: %.100s", strerror(errno)); 573 permanently_set_uid(pw); 574 #endif 575 } 576 577 static Authctxt* 578 privsep_preauth(void) 579 { 580 Authctxt *authctxt = NULL; 581 int status; 582 pid_t pid; 583 584 /* Set up unprivileged child process to deal with network data */ 585 pmonitor = monitor_init(); 586 /* Store a pointer to the kex for later rekeying */ 587 pmonitor->m_pkex = &xxx_kex; 588 589 pid = fork(); 590 if (pid == -1) { 591 fatal("fork of unprivileged child failed"); 592 } else if (pid != 0) { 593 debug2("Network child is on pid %ld", (long)pid); 594 595 close(pmonitor->m_recvfd); 596 authctxt = monitor_child_preauth(pmonitor); 597 close(pmonitor->m_sendfd); 598 599 /* Sync memory */ 600 monitor_sync(pmonitor); 601 602 /* Wait for the child's exit status */ 603 while (waitpid(pid, &status, 0) < 0) 604 if (errno != EINTR) 605 break; 606 return (authctxt); 607 } else { 608 /* child */ 609 610 close(pmonitor->m_sendfd); 611 612 /* Demote the child */ 613 if (getuid() == 0 || geteuid() == 0) 614 privsep_preauth_child(); 615 setproctitle("%s", "[net]"); 616 } 617 return (NULL); 618 } 619 620 static void 621 privsep_postauth(Authctxt *authctxt) 622 { 623 extern Authctxt *x_authctxt; 624 625 /* XXX - Remote port forwarding */ 626 x_authctxt = authctxt; 627 628 #ifdef BROKEN_FD_PASSING 629 if (1) { 630 #else 631 if (authctxt->pw->pw_uid == 0 || options.use_login) { 632 #endif 633 /* File descriptor passing is broken or root login */ 634 monitor_apply_keystate(pmonitor); 635 use_privsep = 0; 636 return; 637 } 638 639 /* Authentication complete */ 640 alarm(0); 641 if (startup_pipe != -1) { 642 close(startup_pipe); 643 startup_pipe = -1; 644 } 645 646 /* New socket pair */ 647 monitor_reinit(pmonitor); 648 649 pmonitor->m_pid = fork(); 650 if (pmonitor->m_pid == -1) 651 fatal("fork of unprivileged child failed"); 652 else if (pmonitor->m_pid != 0) { 653 debug2("User child is on pid %ld", (long)pmonitor->m_pid); 654 close(pmonitor->m_recvfd); 655 monitor_child_postauth(pmonitor); 656 657 /* NEVERREACHED */ 658 exit(0); 659 } 660 661 close(pmonitor->m_sendfd); 662 663 /* Demote the private keys to public keys. */ 664 demote_sensitive_data(); 665 666 /* Drop privileges */ 667 do_setusercontext(authctxt->pw); 668 669 /* It is safe now to apply the key state */ 670 monitor_apply_keystate(pmonitor); 671 } 672 673 static char * 674 list_hostkey_types(void) 675 { 676 Buffer b; 677 char *p; 678 int i; 679 680 buffer_init(&b); 681 for (i = 0; i < options.num_host_key_files; i++) { 682 Key *key = sensitive_data.host_keys[i]; 683 if (key == NULL) 684 continue; 685 switch (key->type) { 686 case KEY_RSA: 687 case KEY_DSA: 688 if (buffer_len(&b) > 0) 689 buffer_append(&b, ",", 1); 690 p = key_ssh_name(key); 691 buffer_append(&b, p, strlen(p)); 692 break; 693 } 694 } 695 buffer_append(&b, "\0", 1); 696 p = xstrdup(buffer_ptr(&b)); 697 buffer_free(&b); 698 debug("list_hostkey_types: %s", p); 699 return p; 700 } 701 702 Key * 703 get_hostkey_by_type(int type) 704 { 705 int i; 706 707 for (i = 0; i < options.num_host_key_files; i++) { 708 Key *key = sensitive_data.host_keys[i]; 709 if (key != NULL && key->type == type) 710 return key; 711 } 712 return NULL; 713 } 714 715 Key * 716 get_hostkey_by_index(int ind) 717 { 718 if (ind < 0 || ind >= options.num_host_key_files) 719 return (NULL); 720 return (sensitive_data.host_keys[ind]); 721 } 722 723 int 724 get_hostkey_index(Key *key) 725 { 726 int i; 727 728 for (i = 0; i < options.num_host_key_files; i++) { 729 if (key == sensitive_data.host_keys[i]) 730 return (i); 731 } 732 return (-1); 733 } 734 735 /* 736 * returns 1 if connection should be dropped, 0 otherwise. 737 * dropping starts at connection #max_startups_begin with a probability 738 * of (max_startups_rate/100). the probability increases linearly until 739 * all connections are dropped for startups > max_startups 740 */ 741 static int 742 drop_connection(int startups) 743 { 744 double p, r; 745 746 if (startups < options.max_startups_begin) 747 return 0; 748 if (startups >= options.max_startups) 749 return 1; 750 if (options.max_startups_rate == 100) 751 return 1; 752 753 p = 100 - options.max_startups_rate; 754 p *= startups - options.max_startups_begin; 755 p /= (double) (options.max_startups - options.max_startups_begin); 756 p += options.max_startups_rate; 757 p /= 100.0; 758 r = arc4random() / (double) UINT_MAX; 759 760 debug("drop_connection: p %g, r %g", p, r); 761 return (r < p) ? 1 : 0; 762 } 763 764 static void 765 usage(void) 766 { 767 fprintf(stderr, "sshd version %s\n", SSH_VERSION); 768 fprintf(stderr, "Usage: %s [options]\n", __progname); 769 fprintf(stderr, "Options:\n"); 770 fprintf(stderr, " -f file Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE); 771 fprintf(stderr, " -d Debugging mode (multiple -d means more debugging)\n"); 772 fprintf(stderr, " -i Started from inetd\n"); 773 fprintf(stderr, " -D Do not fork into daemon mode\n"); 774 fprintf(stderr, " -t Only test configuration file and keys\n"); 775 fprintf(stderr, " -q Quiet (no logging)\n"); 776 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n"); 777 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n"); 778 fprintf(stderr, " -g seconds Grace period for authentication (default: 600)\n"); 779 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n"); 780 fprintf(stderr, " -h file File from which to read host key (default: %s)\n", 781 _PATH_HOST_KEY_FILE); 782 fprintf(stderr, " -u len Maximum hostname length for utmp recording\n"); 783 fprintf(stderr, " -4 Use IPv4 only\n"); 784 fprintf(stderr, " -6 Use IPv6 only\n"); 785 fprintf(stderr, " -o option Process the option as if it was read from a configuration file.\n"); 786 exit(1); 787 } 788 789 /* 790 * Main program for the daemon. 791 */ 792 int 793 main(int ac, char **av) 794 { 795 extern char *optarg; 796 extern int optind; 797 int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1; 798 pid_t pid; 799 socklen_t fromlen; 800 fd_set *fdset; 801 struct sockaddr_storage from; 802 const char *remote_ip; 803 int remote_port; 804 FILE *f; 805 struct linger linger; 806 struct addrinfo *ai; 807 char ntop[NI_MAXHOST], strport[NI_MAXSERV]; 808 int listen_sock, maxfd; 809 int startup_p[2]; 810 int startups = 0; 811 Authctxt *authctxt; 812 Key *key; 813 int ret, key_used = 0; 814 815 #ifdef HAVE_SECUREWARE 816 (void)set_auth_parameters(ac, av); 817 #endif 818 __progname = get_progname(av[0]); 819 init_rng(); 820 821 /* Save argv. */ 822 saved_argc = ac; 823 saved_argv = av; 824 825 /* Initialize configuration options to their default values. */ 826 initialize_server_options(&options); 827 828 /* Parse command-line arguments. */ 829 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) { 830 switch (opt) { 831 case '4': 832 IPv4or6 = AF_INET; 833 break; 834 case '6': 835 IPv4or6 = AF_INET6; 836 break; 837 case 'f': 838 config_file_name = optarg; 839 break; 840 case 'd': 841 if (0 == debug_flag) { 842 debug_flag = 1; 843 options.log_level = SYSLOG_LEVEL_DEBUG1; 844 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) { 845 options.log_level++; 846 } else { 847 fprintf(stderr, "Too high debugging level.\n"); 848 exit(1); 849 } 850 break; 851 case 'D': 852 no_daemon_flag = 1; 853 break; 854 case 'e': 855 log_stderr = 1; 856 break; 857 case 'i': 858 inetd_flag = 1; 859 break; 860 case 'Q': 861 /* ignored */ 862 break; 863 case 'q': 864 options.log_level = SYSLOG_LEVEL_QUIET; 865 break; 866 case 'b': 867 options.server_key_bits = atoi(optarg); 868 break; 869 case 'p': 870 options.ports_from_cmdline = 1; 871 if (options.num_ports >= MAX_PORTS) { 872 fprintf(stderr, "too many ports.\n"); 873 exit(1); 874 } 875 options.ports[options.num_ports++] = a2port(optarg); 876 if (options.ports[options.num_ports-1] == 0) { 877 fprintf(stderr, "Bad port number.\n"); 878 exit(1); 879 } 880 break; 881 case 'g': 882 if ((options.login_grace_time = convtime(optarg)) == -1) { 883 fprintf(stderr, "Invalid login grace time.\n"); 884 exit(1); 885 } 886 break; 887 case 'k': 888 if ((options.key_regeneration_time = convtime(optarg)) == -1) { 889 fprintf(stderr, "Invalid key regeneration interval.\n"); 890 exit(1); 891 } 892 break; 893 case 'h': 894 if (options.num_host_key_files >= MAX_HOSTKEYS) { 895 fprintf(stderr, "too many host keys.\n"); 896 exit(1); 897 } 898 options.host_key_files[options.num_host_key_files++] = optarg; 899 break; 900 case 'V': 901 client_version_string = optarg; 902 /* only makes sense with inetd_flag, i.e. no listen() */ 903 inetd_flag = 1; 904 break; 905 case 't': 906 test_flag = 1; 907 break; 908 case 'u': 909 utmp_len = atoi(optarg); 910 break; 911 case 'o': 912 if (process_server_config_line(&options, optarg, 913 "command-line", 0) != 0) 914 exit(1); 915 break; 916 case '?': 917 default: 918 usage(); 919 break; 920 } 921 } 922 SSLeay_add_all_algorithms(); 923 channel_set_af(IPv4or6); 924 925 /* 926 * Force logging to stderr until we have loaded the private host 927 * key (unless started from inetd) 928 */ 929 log_init(__progname, 930 options.log_level == SYSLOG_LEVEL_NOT_SET ? 931 SYSLOG_LEVEL_INFO : options.log_level, 932 options.log_facility == SYSLOG_FACILITY_NOT_SET ? 933 SYSLOG_FACILITY_AUTH : options.log_facility, 934 !inetd_flag); 935 936 #ifdef _CRAY 937 /* Cray can define user privs drop all prives now! 938 * Not needed on PRIV_SU systems! 939 */ 940 drop_cray_privs(); 941 #endif 942 943 seed_rng(); 944 945 /* Read server configuration options from the configuration file. */ 946 read_server_config(&options, config_file_name); 947 948 /* Fill in default values for those options not explicitly set. */ 949 fill_default_server_options(&options); 950 951 /* Check that there are no remaining arguments. */ 952 if (optind < ac) { 953 fprintf(stderr, "Extra argument %s.\n", av[optind]); 954 exit(1); 955 } 956 957 debug("sshd version %.100s", SSH_VERSION); 958 959 /* load private host keys */ 960 sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*)); 961 for (i = 0; i < options.num_host_key_files; i++) 962 sensitive_data.host_keys[i] = NULL; 963 sensitive_data.server_key = NULL; 964 sensitive_data.ssh1_host_key = NULL; 965 sensitive_data.have_ssh1_key = 0; 966 sensitive_data.have_ssh2_key = 0; 967 968 for (i = 0; i < options.num_host_key_files; i++) { 969 key = key_load_private(options.host_key_files[i], "", NULL); 970 sensitive_data.host_keys[i] = key; 971 if (key == NULL) { 972 error("Could not load host key: %s", 973 options.host_key_files[i]); 974 sensitive_data.host_keys[i] = NULL; 975 continue; 976 } 977 switch (key->type) { 978 case KEY_RSA1: 979 sensitive_data.ssh1_host_key = key; 980 sensitive_data.have_ssh1_key = 1; 981 break; 982 case KEY_RSA: 983 case KEY_DSA: 984 sensitive_data.have_ssh2_key = 1; 985 break; 986 } 987 debug("private host key: #%d type %d %s", i, key->type, 988 key_type(key)); 989 } 990 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) { 991 log("Disabling protocol version 1. Could not load host key"); 992 options.protocol &= ~SSH_PROTO_1; 993 } 994 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) { 995 log("Disabling protocol version 2. Could not load host key"); 996 options.protocol &= ~SSH_PROTO_2; 997 } 998 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) { 999 log("sshd: no hostkeys available -- exiting."); 1000 exit(1); 1001 } 1002 1003 /* Check certain values for sanity. */ 1004 if (options.protocol & SSH_PROTO_1) { 1005 if (options.server_key_bits < 512 || 1006 options.server_key_bits > 32768) { 1007 fprintf(stderr, "Bad server key size.\n"); 1008 exit(1); 1009 } 1010 /* 1011 * Check that server and host key lengths differ sufficiently. This 1012 * is necessary to make double encryption work with rsaref. Oh, I 1013 * hate software patents. I dont know if this can go? Niels 1014 */ 1015 if (options.server_key_bits > 1016 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - 1017 SSH_KEY_BITS_RESERVED && options.server_key_bits < 1018 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + 1019 SSH_KEY_BITS_RESERVED) { 1020 options.server_key_bits = 1021 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + 1022 SSH_KEY_BITS_RESERVED; 1023 debug("Forcing server key to %d bits to make it differ from host key.", 1024 options.server_key_bits); 1025 } 1026 } 1027 1028 if (use_privsep) { 1029 struct passwd *pw; 1030 struct stat st; 1031 1032 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) 1033 fatal("Privilege separation user %s does not exist", 1034 SSH_PRIVSEP_USER); 1035 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) || 1036 (S_ISDIR(st.st_mode) == 0)) 1037 fatal("Missing privilege separation directory: %s", 1038 _PATH_PRIVSEP_CHROOT_DIR); 1039 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0) 1040 fatal("Bad owner or mode for %s", 1041 _PATH_PRIVSEP_CHROOT_DIR); 1042 } 1043 1044 /* Configuration looks good, so exit if in test mode. */ 1045 if (test_flag) 1046 exit(0); 1047 1048 /* 1049 * Clear out any supplemental groups we may have inherited. This 1050 * prevents inadvertent creation of files with bad modes (in the 1051 * portable version at least, it's certainly possible for PAM 1052 * to create a file, and we can't control the code in every 1053 * module which might be used). 1054 */ 1055 if (setgroups(0, NULL) < 0) 1056 debug("setgroups() failed: %.200s", strerror(errno)); 1057 1058 /* Initialize the log (it is reinitialized below in case we forked). */ 1059 if (debug_flag && !inetd_flag) 1060 log_stderr = 1; 1061 log_init(__progname, options.log_level, options.log_facility, log_stderr); 1062 1063 /* 1064 * If not in debugging mode, and not started from inetd, disconnect 1065 * from the controlling terminal, and fork. The original process 1066 * exits. 1067 */ 1068 if (!(debug_flag || inetd_flag || no_daemon_flag)) { 1069 #ifdef TIOCNOTTY 1070 int fd; 1071 #endif /* TIOCNOTTY */ 1072 if (daemon(0, 0) < 0) 1073 fatal("daemon() failed: %.200s", strerror(errno)); 1074 1075 /* Disconnect from the controlling tty. */ 1076 #ifdef TIOCNOTTY 1077 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY); 1078 if (fd >= 0) { 1079 (void) ioctl(fd, TIOCNOTTY, NULL); 1080 close(fd); 1081 } 1082 #endif /* TIOCNOTTY */ 1083 } 1084 /* Reinitialize the log (because of the fork above). */ 1085 log_init(__progname, options.log_level, options.log_facility, log_stderr); 1086 1087 /* Initialize the random number generator. */ 1088 arc4random_stir(); 1089 1090 /* Chdir to the root directory so that the current disk can be 1091 unmounted if desired. */ 1092 chdir("/"); 1093 1094 /* ignore SIGPIPE */ 1095 signal(SIGPIPE, SIG_IGN); 1096 1097 /* Start listening for a socket, unless started from inetd. */ 1098 if (inetd_flag) { 1099 int s1; 1100 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */ 1101 dup(s1); 1102 sock_in = dup(0); 1103 sock_out = dup(1); 1104 startup_pipe = -1; 1105 /* 1106 * We intentionally do not close the descriptors 0, 1, and 2 1107 * as our code for setting the descriptors won\'t work if 1108 * ttyfd happens to be one of those. 1109 */ 1110 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out); 1111 if (options.protocol & SSH_PROTO_1) 1112 generate_ephemeral_server_key(); 1113 } else { 1114 for (ai = options.listen_addrs; ai; ai = ai->ai_next) { 1115 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) 1116 continue; 1117 if (num_listen_socks >= MAX_LISTEN_SOCKS) 1118 fatal("Too many listen sockets. " 1119 "Enlarge MAX_LISTEN_SOCKS"); 1120 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, 1121 ntop, sizeof(ntop), strport, sizeof(strport), 1122 NI_NUMERICHOST|NI_NUMERICSERV) != 0) { 1123 error("getnameinfo failed"); 1124 continue; 1125 } 1126 /* Create socket for listening. */ 1127 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0); 1128 if (listen_sock < 0) { 1129 /* kernel may not support ipv6 */ 1130 verbose("socket: %.100s", strerror(errno)); 1131 continue; 1132 } 1133 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) { 1134 error("listen_sock O_NONBLOCK: %s", strerror(errno)); 1135 close(listen_sock); 1136 continue; 1137 } 1138 /* 1139 * Set socket options. We try to make the port 1140 * reusable and have it close as fast as possible 1141 * without waiting in unnecessary wait states on 1142 * close. 1143 */ 1144 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, 1145 &on, sizeof(on)); 1146 linger.l_onoff = 1; 1147 linger.l_linger = 5; 1148 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, 1149 &linger, sizeof(linger)); 1150 1151 debug("Bind to port %s on %s.", strport, ntop); 1152 1153 /* Bind the socket to the desired port. */ 1154 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) { 1155 if (!ai->ai_next) 1156 error("Bind to port %s on %s failed: %.200s.", 1157 strport, ntop, strerror(errno)); 1158 close(listen_sock); 1159 continue; 1160 } 1161 listen_socks[num_listen_socks] = listen_sock; 1162 num_listen_socks++; 1163 1164 /* Start listening on the port. */ 1165 log("Server listening on %s port %s.", ntop, strport); 1166 if (listen(listen_sock, 5) < 0) 1167 fatal("listen: %.100s", strerror(errno)); 1168 1169 } 1170 freeaddrinfo(options.listen_addrs); 1171 1172 if (!num_listen_socks) 1173 fatal("Cannot bind any address."); 1174 1175 if (options.protocol & SSH_PROTO_1) 1176 generate_ephemeral_server_key(); 1177 1178 /* 1179 * Arrange to restart on SIGHUP. The handler needs 1180 * listen_sock. 1181 */ 1182 signal(SIGHUP, sighup_handler); 1183 1184 signal(SIGTERM, sigterm_handler); 1185 signal(SIGQUIT, sigterm_handler); 1186 1187 /* Arrange SIGCHLD to be caught. */ 1188 signal(SIGCHLD, main_sigchld_handler); 1189 1190 /* Write out the pid file after the sigterm handler is setup */ 1191 if (!debug_flag) { 1192 /* 1193 * Record our pid in /var/run/sshd.pid to make it 1194 * easier to kill the correct sshd. We don't want to 1195 * do this before the bind above because the bind will 1196 * fail if there already is a daemon, and this will 1197 * overwrite any old pid in the file. 1198 */ 1199 f = fopen(options.pid_file, "wb"); 1200 if (f) { 1201 fprintf(f, "%ld\n", (long) getpid()); 1202 fclose(f); 1203 } 1204 } 1205 1206 /* setup fd set for listen */ 1207 fdset = NULL; 1208 maxfd = 0; 1209 for (i = 0; i < num_listen_socks; i++) 1210 if (listen_socks[i] > maxfd) 1211 maxfd = listen_socks[i]; 1212 /* pipes connected to unauthenticated childs */ 1213 startup_pipes = xmalloc(options.max_startups * sizeof(int)); 1214 for (i = 0; i < options.max_startups; i++) 1215 startup_pipes[i] = -1; 1216 1217 /* 1218 * Stay listening for connections until the system crashes or 1219 * the daemon is killed with a signal. 1220 */ 1221 for (;;) { 1222 if (received_sighup) 1223 sighup_restart(); 1224 if (fdset != NULL) 1225 xfree(fdset); 1226 fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask); 1227 fdset = (fd_set *)xmalloc(fdsetsz); 1228 memset(fdset, 0, fdsetsz); 1229 1230 for (i = 0; i < num_listen_socks; i++) 1231 FD_SET(listen_socks[i], fdset); 1232 for (i = 0; i < options.max_startups; i++) 1233 if (startup_pipes[i] != -1) 1234 FD_SET(startup_pipes[i], fdset); 1235 1236 /* Wait in select until there is a connection. */ 1237 ret = select(maxfd+1, fdset, NULL, NULL, NULL); 1238 if (ret < 0 && errno != EINTR) 1239 error("select: %.100s", strerror(errno)); 1240 if (received_sigterm) { 1241 log("Received signal %d; terminating.", 1242 (int) received_sigterm); 1243 close_listen_socks(); 1244 unlink(options.pid_file); 1245 exit(255); 1246 } 1247 if (key_used && key_do_regen) { 1248 generate_ephemeral_server_key(); 1249 key_used = 0; 1250 key_do_regen = 0; 1251 } 1252 if (ret < 0) 1253 continue; 1254 1255 for (i = 0; i < options.max_startups; i++) 1256 if (startup_pipes[i] != -1 && 1257 FD_ISSET(startup_pipes[i], fdset)) { 1258 /* 1259 * the read end of the pipe is ready 1260 * if the child has closed the pipe 1261 * after successful authentication 1262 * or if the child has died 1263 */ 1264 close(startup_pipes[i]); 1265 startup_pipes[i] = -1; 1266 startups--; 1267 } 1268 for (i = 0; i < num_listen_socks; i++) { 1269 if (!FD_ISSET(listen_socks[i], fdset)) 1270 continue; 1271 fromlen = sizeof(from); 1272 newsock = accept(listen_socks[i], (struct sockaddr *)&from, 1273 &fromlen); 1274 if (newsock < 0) { 1275 if (errno != EINTR && errno != EWOULDBLOCK) 1276 error("accept: %.100s", strerror(errno)); 1277 continue; 1278 } 1279 if (fcntl(newsock, F_SETFL, 0) < 0) { 1280 error("newsock del O_NONBLOCK: %s", strerror(errno)); 1281 close(newsock); 1282 continue; 1283 } 1284 if (drop_connection(startups) == 1) { 1285 debug("drop connection #%d", startups); 1286 close(newsock); 1287 continue; 1288 } 1289 if (pipe(startup_p) == -1) { 1290 close(newsock); 1291 continue; 1292 } 1293 1294 for (j = 0; j < options.max_startups; j++) 1295 if (startup_pipes[j] == -1) { 1296 startup_pipes[j] = startup_p[0]; 1297 if (maxfd < startup_p[0]) 1298 maxfd = startup_p[0]; 1299 startups++; 1300 break; 1301 } 1302 1303 /* 1304 * Got connection. Fork a child to handle it, unless 1305 * we are in debugging mode. 1306 */ 1307 if (debug_flag) { 1308 /* 1309 * In debugging mode. Close the listening 1310 * socket, and start processing the 1311 * connection without forking. 1312 */ 1313 debug("Server will not fork when running in debugging mode."); 1314 close_listen_socks(); 1315 sock_in = newsock; 1316 sock_out = newsock; 1317 startup_pipe = -1; 1318 pid = getpid(); 1319 break; 1320 } else { 1321 /* 1322 * Normal production daemon. Fork, and have 1323 * the child process the connection. The 1324 * parent continues listening. 1325 */ 1326 if ((pid = fork()) == 0) { 1327 /* 1328 * Child. Close the listening and max_startup 1329 * sockets. Start using the accepted socket. 1330 * Reinitialize logging (since our pid has 1331 * changed). We break out of the loop to handle 1332 * the connection. 1333 */ 1334 startup_pipe = startup_p[1]; 1335 close_startup_pipes(); 1336 close_listen_socks(); 1337 sock_in = newsock; 1338 sock_out = newsock; 1339 log_init(__progname, options.log_level, options.log_facility, log_stderr); 1340 break; 1341 } 1342 } 1343 1344 /* Parent. Stay in the loop. */ 1345 if (pid < 0) 1346 error("fork: %.100s", strerror(errno)); 1347 else 1348 debug("Forked child %ld.", (long)pid); 1349 1350 close(startup_p[1]); 1351 1352 /* Mark that the key has been used (it was "given" to the child). */ 1353 if ((options.protocol & SSH_PROTO_1) && 1354 key_used == 0) { 1355 /* Schedule server key regeneration alarm. */ 1356 signal(SIGALRM, key_regeneration_alarm); 1357 alarm(options.key_regeneration_time); 1358 key_used = 1; 1359 } 1360 1361 arc4random_stir(); 1362 1363 /* Close the new socket (the child is now taking care of it). */ 1364 close(newsock); 1365 } 1366 /* child process check (or debug mode) */ 1367 if (num_listen_socks < 0) 1368 break; 1369 } 1370 } 1371 1372 /* This is the child processing a new connection. */ 1373 1374 /* 1375 * Create a new session and process group since the 4.4BSD 1376 * setlogin() affects the entire process group. We don't 1377 * want the child to be able to affect the parent. 1378 */ 1379 #if 0 1380 /* XXX: this breaks Solaris */ 1381 if (!debug_flag && !inetd_flag && setsid() < 0) 1382 error("setsid: %.100s", strerror(errno)); 1383 #endif 1384 1385 /* 1386 * Disable the key regeneration alarm. We will not regenerate the 1387 * key since we are no longer in a position to give it to anyone. We 1388 * will not restart on SIGHUP since it no longer makes sense. 1389 */ 1390 alarm(0); 1391 signal(SIGALRM, SIG_DFL); 1392 signal(SIGHUP, SIG_DFL); 1393 signal(SIGTERM, SIG_DFL); 1394 signal(SIGQUIT, SIG_DFL); 1395 signal(SIGCHLD, SIG_DFL); 1396 signal(SIGINT, SIG_DFL); 1397 1398 /* 1399 * Set socket options for the connection. We want the socket to 1400 * close as fast as possible without waiting for anything. If the 1401 * connection is not a socket, these will do nothing. 1402 */ 1403 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */ 1404 linger.l_onoff = 1; 1405 linger.l_linger = 5; 1406 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger)); 1407 1408 /* Set keepalives if requested. */ 1409 if (options.keepalives && 1410 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, 1411 sizeof(on)) < 0) 1412 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno)); 1413 1414 /* 1415 * Register our connection. This turns encryption off because we do 1416 * not have a key. 1417 */ 1418 packet_set_connection(sock_in, sock_out); 1419 1420 remote_port = get_remote_port(); 1421 remote_ip = get_remote_ipaddr(); 1422 1423 #ifdef LIBWRAP 1424 /* Check whether logins are denied from this host. */ 1425 { 1426 struct request_info req; 1427 1428 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0); 1429 fromhost(&req); 1430 1431 if (!hosts_access(&req)) { 1432 debug("Connection refused by tcp wrapper"); 1433 refuse(&req); 1434 /* NOTREACHED */ 1435 fatal("libwrap refuse returns"); 1436 } 1437 } 1438 #endif /* LIBWRAP */ 1439 1440 /* Log the connection. */ 1441 verbose("Connection from %.500s port %d", remote_ip, remote_port); 1442 1443 /* 1444 * We don\'t want to listen forever unless the other side 1445 * successfully authenticates itself. So we set up an alarm which is 1446 * cleared after successful authentication. A limit of zero 1447 * indicates no limit. Note that we don\'t set the alarm in debugging 1448 * mode; it is just annoying to have the server exit just when you 1449 * are about to discover the bug. 1450 */ 1451 signal(SIGALRM, grace_alarm_handler); 1452 if (!debug_flag) 1453 alarm(options.login_grace_time); 1454 1455 sshd_exchange_identification(sock_in, sock_out); 1456 /* 1457 * Check that the connection comes from a privileged port. 1458 * Rhosts-Authentication only makes sense from privileged 1459 * programs. Of course, if the intruder has root access on his local 1460 * machine, he can connect from any port. So do not use these 1461 * authentication methods from machines that you do not trust. 1462 */ 1463 if (options.rhosts_authentication && 1464 (remote_port >= IPPORT_RESERVED || 1465 remote_port < IPPORT_RESERVED / 2)) { 1466 debug("Rhosts Authentication disabled, " 1467 "originating port %d not trusted.", remote_port); 1468 options.rhosts_authentication = 0; 1469 } 1470 #if defined(KRB4) && !defined(KRB5) 1471 if (!packet_connection_is_ipv4() && 1472 options.kerberos_authentication) { 1473 debug("Kerberos Authentication disabled, only available for IPv4."); 1474 options.kerberos_authentication = 0; 1475 } 1476 #endif /* KRB4 && !KRB5 */ 1477 #ifdef AFS 1478 /* If machine has AFS, set process authentication group. */ 1479 if (k_hasafs()) { 1480 k_setpag(); 1481 k_unlog(); 1482 } 1483 #endif /* AFS */ 1484 1485 packet_set_nonblocking(); 1486 1487 if (use_privsep) 1488 if ((authctxt = privsep_preauth()) != NULL) 1489 goto authenticated; 1490 1491 /* perform the key exchange */ 1492 /* authenticate user and start session */ 1493 if (compat20) { 1494 do_ssh2_kex(); 1495 authctxt = do_authentication2(); 1496 } else { 1497 do_ssh1_kex(); 1498 authctxt = do_authentication(); 1499 } 1500 /* 1501 * If we use privilege separation, the unprivileged child transfers 1502 * the current keystate and exits 1503 */ 1504 if (use_privsep) { 1505 mm_send_keystate(pmonitor); 1506 exit(0); 1507 } 1508 1509 authenticated: 1510 /* 1511 * In privilege separation, we fork another child and prepare 1512 * file descriptor passing. 1513 */ 1514 if (use_privsep) { 1515 privsep_postauth(authctxt); 1516 /* the monitor process [priv] will not return */ 1517 if (!compat20) 1518 destroy_sensitive_data(); 1519 } 1520 1521 /* Perform session preparation. */ 1522 do_authenticated(authctxt); 1523 1524 /* The connection has been terminated. */ 1525 verbose("Closing connection to %.100s", remote_ip); 1526 1527 #ifdef USE_PAM 1528 finish_pam(); 1529 #endif /* USE_PAM */ 1530 1531 packet_close(); 1532 1533 if (use_privsep) 1534 mm_terminate(); 1535 1536 exit(0); 1537 } 1538 1539 /* 1540 * Decrypt session_key_int using our private server key and private host key 1541 * (key with larger modulus first). 1542 */ 1543 int 1544 ssh1_session_key(BIGNUM *session_key_int) 1545 { 1546 int rsafail = 0; 1547 1548 if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) { 1549 /* Server key has bigger modulus. */ 1550 if (BN_num_bits(sensitive_data.server_key->rsa->n) < 1551 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) { 1552 fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d", 1553 get_remote_ipaddr(), 1554 BN_num_bits(sensitive_data.server_key->rsa->n), 1555 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n), 1556 SSH_KEY_BITS_RESERVED); 1557 } 1558 if (rsa_private_decrypt(session_key_int, session_key_int, 1559 sensitive_data.server_key->rsa) <= 0) 1560 rsafail++; 1561 if (rsa_private_decrypt(session_key_int, session_key_int, 1562 sensitive_data.ssh1_host_key->rsa) <= 0) 1563 rsafail++; 1564 } else { 1565 /* Host key has bigger modulus (or they are equal). */ 1566 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) < 1567 BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) { 1568 fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d", 1569 get_remote_ipaddr(), 1570 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n), 1571 BN_num_bits(sensitive_data.server_key->rsa->n), 1572 SSH_KEY_BITS_RESERVED); 1573 } 1574 if (rsa_private_decrypt(session_key_int, session_key_int, 1575 sensitive_data.ssh1_host_key->rsa) < 0) 1576 rsafail++; 1577 if (rsa_private_decrypt(session_key_int, session_key_int, 1578 sensitive_data.server_key->rsa) < 0) 1579 rsafail++; 1580 } 1581 return (rsafail); 1582 } 1583 /* 1584 * SSH1 key exchange 1585 */ 1586 static void 1587 do_ssh1_kex(void) 1588 { 1589 int i, len; 1590 int rsafail = 0; 1591 BIGNUM *session_key_int; 1592 u_char session_key[SSH_SESSION_KEY_LENGTH]; 1593 u_char cookie[8]; 1594 u_int cipher_type, auth_mask, protocol_flags; 1595 u_int32_t rand = 0; 1596 1597 /* 1598 * Generate check bytes that the client must send back in the user 1599 * packet in order for it to be accepted; this is used to defy ip 1600 * spoofing attacks. Note that this only works against somebody 1601 * doing IP spoofing from a remote machine; any machine on the local 1602 * network can still see outgoing packets and catch the random 1603 * cookie. This only affects rhosts authentication, and this is one 1604 * of the reasons why it is inherently insecure. 1605 */ 1606 for (i = 0; i < 8; i++) { 1607 if (i % 4 == 0) 1608 rand = arc4random(); 1609 cookie[i] = rand & 0xff; 1610 rand >>= 8; 1611 } 1612 1613 /* 1614 * Send our public key. We include in the packet 64 bits of random 1615 * data that must be matched in the reply in order to prevent IP 1616 * spoofing. 1617 */ 1618 packet_start(SSH_SMSG_PUBLIC_KEY); 1619 for (i = 0; i < 8; i++) 1620 packet_put_char(cookie[i]); 1621 1622 /* Store our public server RSA key. */ 1623 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n)); 1624 packet_put_bignum(sensitive_data.server_key->rsa->e); 1625 packet_put_bignum(sensitive_data.server_key->rsa->n); 1626 1627 /* Store our public host RSA key. */ 1628 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n)); 1629 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e); 1630 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n); 1631 1632 /* Put protocol flags. */ 1633 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN); 1634 1635 /* Declare which ciphers we support. */ 1636 packet_put_int(cipher_mask_ssh1(0)); 1637 1638 /* Declare supported authentication types. */ 1639 auth_mask = 0; 1640 if (options.rhosts_authentication) 1641 auth_mask |= 1 << SSH_AUTH_RHOSTS; 1642 if (options.rhosts_rsa_authentication) 1643 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA; 1644 if (options.rsa_authentication) 1645 auth_mask |= 1 << SSH_AUTH_RSA; 1646 #if defined(KRB4) || defined(KRB5) 1647 if (options.kerberos_authentication) 1648 auth_mask |= 1 << SSH_AUTH_KERBEROS; 1649 #endif 1650 #if defined(AFS) || defined(KRB5) 1651 if (options.kerberos_tgt_passing) 1652 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT; 1653 #endif 1654 #ifdef AFS 1655 if (options.afs_token_passing) 1656 auth_mask |= 1 << SSH_PASS_AFS_TOKEN; 1657 #endif 1658 if (options.challenge_response_authentication == 1) 1659 auth_mask |= 1 << SSH_AUTH_TIS; 1660 if (options.password_authentication) 1661 auth_mask |= 1 << SSH_AUTH_PASSWORD; 1662 packet_put_int(auth_mask); 1663 1664 /* Send the packet and wait for it to be sent. */ 1665 packet_send(); 1666 packet_write_wait(); 1667 1668 debug("Sent %d bit server key and %d bit host key.", 1669 BN_num_bits(sensitive_data.server_key->rsa->n), 1670 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n)); 1671 1672 /* Read clients reply (cipher type and session key). */ 1673 packet_read_expect(SSH_CMSG_SESSION_KEY); 1674 1675 /* Get cipher type and check whether we accept this. */ 1676 cipher_type = packet_get_char(); 1677 1678 if (!(cipher_mask_ssh1(0) & (1 << cipher_type))) 1679 packet_disconnect("Warning: client selects unsupported cipher."); 1680 1681 /* Get check bytes from the packet. These must match those we 1682 sent earlier with the public key packet. */ 1683 for (i = 0; i < 8; i++) 1684 if (cookie[i] != packet_get_char()) 1685 packet_disconnect("IP Spoofing check bytes do not match."); 1686 1687 debug("Encryption type: %.200s", cipher_name(cipher_type)); 1688 1689 /* Get the encrypted integer. */ 1690 if ((session_key_int = BN_new()) == NULL) 1691 fatal("do_ssh1_kex: BN_new failed"); 1692 packet_get_bignum(session_key_int); 1693 1694 protocol_flags = packet_get_int(); 1695 packet_set_protocol_flags(protocol_flags); 1696 packet_check_eom(); 1697 1698 /* Decrypt session_key_int using host/server keys */ 1699 rsafail = PRIVSEP(ssh1_session_key(session_key_int)); 1700 1701 /* 1702 * Extract session key from the decrypted integer. The key is in the 1703 * least significant 256 bits of the integer; the first byte of the 1704 * key is in the highest bits. 1705 */ 1706 if (!rsafail) { 1707 BN_mask_bits(session_key_int, sizeof(session_key) * 8); 1708 len = BN_num_bytes(session_key_int); 1709 if (len < 0 || len > sizeof(session_key)) { 1710 error("do_connection: bad session key len from %s: " 1711 "session_key_int %d > sizeof(session_key) %lu", 1712 get_remote_ipaddr(), len, (u_long)sizeof(session_key)); 1713 rsafail++; 1714 } else { 1715 memset(session_key, 0, sizeof(session_key)); 1716 BN_bn2bin(session_key_int, 1717 session_key + sizeof(session_key) - len); 1718 1719 compute_session_id(session_id, cookie, 1720 sensitive_data.ssh1_host_key->rsa->n, 1721 sensitive_data.server_key->rsa->n); 1722 /* 1723 * Xor the first 16 bytes of the session key with the 1724 * session id. 1725 */ 1726 for (i = 0; i < 16; i++) 1727 session_key[i] ^= session_id[i]; 1728 } 1729 } 1730 if (rsafail) { 1731 int bytes = BN_num_bytes(session_key_int); 1732 u_char *buf = xmalloc(bytes); 1733 MD5_CTX md; 1734 1735 log("do_connection: generating a fake encryption key"); 1736 BN_bn2bin(session_key_int, buf); 1737 MD5_Init(&md); 1738 MD5_Update(&md, buf, bytes); 1739 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH); 1740 MD5_Final(session_key, &md); 1741 MD5_Init(&md); 1742 MD5_Update(&md, session_key, 16); 1743 MD5_Update(&md, buf, bytes); 1744 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH); 1745 MD5_Final(session_key + 16, &md); 1746 memset(buf, 0, bytes); 1747 xfree(buf); 1748 for (i = 0; i < 16; i++) 1749 session_id[i] = session_key[i] ^ session_key[i + 16]; 1750 } 1751 /* Destroy the private and public keys. No longer. */ 1752 destroy_sensitive_data(); 1753 1754 if (use_privsep) 1755 mm_ssh1_session_id(session_id); 1756 1757 /* Destroy the decrypted integer. It is no longer needed. */ 1758 BN_clear_free(session_key_int); 1759 1760 /* Set the session key. From this on all communications will be encrypted. */ 1761 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type); 1762 1763 /* Destroy our copy of the session key. It is no longer needed. */ 1764 memset(session_key, 0, sizeof(session_key)); 1765 1766 debug("Received session key; encryption turned on."); 1767 1768 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */ 1769 packet_start(SSH_SMSG_SUCCESS); 1770 packet_send(); 1771 packet_write_wait(); 1772 } 1773 1774 /* 1775 * SSH2 key exchange: diffie-hellman-group1-sha1 1776 */ 1777 static void 1778 do_ssh2_kex(void) 1779 { 1780 Kex *kex; 1781 1782 if (options.ciphers != NULL) { 1783 myproposal[PROPOSAL_ENC_ALGS_CTOS] = 1784 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers; 1785 } 1786 myproposal[PROPOSAL_ENC_ALGS_CTOS] = 1787 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]); 1788 myproposal[PROPOSAL_ENC_ALGS_STOC] = 1789 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]); 1790 1791 if (options.macs != NULL) { 1792 myproposal[PROPOSAL_MAC_ALGS_CTOS] = 1793 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs; 1794 } 1795 if (!options.compression) { 1796 myproposal[PROPOSAL_COMP_ALGS_CTOS] = 1797 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none"; 1798 } 1799 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types(); 1800 1801 /* start key exchange */ 1802 kex = kex_setup(myproposal); 1803 kex->server = 1; 1804 kex->client_version_string=client_version_string; 1805 kex->server_version_string=server_version_string; 1806 kex->load_host_key=&get_hostkey_by_type; 1807 kex->host_key_index=&get_hostkey_index; 1808 1809 xxx_kex = kex; 1810 1811 dispatch_run(DISPATCH_BLOCK, &kex->done, kex); 1812 1813 session_id2 = kex->session_id; 1814 session_id2_len = kex->session_id_len; 1815 1816 #ifdef DEBUG_KEXDH 1817 /* send 1st encrypted/maced/compressed message */ 1818 packet_start(SSH2_MSG_IGNORE); 1819 packet_put_cstring("markus"); 1820 packet_send(); 1821 packet_write_wait(); 1822 #endif 1823 debug("KEX done"); 1824 } 1825