Home | History | Annotate | Download | only in sshd
      1 /*
      2  * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
      3  * Copyright (c) 1995 Tatu Ylonen <ylo (at) 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  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
     45  * Use is subject to license terms.
     46  */
     47 
     48 #include "includes.h"
     49 RCSID("$OpenBSD: sshd.c,v 1.260 2002/09/27 10:42:09 mickey Exp $");
     50 
     51 #pragma ident	"%Z%%M%	%I%	%E% SMI"
     52 
     53 #include <openssl/dh.h>
     54 #include <openssl/bn.h>
     55 #include <openssl/md5.h>
     56 
     57 #include <openssl/rand.h>
     58 #ifdef HAVE_SECUREWARE
     59 #include <sys/security.h>
     60 #include <prot.h>
     61 #endif
     62 
     63 #include "ssh.h"
     64 #include "ssh1.h"
     65 #include "ssh2.h"
     66 #include "xmalloc.h"
     67 #include "rsa.h"
     68 #include "sshpty.h"
     69 #include "packet.h"
     70 #include "mpaux.h"
     71 #include "log.h"
     72 #include "servconf.h"
     73 #include "uidswap.h"
     74 #include "compat.h"
     75 #include "buffer.h"
     76 #include "cipher.h"
     77 #include "kex.h"
     78 #include "key.h"
     79 #include "dh.h"
     80 #include "myproposal.h"
     81 #include "authfile.h"
     82 #include "pathnames.h"
     83 #include "atomicio.h"
     84 #include "canohost.h"
     85 #include "auth.h"
     86 #include "misc.h"
     87 #include "dispatch.h"
     88 #include "channels.h"
     89 #include "session.h"
     90 #include "g11n.h"
     91 #include "sshlogin.h"
     92 #include "xlist.h"
     93 
     94 #ifdef HAVE_BSM
     95 #include "bsmaudit.h"
     96 adt_session_data_t *ah = NULL;
     97 #endif /* HAVE_BSM */
     98 
     99 #ifdef ALTPRIVSEP
    100 #include "altprivsep.h"
    101 #endif /* ALTPRIVSEP */
    102 
    103 #ifdef HAVE_SOLARIS_CONTRACTS
    104 #include <sys/ctfs.h>
    105 #include <sys/contract.h>
    106 #include <sys/contract/process.h>
    107 #include <libcontract.h>
    108 #endif /* HAVE_SOLARIS_CONTRACTS */
    109 
    110 #ifdef GSSAPI
    111 #include "ssh-gss.h"
    112 extern Gssctxt *xxx_gssctxt;
    113 #endif /* GSSAPI */
    114 
    115 #ifdef LIBWRAP
    116 #include <tcpd.h>
    117 #include <syslog.h>
    118 #ifndef lint
    119 int allow_severity = LOG_INFO;
    120 int deny_severity = LOG_WARNING;
    121 #endif /* lint */
    122 #endif /* LIBWRAP */
    123 
    124 #ifndef O_NOCTTY
    125 #define O_NOCTTY	0
    126 #endif
    127 
    128 #ifdef HAVE___PROGNAME
    129 extern char *__progname;
    130 #else
    131 char *__progname;
    132 #endif
    133 
    134 /* Server configuration options. */
    135 ServerOptions options;
    136 
    137 /* Name of the server configuration file. */
    138 static char *config_file_name = _PATH_SERVER_CONFIG_FILE;
    139 
    140 /*
    141  * Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
    142  * Default value is AF_UNSPEC means both IPv4 and IPv6.
    143  */
    144 #ifdef IPV4_DEFAULT
    145 int IPv4or6 = AF_INET;
    146 #else
    147 int IPv4or6 = AF_UNSPEC;
    148 #endif
    149 
    150 /*
    151  * Debug mode flag.  This can be set on the command line.  If debug
    152  * mode is enabled, extra debugging output will be sent to the system
    153  * log, the daemon will not go to background, and will exit after processing
    154  * the first connection.
    155  */
    156 int debug_flag = 0;
    157 
    158 /* Flag indicating that the daemon should only test the configuration and keys. */
    159 static int test_flag = 0;
    160 
    161 /* Flag indicating that the daemon is being started from inetd. */
    162 static int inetd_flag = 0;
    163 
    164 /* Flag indicating that sshd should not detach and become a daemon. */
    165 static int no_daemon_flag = 0;
    166 
    167 /* debug goes to stderr unless inetd_flag is set */
    168 int log_stderr = 0;
    169 
    170 /* Saved arguments to main(). */
    171 static char **saved_argv;
    172 static int saved_argc;
    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 static int listen_socks[MAX_LISTEN_SOCKS];
    180 static 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 static char *client_version_string = NULL;
    187 static char *server_version_string = NULL;
    188 
    189 /* for rekeying XXX fixme */
    190 Kex *xxx_kex;
    191 
    192 /*
    193  * Any really sensitive data in the application is contained in this
    194  * structure. The idea is that this structure could be locked into memory so
    195  * that the pages do not get written into swap.  However, there are some
    196  * problems. The private key contains BIGNUMs, and we do not (in principle)
    197  * have access to the internals of them, and locking just the structure is
    198  * not very useful.  Currently, memory locking is not implemented.
    199  */
    200 static struct {
    201 	Key	*server_key;		/* ephemeral server key */
    202 	Key	*ssh1_host_key;		/* ssh1 host key */
    203 	Key	**host_keys;		/* all private host keys */
    204 	int	have_ssh1_key;
    205 	int	have_ssh2_key;
    206 	u_char	ssh1_cookie[SSH_SESSION_KEY_LENGTH];
    207 } sensitive_data;
    208 
    209 /*
    210  * Flag indicating whether the RSA server key needs to be regenerated.
    211  * Is set in the SIGALRM handler and cleared when the key is regenerated.
    212  */
    213 static volatile sig_atomic_t key_do_regen = 0;
    214 
    215 /* This is set to true when a signal is received. */
    216 static volatile sig_atomic_t received_sighup = 0;
    217 static volatile sig_atomic_t received_sigterm = 0;
    218 
    219 /* session identifier, used by RSA-auth */
    220 u_char session_id[16];
    221 
    222 /* same for ssh2 */
    223 u_char *session_id2 = NULL;
    224 int session_id2_len = 0;
    225 
    226 /* record remote hostname or ip */
    227 u_int utmp_len = MAXHOSTNAMELEN;
    228 
    229 /* options.max_startup sized array of fd ints */
    230 static int *startup_pipes = NULL;
    231 static int startup_pipe = -1;	/* in child */
    232 
    233 #ifdef GSSAPI
    234 static gss_OID_set mechs = GSS_C_NULL_OID_SET;
    235 #endif /* GSSAPI */
    236 
    237 /* Prototypes for various functions defined later in this file. */
    238 void destroy_sensitive_data(void);
    239 static void demote_sensitive_data(void);
    240 
    241 static void do_ssh1_kex(void);
    242 static void do_ssh2_kex(void);
    243 
    244 /*
    245  * Close all listening sockets
    246  */
    247 static void
    248 close_listen_socks(void)
    249 {
    250 	int i;
    251 
    252 	for (i = 0; i < num_listen_socks; i++)
    253 		(void) close(listen_socks[i]);
    254 	num_listen_socks = -1;
    255 }
    256 
    257 static void
    258 close_startup_pipes(void)
    259 {
    260 	int i;
    261 
    262 	if (startup_pipes)
    263 		for (i = 0; i < options.max_startups; i++)
    264 			if (startup_pipes[i] != -1)
    265 				(void) close(startup_pipes[i]);
    266 }
    267 
    268 /*
    269  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
    270  * the effect is to reread the configuration file (and to regenerate
    271  * the server key).
    272  */
    273 static void
    274 sighup_handler(int sig)
    275 {
    276 	int save_errno = errno;
    277 
    278 	received_sighup = 1;
    279 	(void) signal(SIGHUP, sighup_handler);
    280 	errno = save_errno;
    281 }
    282 
    283 /*
    284  * Called from the main program after receiving SIGHUP.
    285  * Restarts the server.
    286  */
    287 static void
    288 sighup_restart(void)
    289 {
    290 	log("Received SIGHUP; restarting.");
    291 	close_listen_socks();
    292 	close_startup_pipes();
    293 	(void) execv(saved_argv[0], saved_argv);
    294 	log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
    295 	    strerror(errno));
    296 	exit(1);
    297 }
    298 
    299 /*
    300  * Generic signal handler for terminating signals in the master daemon.
    301  */
    302 static void
    303 sigterm_handler(int sig)
    304 {
    305 	received_sigterm = sig;
    306 }
    307 
    308 /*
    309  * SIGCHLD handler.  This is called whenever a child dies.  This will then
    310  * reap any zombies left by exited children.
    311  */
    312 static void
    313 main_sigchld_handler(int sig)
    314 {
    315 	int save_errno = errno;
    316 	pid_t pid;
    317 	int status;
    318 
    319 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
    320 	    (pid < 0 && errno == EINTR))
    321 		;
    322 
    323 	(void) signal(SIGCHLD, main_sigchld_handler);
    324 	errno = save_errno;
    325 }
    326 
    327 /*
    328  * Signal handler for the alarm after the login grace period has expired.
    329  */
    330 static void
    331 grace_alarm_handler(int sig)
    332 {
    333 	/* XXX no idea how fix this signal handler */
    334 
    335 	/* Log error and exit. */
    336 	fatal("Timeout before authentication for %s", get_remote_ipaddr());
    337 }
    338 
    339 #ifdef HAVE_SOLARIS_CONTRACTS
    340 static int contracts_fd = -1;
    341 void
    342 contracts_pre_fork()
    343 {
    344 	const char *during = "opening process contract template";
    345 
    346 	/*
    347 	 * Failure should not be treated as fatal on the theory that
    348 	 * it's better to start with children in the same contract as
    349 	 * the master listener than not at all.
    350 	 */
    351 
    352 	if (contracts_fd == -1) {
    353 		if ((contracts_fd = open64(CTFS_ROOT "/process/template",
    354 				O_RDWR)) == -1)
    355 			goto cleanup;
    356 
    357 		during = "setting sundry contract terms";
    358 		if ((errno = ct_pr_tmpl_set_param(contracts_fd, CT_PR_PGRPONLY)))
    359 			goto cleanup;
    360 
    361 		if ((errno = ct_tmpl_set_informative(contracts_fd, CT_PR_EV_HWERR)))
    362 			goto cleanup;
    363 
    364 		if ((errno = ct_pr_tmpl_set_fatal(contracts_fd, CT_PR_EV_HWERR)))
    365 			goto cleanup;
    366 
    367 		if ((errno = ct_tmpl_set_critical(contracts_fd, 0)))
    368 			goto cleanup;
    369 	}
    370 
    371 	during = "setting active template";
    372 	if ((errno = ct_tmpl_activate(contracts_fd)))
    373 		goto cleanup;
    374 
    375 	debug3("Set active contract");
    376 	return;
    377 
    378 cleanup:
    379 	if (contracts_fd != -1)
    380 		(void) close(contracts_fd);
    381 
    382 	contracts_fd = -1;
    383 
    384 	if (errno)
    385 		debug2("Error while trying to set up active contract"
    386 			" template: %s while %s", strerror(errno), during);
    387 }
    388 
    389 void
    390 contracts_post_fork_child()
    391 {
    392 	/* Clear active template so fork() creates no new contracts. */
    393 
    394 	if (contracts_fd == -1)
    395 		return;
    396 
    397 	if ((errno = (ct_tmpl_clear(contracts_fd))))
    398 		debug2("Error while trying to clear active contract template"
    399 			" (child): %s", strerror(errno));
    400 	else
    401 		debug3("Cleared active contract template (child)");
    402 
    403 	(void) close(contracts_fd);
    404 
    405 	contracts_fd = -1;
    406 }
    407 
    408 void
    409 contracts_post_fork_parent(int fork_succeeded)
    410 {
    411 	char path[PATH_MAX];
    412 	int cfd, n;
    413 	ct_stathdl_t st;
    414 	ctid_t latest;
    415 
    416 	/* Clear active template, abandon latest contract. */
    417 	if (contracts_fd == -1)
    418 		return;
    419 
    420 	if ((errno = ct_tmpl_clear(contracts_fd)))
    421 		debug2("Error while clearing active contract template: %s",
    422 			strerror(errno));
    423 	else
    424 		debug3("Cleared active contract template (parent)");
    425 
    426 	if (!fork_succeeded)
    427 		return;
    428 
    429 	if ((cfd = open64(CTFS_ROOT "/process/latest", O_RDONLY)) == -1) {
    430 		debug2("Error while getting latest contract: %s",
    431 			strerror(errno));
    432 		return;
    433 	}
    434 
    435 	if ((errno = ct_status_read(cfd, CTD_COMMON, &st)) != 0) {
    436 		debug2("Error while getting latest contract ID: %s",
    437 			strerror(errno));
    438 		(void) close(cfd);
    439 		return;
    440 	}
    441 
    442 	latest = ct_status_get_id(st);
    443 	ct_status_free(st);
    444 	(void) close(cfd);
    445 
    446 	n = snprintf(path, PATH_MAX, CTFS_ROOT "/all/%ld/ctl", latest);
    447 
    448 	if (n >= PATH_MAX) {
    449 		debug2("Error while opening the latest contract ctl file: %s",
    450 			strerror(ENAMETOOLONG));
    451 		return;
    452 	}
    453 
    454 	if ((cfd = open64(path, O_WRONLY)) == -1) {
    455 		debug2("Error while opening the latest contract ctl file: %s",
    456 			strerror(errno));
    457 		return;
    458 	}
    459 
    460 	if ((errno = ct_ctl_abandon(cfd)))
    461 		debug2("Error while abandoning latest contract: %s",
    462 			strerror(errno));
    463 	else
    464 		debug3("Abandoned latest contract");
    465 
    466 	(void) close(cfd);
    467 }
    468 #endif /* HAVE_SOLARIS_CONTRACTS */
    469 
    470 /*
    471  * Signal handler for the key regeneration alarm.  Note that this
    472  * alarm only occurs in the daemon waiting for connections, and it does not
    473  * do anything with the private key or random state before forking.
    474  * Thus there should be no concurrency control/asynchronous execution
    475  * problems.
    476  */
    477 static void
    478 generate_ephemeral_server_key(void)
    479 {
    480 	u_int32_t rnd = 0;
    481 	int i;
    482 
    483 	verbose("Generating %s%d bit RSA key.",
    484 	    sensitive_data.server_key ? "new " : "", options.server_key_bits);
    485 	if (sensitive_data.server_key != NULL)
    486 		key_free(sensitive_data.server_key);
    487 	sensitive_data.server_key = key_generate(KEY_RSA1,
    488 	    options.server_key_bits);
    489 	verbose("RSA key generation complete.");
    490 
    491 	for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
    492 		if (i % 4 == 0)
    493 			rnd = arc4random();
    494 		sensitive_data.ssh1_cookie[i] = rnd & 0xff;
    495 		rnd >>= 8;
    496 	}
    497 	arc4random_stir();
    498 }
    499 
    500 static void
    501 key_regeneration_alarm(int sig)
    502 {
    503 	int save_errno = errno;
    504 
    505 	(void) signal(SIGALRM, SIG_DFL);
    506 	errno = save_errno;
    507 	key_do_regen = 1;
    508 }
    509 
    510 static void
    511 sshd_exchange_identification(int sock_in, int sock_out)
    512 {
    513 	int i, mismatch;
    514 	int remote_major, remote_minor;
    515 	int major, minor;
    516 	char *s;
    517 	char buf[256];			/* Must not be larger than remote_version. */
    518 	char remote_version[256];	/* Must be at least as big as buf. */
    519 
    520 	if ((options.protocol & SSH_PROTO_1) &&
    521 	    (options.protocol & SSH_PROTO_2)) {
    522 		major = PROTOCOL_MAJOR_1;
    523 		minor = 99;
    524 	} else if (options.protocol & SSH_PROTO_2) {
    525 		major = PROTOCOL_MAJOR_2;
    526 		minor = PROTOCOL_MINOR_2;
    527 	} else {
    528 		major = PROTOCOL_MAJOR_1;
    529 		minor = PROTOCOL_MINOR_1;
    530 	}
    531 	(void) snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
    532 	server_version_string = xstrdup(buf);
    533 
    534 	if (client_version_string == NULL) {
    535 		/* Send our protocol version identification. */
    536 		if (atomicio(write, sock_out, server_version_string,
    537 		    strlen(server_version_string))
    538 		    != strlen(server_version_string)) {
    539 			log("Could not write ident string to %s", get_remote_ipaddr());
    540 			fatal_cleanup();
    541 		}
    542 
    543 		/* Read other sides version identification. */
    544 		(void) memset(buf, 0, sizeof(buf));
    545 		for (i = 0; i < sizeof(buf) - 1; i++) {
    546 			if (atomicio(read, sock_in, &buf[i], 1) != 1) {
    547 				log("Did not receive identification string from %s",
    548 				    get_remote_ipaddr());
    549 				fatal_cleanup();
    550 			}
    551 			if (buf[i] == '\r') {
    552 				buf[i] = 0;
    553 				/* Kludge for F-Secure Macintosh < 1.0.2 */
    554 				if (i == 12 &&
    555 				    strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
    556 					break;
    557 				continue;
    558 			}
    559 			if (buf[i] == '\n') {
    560 				buf[i] = 0;
    561 				break;
    562 			}
    563 		}
    564 		buf[sizeof(buf) - 1] = 0;
    565 		client_version_string = xstrdup(buf);
    566 	}
    567 
    568 	/*
    569 	 * Check that the versions match.  In future this might accept
    570 	 * several versions and set appropriate flags to handle them.
    571 	 */
    572 	if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
    573 	    &remote_major, &remote_minor, remote_version) != 3) {
    574 		s = "Protocol mismatch.\n";
    575 		(void) atomicio(write, sock_out, s, strlen(s));
    576 		(void) close(sock_in);
    577 		(void) close(sock_out);
    578 		log("Bad protocol version identification '%.100s' from %s",
    579 		    client_version_string, get_remote_ipaddr());
    580 		fatal_cleanup();
    581 	}
    582 	debug("Client protocol version %d.%d; client software version %.100s",
    583 	    remote_major, remote_minor, remote_version);
    584 
    585 	compat_datafellows(remote_version);
    586 
    587 	if (datafellows & SSH_BUG_PROBE) {
    588 		log("probed from %s with %s.  Don't panic.",
    589 		    get_remote_ipaddr(), client_version_string);
    590 		fatal_cleanup();
    591 	}
    592 
    593 	if (datafellows & SSH_BUG_SCANNER) {
    594 		log("scanned from %s with %s.  Don't panic.",
    595 		    get_remote_ipaddr(), client_version_string);
    596 		fatal_cleanup();
    597 	}
    598 
    599 	mismatch = 0;
    600 	switch (remote_major) {
    601 	case 1:
    602 		if (remote_minor == 99) {
    603 			if (options.protocol & SSH_PROTO_2)
    604 				enable_compat20();
    605 			else
    606 				mismatch = 1;
    607 			break;
    608 		}
    609 		if (!(options.protocol & SSH_PROTO_1)) {
    610 			mismatch = 1;
    611 			break;
    612 		}
    613 		if (remote_minor < 3) {
    614 			packet_disconnect("Your ssh version is too old and "
    615 			    "is no longer supported.  Please install a newer version.");
    616 		} else if (remote_minor == 3) {
    617 			/* note that this disables agent-forwarding */
    618 			enable_compat13();
    619 		}
    620 		break;
    621 	case 2:
    622 		if (options.protocol & SSH_PROTO_2) {
    623 			enable_compat20();
    624 			break;
    625 		}
    626 		/* FALLTHROUGH */
    627 	default:
    628 		mismatch = 1;
    629 		break;
    630 	}
    631 	chop(server_version_string);
    632 	debug("Local version string %.200s", server_version_string);
    633 
    634 	if (mismatch) {
    635 		s = "Protocol major versions differ.\n";
    636 		(void) atomicio(write, sock_out, s, strlen(s));
    637 		(void) close(sock_in);
    638 		(void) close(sock_out);
    639 		log("Protocol major versions differ for %s: %.200s vs. %.200s",
    640 		    get_remote_ipaddr(),
    641 		    server_version_string, client_version_string);
    642 		fatal_cleanup();
    643 	}
    644 }
    645 
    646 /* Destroy the host and server keys.  They will no longer be needed. */
    647 void
    648 destroy_sensitive_data(void)
    649 {
    650 	int i;
    651 
    652 	if (sensitive_data.server_key) {
    653 		key_free(sensitive_data.server_key);
    654 		sensitive_data.server_key = NULL;
    655 	}
    656 	for (i = 0; i < options.num_host_key_files; i++) {
    657 		if (sensitive_data.host_keys[i]) {
    658 			key_free(sensitive_data.host_keys[i]);
    659 			sensitive_data.host_keys[i] = NULL;
    660 		}
    661 	}
    662 	sensitive_data.ssh1_host_key = NULL;
    663 	(void) memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
    664 }
    665 
    666 /* Demote private to public keys for network child */
    667 static void
    668 demote_sensitive_data(void)
    669 {
    670 	Key *tmp;
    671 	int i;
    672 
    673 	if (sensitive_data.server_key) {
    674 		tmp = key_demote(sensitive_data.server_key);
    675 		key_free(sensitive_data.server_key);
    676 		sensitive_data.server_key = tmp;
    677 	}
    678 
    679 	for (i = 0; i < options.num_host_key_files; i++) {
    680 		if (sensitive_data.host_keys[i]) {
    681 			tmp = key_demote(sensitive_data.host_keys[i]);
    682 			key_free(sensitive_data.host_keys[i]);
    683 			sensitive_data.host_keys[i] = tmp;
    684 			if (tmp->type == KEY_RSA1)
    685 				sensitive_data.ssh1_host_key = tmp;
    686 		}
    687 	}
    688 
    689 	/* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
    690 }
    691 
    692 static char *
    693 list_hostkey_types(void)
    694 {
    695 	Buffer b;
    696 	char *p;
    697 	int i;
    698 
    699 	buffer_init(&b);
    700 	for (i = 0; i < options.num_host_key_files; i++) {
    701 		Key *key = sensitive_data.host_keys[i];
    702 		if (key == NULL)
    703 			continue;
    704 		switch (key->type) {
    705 		case KEY_RSA:
    706 		case KEY_DSA:
    707 			if (buffer_len(&b) > 0)
    708 				buffer_append(&b, ",", 1);
    709 			p = key_ssh_name(key);
    710 			buffer_append(&b, p, strlen(p));
    711 			break;
    712 		}
    713 	}
    714 	buffer_append(&b, "\0", 1);
    715 	p = xstrdup(buffer_ptr(&b));
    716 	buffer_free(&b);
    717 	debug("list_hostkey_types: %s", p);
    718 	return p;
    719 }
    720 
    721 #ifdef lint
    722 static
    723 #endif /* lint */
    724 Key *
    725 get_hostkey_by_type(int type)
    726 {
    727 	int i;
    728 
    729 	for (i = 0; i < options.num_host_key_files; i++) {
    730 		Key *key = sensitive_data.host_keys[i];
    731 		if (key != NULL && key->type == type)
    732 			return key;
    733 	}
    734 	return NULL;
    735 }
    736 
    737 #ifdef lint
    738 static
    739 #endif /* lint */
    740 Key *
    741 get_hostkey_by_index(int ind)
    742 {
    743 	if (ind < 0 || ind >= options.num_host_key_files)
    744 		return (NULL);
    745 	return (sensitive_data.host_keys[ind]);
    746 }
    747 
    748 #ifdef lint
    749 static
    750 #endif /* lint */
    751 int
    752 get_hostkey_index(Key *key)
    753 {
    754 	int i;
    755 
    756 	for (i = 0; i < options.num_host_key_files; i++) {
    757 		if (key == sensitive_data.host_keys[i])
    758 			return (i);
    759 	}
    760 	return (-1);
    761 }
    762 
    763 /*
    764  * returns 1 if connection should be dropped, 0 otherwise.
    765  * dropping starts at connection #max_startups_begin with a probability
    766  * of (max_startups_rate/100). the probability increases linearly until
    767  * all connections are dropped for startups > max_startups
    768  */
    769 static int
    770 drop_connection(int startups)
    771 {
    772 	double p, r;
    773 
    774 	if (startups < options.max_startups_begin)
    775 		return 0;
    776 	if (startups >= options.max_startups)
    777 		return 1;
    778 	if (options.max_startups_rate == 100)
    779 		return 1;
    780 
    781 	p  = 100 - options.max_startups_rate;
    782 	p *= startups - options.max_startups_begin;
    783 	p /= (double) (options.max_startups - options.max_startups_begin);
    784 	p += options.max_startups_rate;
    785 	p /= 100.0;
    786 	r = arc4random() / (double) UINT_MAX;
    787 
    788 	debug("drop_connection: p %g, r %g", p, r);
    789 	return (r < p) ? 1 : 0;
    790 }
    791 
    792 static void
    793 usage(void)
    794 {
    795 	(void) fprintf(stderr, gettext("sshd version %s\n"), SSH_VERSION);
    796 	(void) fprintf(stderr,
    797 	    gettext("Usage: %s [options]\n"
    798 		"Options:\n"
    799 		"  -f file    Configuration file (default %s)\n"
    800 		"  -d         Debugging mode (multiple -d means more "
    801 		"debugging)\n"
    802 		"  -i         Started from inetd\n"
    803 		"  -D         Do not fork into daemon mode\n"
    804 		"  -t         Only test configuration file and keys\n"
    805 		"  -q         Quiet (no logging)\n"
    806 		"  -p port    Listen on the specified port (default: 22)\n"
    807 		"  -k seconds Regenerate server key every this many seconds "
    808 		"(default: 3600)\n"
    809 		"  -g seconds Grace period for authentication (default: 600)\n"
    810 		"  -b bits    Size of server RSA key (default: 768 bits)\n"
    811 		"  -h file    File from which to read host key (default: %s)\n"
    812 		"  -4         Use IPv4 only\n"
    813 		"  -6         Use IPv6 only\n"
    814 		"  -o option  Process the option as if it was read from "
    815 		"a configuration file.\n"),
    816 	    __progname, _PATH_SERVER_CONFIG_FILE, _PATH_HOST_KEY_FILE);
    817 	exit(1);
    818 }
    819 
    820 /*
    821  * Main program for the daemon.
    822  */
    823 int
    824 main(int ac, char **av)
    825 {
    826 	extern char *optarg;
    827 	extern int optind;
    828 	int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
    829 	pid_t pid;
    830 	socklen_t fromlen;
    831 	fd_set *fdset;
    832 	struct sockaddr_storage from;
    833 	const char *remote_ip;
    834 	int remote_port;
    835 	FILE *f;
    836 	struct addrinfo *ai;
    837 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
    838 	int listen_sock, maxfd;
    839 	int startup_p[2];
    840 	int startups = 0;
    841 	Authctxt *authctxt;
    842 	Key *key;
    843 	int ret, key_used = 0;
    844 #ifdef HAVE_BSM
    845 	au_id_t	    auid = AU_NOAUDITID;
    846 #endif /* HAVE_BSM */
    847 #ifdef ALTPRIVSEP
    848 	pid_t aps_child;
    849 #endif /* ALTPRIVSEP */
    850 
    851 	__progname = get_progname(av[0]);
    852 
    853 	(void) g11n_setlocale(LC_ALL, "");
    854 
    855 #ifdef HAVE_SECUREWARE
    856 	(void)set_auth_parameters(ac, av);
    857 #endif
    858 
    859 	init_rng();
    860 
    861 	/* Save argv. */
    862 	saved_argc = ac;
    863 	saved_argv = av;
    864 
    865 	/* Initialize configuration options to their default values. */
    866 	initialize_server_options(&options);
    867 
    868 	/* Parse command-line arguments. */
    869 	while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
    870 		switch (opt) {
    871 		case '4':
    872 			IPv4or6 = AF_INET;
    873 			break;
    874 		case '6':
    875 			IPv4or6 = AF_INET6;
    876 			break;
    877 		case 'f':
    878 			config_file_name = optarg;
    879 			break;
    880 		case 'd':
    881 			if (0 == debug_flag) {
    882 				debug_flag = 1;
    883 				options.log_level = SYSLOG_LEVEL_DEBUG1;
    884 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
    885 				options.log_level++;
    886 			} else {
    887 				(void) fprintf(stderr,
    888 					gettext("Debug level too high.\n"));
    889 				exit(1);
    890 			}
    891 			break;
    892 		case 'D':
    893 			no_daemon_flag = 1;
    894 			break;
    895 		case 'e':
    896 			log_stderr = 1;
    897 			break;
    898 		case 'i':
    899 			inetd_flag = 1;
    900 			break;
    901 		case 'Q':
    902 			/* ignored */
    903 			break;
    904 		case 'q':
    905 			options.log_level = SYSLOG_LEVEL_QUIET;
    906 			break;
    907 		case 'b':
    908 			options.server_key_bits = atoi(optarg);
    909 			break;
    910 		case 'p':
    911 			options.ports_from_cmdline = 1;
    912 			if (options.num_ports >= MAX_PORTS) {
    913 				(void) fprintf(stderr, gettext("too many ports.\n"));
    914 				exit(1);
    915 			}
    916 			options.ports[options.num_ports++] = a2port(optarg);
    917 			if (options.ports[options.num_ports-1] == 0) {
    918 				(void) fprintf(stderr, gettext("Bad port number.\n"));
    919 				exit(1);
    920 			}
    921 			break;
    922 		case 'g':
    923 			if ((options.login_grace_time = convtime(optarg)) == -1) {
    924 				(void) fprintf(stderr,
    925 					gettext("Invalid login grace time.\n"));
    926 				exit(1);
    927 			}
    928 			break;
    929 		case 'k':
    930 			if ((options.key_regeneration_time = convtime(optarg)) == -1) {
    931 				(void) fprintf(stderr,
    932 					gettext("Invalid key regeneration "
    933 						"interval.\n"));
    934 				exit(1);
    935 			}
    936 			break;
    937 		case 'h':
    938 			if (options.num_host_key_files >= MAX_HOSTKEYS) {
    939 				(void) fprintf(stderr,
    940 					gettext("too many host keys.\n"));
    941 				exit(1);
    942 			}
    943 			options.host_key_files[options.num_host_key_files++] = optarg;
    944 			break;
    945 		case 'V':
    946 			client_version_string = optarg;
    947 			/* only makes sense with inetd_flag, i.e. no listen() */
    948 			inetd_flag = 1;
    949 			break;
    950 		case 't':
    951 			test_flag = 1;
    952 			break;
    953 		case 'o':
    954 			if (process_server_config_line(&options, optarg,
    955 			    "command-line", 0) != 0)
    956 				exit(1);
    957 			break;
    958 		case '?':
    959 		default:
    960 			usage();
    961 			break;
    962 		}
    963 	}
    964 	SSLeay_add_all_algorithms();
    965 	channel_set_af(IPv4or6);
    966 
    967 	/*
    968 	 * Force logging to stderr until we have loaded the private host
    969 	 * key (unless started from inetd)
    970 	 */
    971 	log_init(__progname,
    972 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
    973 	    SYSLOG_LEVEL_INFO : options.log_level,
    974 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
    975 	    SYSLOG_FACILITY_AUTH : options.log_facility,
    976 	    !inetd_flag);
    977 
    978 #ifdef _UNICOS
    979 	/* Cray can define user privs drop all prives now!
    980 	 * Not needed on PRIV_SU systems!
    981 	 */
    982 	drop_cray_privs();
    983 #endif
    984 
    985 	seed_rng();
    986 
    987 	/* Read server configuration options from the configuration file. */
    988 	read_server_config(&options, config_file_name);
    989 
    990 	/* Fill in default values for those options not explicitly set. */
    991 	fill_default_server_options(&options);
    992 
    993 	utmp_len = options.lookup_client_hostnames ? utmp_len : 0;
    994 
    995 	/* Check that there are no remaining arguments. */
    996 	if (optind < ac) {
    997 		(void) fprintf(stderr, gettext("Extra argument %s.\n"), av[optind]);
    998 		exit(1);
    999 	}
   1000 
   1001 	debug("sshd version %.100s", SSH_VERSION);
   1002 
   1003 	/* load private host keys */
   1004 	if (options.num_host_key_files > 0)
   1005 		sensitive_data.host_keys =
   1006 		    xmalloc(options.num_host_key_files * sizeof(Key *));
   1007 	for (i = 0; i < options.num_host_key_files; i++)
   1008 		sensitive_data.host_keys[i] = NULL;
   1009 	sensitive_data.server_key = NULL;
   1010 	sensitive_data.ssh1_host_key = NULL;
   1011 	sensitive_data.have_ssh1_key = 0;
   1012 	sensitive_data.have_ssh2_key = 0;
   1013 
   1014 	for (i = 0; i < options.num_host_key_files; i++) {
   1015 		key = key_load_private(options.host_key_files[i], "", NULL);
   1016 		sensitive_data.host_keys[i] = key;
   1017 		if (key == NULL) {
   1018 			error("Could not load host key: %s",
   1019 			    options.host_key_files[i]);
   1020 			sensitive_data.host_keys[i] = NULL;
   1021 			continue;
   1022 		}
   1023 		switch (key->type) {
   1024 		case KEY_RSA1:
   1025 			sensitive_data.ssh1_host_key = key;
   1026 			sensitive_data.have_ssh1_key = 1;
   1027 			break;
   1028 		case KEY_RSA:
   1029 		case KEY_DSA:
   1030 			sensitive_data.have_ssh2_key = 1;
   1031 			break;
   1032 		}
   1033 		debug("private host key: #%d type %d %s", i, key->type,
   1034 		    key_type(key));
   1035 	}
   1036 	if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
   1037 		log("Disabling protocol version 1. Could not load host key");
   1038 		options.protocol &= ~SSH_PROTO_1;
   1039 	}
   1040 	if ((options.protocol & SSH_PROTO_2) &&
   1041 	    !sensitive_data.have_ssh2_key) {
   1042 #ifdef GSSAPI
   1043 		if (options.gss_keyex)
   1044 			ssh_gssapi_server_mechs(&mechs);
   1045 
   1046 		if (mechs == GSS_C_NULL_OID_SET) {
   1047 			log("Disabling protocol version 2. Could not load host"
   1048 			    "key or GSS-API mechanisms");
   1049 			options.protocol &= ~SSH_PROTO_2;
   1050 		}
   1051 #else
   1052 		log("Disabling protocol version 2. Could not load host key");
   1053 		options.protocol &= ~SSH_PROTO_2;
   1054 #endif /* GSSAPI */
   1055 	}
   1056 	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
   1057 		log("sshd: no hostkeys available -- exiting.");
   1058 		exit(1);
   1059 	}
   1060 
   1061 	/* Check certain values for sanity. */
   1062 	if (options.protocol & SSH_PROTO_1) {
   1063 		if (options.server_key_bits < 512 ||
   1064 		    options.server_key_bits > 32768) {
   1065 			(void) fprintf(stderr, gettext("Bad server key size.\n"));
   1066 			exit(1);
   1067 		}
   1068 		/*
   1069 		 * Check that server and host key lengths differ sufficiently. This
   1070 		 * is necessary to make double encryption work with rsaref. Oh, I
   1071 		 * hate software patents. I dont know if this can go? Niels
   1072 		 */
   1073 		if (options.server_key_bits >
   1074 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
   1075 		    SSH_KEY_BITS_RESERVED && options.server_key_bits <
   1076 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
   1077 		    SSH_KEY_BITS_RESERVED) {
   1078 			options.server_key_bits =
   1079 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
   1080 			    SSH_KEY_BITS_RESERVED;
   1081 			debug("Forcing server key to %d bits to make it differ from host key.",
   1082 			    options.server_key_bits);
   1083 		}
   1084 	}
   1085 
   1086 	/* Configuration looks good, so exit if in test mode. */
   1087 	if (test_flag)
   1088 		exit(0);
   1089 
   1090 	/*
   1091 	 * Clear out any supplemental groups we may have inherited.  This
   1092 	 * prevents inadvertent creation of files with bad modes (in the
   1093 	 * portable version at least, it's certainly possible for PAM
   1094 	 * to create a file, and we can't control the code in every
   1095 	 * module which might be used).
   1096 	 */
   1097 	if (setgroups(0, NULL) < 0)
   1098 		debug("setgroups() failed: %.200s", strerror(errno));
   1099 
   1100 	/* Initialize the log (it is reinitialized below in case we forked). */
   1101 	if (debug_flag && !inetd_flag)
   1102 		log_stderr = 1;
   1103 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
   1104 
   1105 #ifdef HAVE_BSM
   1106 	(void) setauid(&auid);
   1107 #endif /* HAVE_BSM */
   1108 
   1109 	/*
   1110 	 * If not in debugging mode, and not started from inetd, disconnect
   1111 	 * from the controlling terminal, and fork.  The original process
   1112 	 * exits.
   1113 	 */
   1114 	if (!(debug_flag || inetd_flag || no_daemon_flag)) {
   1115 #ifdef TIOCNOTTY
   1116 		int fd;
   1117 #endif /* TIOCNOTTY */
   1118 		if (daemon(0, 0) < 0)
   1119 			fatal("daemon() failed: %.200s", strerror(errno));
   1120 
   1121 		/* Disconnect from the controlling tty. */
   1122 #ifdef TIOCNOTTY
   1123 		fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
   1124 		if (fd >= 0) {
   1125 			(void) ioctl(fd, TIOCNOTTY, NULL);
   1126 			(void) close(fd);
   1127 		}
   1128 #endif /* TIOCNOTTY */
   1129 	}
   1130 	/* Reinitialize the log (because of the fork above). */
   1131 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
   1132 
   1133 	/* Initialize the random number generator. */
   1134 	arc4random_stir();
   1135 
   1136 	/* Chdir to the root directory so that the current disk can be
   1137 	   unmounted if desired. */
   1138 	(void) chdir("/");
   1139 
   1140 	/* ignore SIGPIPE */
   1141 	(void) signal(SIGPIPE, SIG_IGN);
   1